text:
Q: How to get images from android camera in RGB? I want to develop a machine learning program using Tensorflow, OpenCV and Android. I already trained my model and uploaded it to my mobile, but I am facing problems when I want to feed the image taken with camera. The problem is that the camera is taking pictures with the format RGBa (which has 4 channels) and my CNN input has only 3 channels (the shape looks like this 100, 100, 3). Also I want to develop the app that I will make inference on each frame, without the necessity to press a button or something like that. I should say that I am a newbie in Android development and this app would be only to provide a demo to my bachelor thesis.
My network input:
    X = tf.placeholder(tf.float32, shape=[1, height, width, channels], name="X")

where height = width = 100 and channels = 3
and my android code looks something like this:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        javaCameraView = (JavaCameraView)findViewById(R.id.java_camera_view);
        javaCameraView.setVisibility(SurfaceView.VISIBLE);
        javaCameraView.setCvCameraViewListener(this);
        inferenceInterface = new TensorFlowInferenceInterface(getAssets(), MODEL_FILE);

    }

    @Override
    public Mat onCameraFrame(Mat inputFrame) {
        mRgba = inputFrame;
        Mat resizeimage = new Mat(100, 100, CvType.CV_32SC4);
        Imgproc.resize( inputFrame.clone(), resizeimage, new Size(100, 100));
        MatOfInt rgb = new MatOfInt(100, 100, CvType.CV_32SC3);
        resizeimage.convertTo(rgb,CvType.CV_32SC3);
        float[] rgbFloat = new float[(int)(rgb.total()*rgb.channels())];
        rgb.get(0,0,rgbFloat);
        inferenceInterface.feed(INPUT_NODE, rgbFloat, INPUT_SIZE);

        inferenceInterface.run(new String[] {OUTPUT_NODE});
        int size = classes.length;
        float resu[] = new float[size];
        for(int i =0;i< size;i++){
            resu[i] = 0;
        }
        inferenceInterface.fetch(OUTPUT_NODE, resu);
        Log.d("result", convert(resu));
        return mRgba;
    }

How should I proceed?


text:
Q: is it *always* wrong to use an `if`-`else` structure inside a Durable Orchestration? Is the following if-else structure too non-deterministic for an Azure Durable Functions orchestration?:
[FunctionName(FUNC_NAME_ORCH0)]
public static async Task<string> RunPlayerYouTubeOrchestration(
    [OrchestrationTrigger] DurableOrchestrationContext orchestrationContext,
    ILogger log)
{
    if (!orchestrationContext.IsReplaying)
        log?.LogInformation(GetInvocationMessage(orchestrationContext, FUNC_NAME_ORCH0));

    var hasExhaustedPartitions = await orchestrationContext
        .CallActivityAsync<bool>(FUNC_NAME_ORCH_FUNC0, null);

    if (!hasExhaustedPartitions)
    {
        var jsonBlobs = await orchestrationContext
            .CallActivityAsync<string[]>(FUNC_NAME_ORCH_FUNC1, null);

        var tasks = new Task[jsonBlobs.Length];
        for (int i = 0; i < jsonBlobs.Length; i++)
        {
            var json = jsonBlobs[i];
            tasks[i] = orchestrationContext.CallActivityAsync(FUNC_NAME_ORCH_FUNC2, json);
        }

        if (!orchestrationContext.IsReplaying)
            log?.LogInformation($"{FUNC_NAME_ORCH0}: fan-out starting...");

        await Task.WhenAll(tasks);
    }
    else
    {
        var orc1InstanceId = await orchestrationContext
             .CallSubOrchestratorAsync<string>(FUNC_NAME_ORCH1, null);
        if (!orchestrationContext.IsReplaying)
            log?.LogInformation($"{FUNC_NAME_ORCH1} completed with instance ID `{orc1InstanceId}`.");

        var orc2InstanceId = await orchestrationContext
            .CallSubOrchestratorAsync<string>(FUNC_NAME_ORCH2, null);
        if (!orchestrationContext.IsReplaying)
            log?.LogInformation($"{FUNC_NAME_ORCH2} completed with instance ID `{orc2InstanceId}`.");

        if (!orchestrationContext.IsReplaying)
            log?.LogInformation($"{FUNC_NAME_ORCH_FUNC3}: calling `{PlayerYouTubeIndicesActivity.ProcedureNameResetYouTubePartitionInfoAsync}`...");
        await orchestrationContext
            .CallActivityAsync(FUNC_NAME_ORCH_FUNC3,
                PlayerYouTubeIndicesActivity.GetInput(
                    PlayerYouTubeIndicesActivity.ProcedureNameResetYouTubePartitionInfoAsync));
    }

    return orchestrationContext.InstanceId;
}

Will hasExhaustedPartitions not work well with replay? When yes, what must done instead?

A: There is nothing wrong with if/else when the evaluated condition is deterministic. In your case, the FUNC_NAME_ORCH_FUNC0 function will execute once, the result will be recorded in the history, and the recorded result will be used to initialize the hasExhaustedPartitions variable on all subsequent replays, so the condition is deterministic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java 8 - Object method reference executes method of null reference Please see my code below. I have a functional interface IFace with a method. I'm creating an implementation using Method reference from a class instance of Test. Can anyone tell me how the interface still refers to the instance method even if the reference is nullified? or reference is changed...?
public class Test {
    private int intVar;

    public Test() {
        intVar = 123;
    }

    public Test(int intVar) {
        this.intVar = intVar;
    }

    public void myInstanceMethod() {
        System.out.println("Hello from instance: " + intVar);
    }

    public static void main(String[] args) {
        Test t = new Test();

        IFace i = t::myInstanceMethod;
        i.method();  // Hello from instance: 123

        t = null; // Nullifying the reference
        i.method(); //  Hello from instance: 123
                    // Why still executing the method if reference is nullified?????

        t = new Test(456);
        i.method(); // Hello from instance: 123
                    // Why not Hello from instance: 456 ??????
    }

    static interface IFace {
        void method();
    }
}

A: In a sense, the question is similar to asking why printing b does not output null in the following program:
String a = "abc";
String b = a;
a = null;

System.out.println(b);

When IFace i = t::myInstanceMethod; finishes running, i has captured a reference to the object that t points to at this time. That reference is independent from the variable t. Look at it like i, the method reference, has its own variable pointing to the same object.

A: The memory is not freed when you nullified the reference. It's freed when ALL references are gone. By passing method reference you created new reference to object itself, so the ref count is 2 at that point, i.e. the i holds reference to t underneath


text:
Q: Dissecting an ERB to HAML conversion example Directly rom the HAML tutorial:
<div class='item' id='item<%= item.id %>'>
  <%= item.body %>
</div>

and the answer is
.item{:id => "item#{item.id}"}= item.body

I understood the reason for first .item, Ok it is a class so we declare it that way.
I also understood the hash, Ok when we have attributes we create a hash for it.
The part I couldn't understand how it is converted is  "item#{item.id}"
Shouldn't be some sort of "=" sign somewhere? because it was saying when we want to calculate Ruby code use that "=" ?

A: {:id => "item#{item.id}"} is evaluated as hash in ruby code by Haml, so you don't need =


text:
Q: python pygame how to debounce a button? so im building a pi based robot.
It uses a ps3 controller for input. When the X button is pressed, it takes a photo. For some reason, it takes around 5 shots at a time. Is there a way to bounce the input so it only recognises one press?
I'm assuming it's registering multiple presses each time... Part of the code is attached, but I must state most of it is used from piborg.org
joystick = pygame.joystick.Joystick(0)

button_take_picture = 14            # X button

while running:
    # Get the latest events from the system
    hadEvent = False
    events = pygame.event.get()
    # Handle each event individually
    for event in events:
        if event.type == pygame.QUIT:
            # User exit
            running = False
        elif event.type == pygame.JOYBUTTONDOWN:
            # A button on the joystick just got pushed down
            hadEvent = True
        elif event.type == pygame.JOYAXISMOTION:
            # A joystick has been moved
            hadEvent = True
        if hadEvent:
            if joystick.get_button(button_take_picture):
                take_picture()

A: What seems to be happening is that the X button stays down for multiple frames. Some other events might happen during this time, causing a call to take_picture() in your code for every frame. To fix this, you can either call take_picture() only on JOYBUTTONUP (when the button is released), or move the if joystick.get_button(button_take_picture) part to inside the pygame.JOYBUTTONDOWN section.
Alternatively, you could use another variable to indicate whether the picture was already taken, like this:
picture_was_taken = False

while running:
     hadEvent = False
     events = pygame.event.get()
     for event in events:
       ...
       if event.type == pygame.JOYBUTTONUP:
           if not joystick.get_button(button_take_picture)
               picture_was_taken = False
       ...
       if hadEvent:
           if joystick.get_button(button_take_picture) and not picture_was_taken:
               take_picture()
               picture_was_taken = True


text:
Q: SQL Syntax with regards to SELECT I keep getting an error saying that a specific column, doesn't exist for b.BookCode But I am fully aware that it does exist! I just wanted to make sure after staring at this for so long that I am not missing something obvious.
SELECT AuthorLast, AuthorFirst, OnHand, Title
FROM (Inventory i, Author a, Book b)
WHERE (i.BookCode = b.BookCode AND b.AuthorNum = a.AuthorNum);

I'm very new to SQL so I'm unsure if my syntax is off, Also do I need parentheses around the columns that I mentioned in SELECT. I had parentheses around them at first and got an error and was confused as to why.
Thanks!

A: Minimally, you should change this to:
SELECT AuthorLast, AuthorFirst, OnHand, Title
FROM Inventory i, Author a, Book b
WHERE i.BookCode = b.BookCode AND
      b.AuthorNum = a.AuthorNum;

... and this is assuming that the columns in the SELECT part of your select statement are not ambiguous (i.e., found in more than one of the tables in the FROM part).

A: You are using the old join syntax, you should use INNER JOIN instead.
SELECT AuthorLast, AuthorFirst, OnHand, Title
FROM Inventory i
INNER JOIN Author a
    USING (BookCode)    -- You can also use ON, but USING remove the ambiguous columns
INNER JOIN Book b
    USING (AuthorNum);   -- Same thing here

If you get an error saying one column doesn't exist, well, you should double check it. MySQL isn't lying to you for the sake of it! You might do your query on an outdated database, for instance.


text:
Q: Adding a PivotItem-derived class to a Pivot throws an exception UWP, C#. I have a Pivot control. I'm trying to add a PivotItem-derived object to the Items collection. It throws a COMException:

No installed components were detected.
Cannot apply a Style with TargetType 'Windows.UI.Xaml.Controls.PivotItem' to an object of type 'Windows.UI.Xaml.Controls.ContentControl'.

The HRESULT is 0x800f1000, if that matters.
Reproduces on a clean example. This works:
MyPivot.Items.Insert(1, new PivotItem() { Header = "Boo" });

And this exceptions:
MyPivot.Items.Insert(1, new BooItem() { Header = "Boo" });

Where BooItem is defined as
public class BooItem : PivotItem
{
    public BooItem(){}
}

If specified via XAML, the PivotItem-derived classes work in a Pivot. My other items in the app are all like that.
The whole codebase is a port from Windows Phone Silverlight (targeting WP8.0), it worked over there. Now, UWP is not quite the same, but still, you'd expect...
EDIT: you can add the item as invisible. The header will still appear, but the contents will be, well, invisible. Trying to make it visible causes the same exception.
There's an interesting line in the Pivot docs:

Any item you add to the Pivot that is not explicitly a PivotItem is implicitly wrapped in a PivotItem.

Do objects that derive PivotItem count?

EDIT2: reproduced on a blank project. The main page XAML goes:
<Page
    x:Class="UWTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWTest"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Pivot x:Name="ThePivot">
        <PivotItem Header="Foo">
            <StackPanel>
                <Button Content="Go" Click="OnGo"/>
            </StackPanel>
        </PivotItem>

    </Pivot>
</Page>

The code behind goes:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace UWTest
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void OnGo(object sender, RoutedEventArgs e)
        {
            ThePivot.Items.Insert(1, new BooItem() { Header = "Boo" });
        }
    }
    public class BooItem : PivotItem
    {
        public BooItem() { }
    }
}

Visual Studio 2015 update 3, target version 14393, min version the same.
EDIT: reproduced on another machine. Visual Studio 2015, brand new Unversal Windows C# project. Windows 10 Pro, v 1803 (build 17134.648).


text:
Q: Efficient double integration in C with GSL Consider the double integral
I = int int [(a^k)*b] da db

where we want to integrate for a between [0,1] and b between [0,1] and k is some constant. I am using the GSL numerical integration library but have a memory allocation issue.
My code is as follows
#include <stdlib.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_integration.h>

double innerIntegrand(double a, void *params) {
    double *cast_params = (double *) params;
    double b = params[0];
    double k = params[1];

    return pow(a,k)*b;
}

I can then evaluate the inner integral for a given b (to get an outer integrand) as follows
double outerIntegrand(double b, void *params) {
    // params = {holder for double b, k}
    double *cast_params = (double *) params;
    cast_params[0] = b;

    // Allocate integration workspace
    gsl_integration_workspace *giw = gsl_integration_workspace_alloc(100);

    // Create GSL function
    gsl_function F;
    F.function = &innerIntegrand;
    F.params = params;

    // Initialise values to put the result in
    double result;
    double abserror;

    // Perform integration
    gsl_integration_qag(&F, 0, 1, 0.001, 0.001, 100, 1, giw, &result, &abserror);

    // Free the integration workspace
    gsl_integration_workspace_free(giw);

    // Return result
    return result
}

Note however I have to allocate and free the integration workspace within the function. This means it is done many times when evaluating the final integration function
double Integral(double k) {
    // Create params
    double *params = malloc(2*sizeof(double));
    params[1] = k;

    // Allocate integration workspace
    gsl_integration_workspace *giw = gsl_integration_workspace_alloc(100);

    // Create GSL function
    gsl_function F;
    F.function = &outerIntegrand;
    F.params = params;

    // Initialise values to put the result in
    double result;
    double abserror;

    // Perform integration
    gsl_integration_qag(&F, 0, 1, 0.001, 0.001, 100, 1, giw, &result, &abserror);

    // Free the integration workspace
    gsl_integration_workspace_free(giw);

    // Free memory
    free(params);

    // Return result
    return result
}

Ideally what I want is two global gsl_integration_workspace variables, one for the integral in outerIntegrand and another for the integral in Integral. However when I try to declare them as global values I receive a initializer element is not constant error.
Can anyone see a way to do this double integral without the repeated memory allocation and freeing? I was thinking we could also pass the workspace in through the params argument although it then starts to get quite messy.

A: I managed to build a decently looking program in C++ for double integration based on GSL, avoiding repeated allocations in a clean way. I used this well known function to play:
f(x,y)=exp(-x*x-y*y)

integrating it over all the plane (the result, pi, can easily be obtained by switching to polar coordinates).
It is trivial to modify it and add parameters by lambda capture.
#include <iostream>
#include <gsl/gsl_integration.h>

// Simple RAII wrapper
class IntegrationWorkspace {
  gsl_integration_workspace * wsp;

  public:
  IntegrationWorkspace(const size_t n=1000):
    wsp(gsl_integration_workspace_alloc(n)) {}
  ~IntegrationWorkspace() { gsl_integration_workspace_free(wsp); }

  operator gsl_integration_workspace*() { return wsp; }
};

// Build gsl_function from lambda
template <typename F>
class gsl_function_pp: public gsl_function {
  const F func;
  static double invoke(double x, void *params) {
    return static_cast<gsl_function_pp*>(params)->func(x);
  }
  public:
  gsl_function_pp(const F& f) : func(f) {
    function = &gsl_function_pp::invoke; //inherited from gsl_function
    params   = this;                     //inherited from gsl_function
  }
  operator gsl_function*(){return this;}
};

// Helper function for template construction
template <typename F>
gsl_function_pp<F> make_gsl_function(const F& func) {
  return gsl_function_pp<F>(func);
}

int main() {
  double epsabs = 1e-8;
  double epsrel = 1e-8;
  size_t limit = 100;
  double result, abserr, inner_result, inner_abserr;

  IntegrationWorkspace wsp1(limit);
  IntegrationWorkspace wsp2(limit);

  auto outer = make_gsl_function( [&](double x) {
    auto inner = make_gsl_function( [&](double y) {return exp(-x*x-y*y);} );
    gsl_integration_qagi(inner, epsabs, epsrel, limit, wsp1,
                         &inner_result, &inner_abserr);
    return inner_result;
  } );
  gsl_integration_qagi(outer, epsabs, epsrel, limit, wsp2, &result, &abserr);

  std::cout << result << std::endl;
}

A: This looks weird:
double innerIntegrand(double a, void *params) {
    double *cast_params = (double *) params;
    double b = params[0];
    double k = params[1];

Is it correct to expect that (void *)param[0] and [1] correctly map to double b and k? How is proper offset to be calculated between void and double types?
Here some hints (do not expect working code below).
You may try something like:
double b = (double )*param;
double k = (double )*(param + sizeof(double));

But probably it would be better and safer to declare:
 double Integral(double k) {
     struct p {
         double b;
         double k;
     } params;
     params.k = k;
 ...
    gsl_function F;
   F.function = &outerIntegrand;
   F.params = &params;

...
double outerIntegrand(double b, void *params) {
   (struct p)params->b = b;

double innerIntegrand(double a, void *params) {
    double b = (struct p)params->b;
    double k = (struct p)params->k;

You may want to typdef the "struct p".


text:
Q: Microsoft Diagnostics Runtime crash.dmp analysis (C#) I'm trying to read in a crash.dmp using the functionality in Microsoft.Diagnostics.Runtime .NET componenet (also known as ClrMD).
I have a crash.dmp in a known location (in a string called pathToFile) so that's not the issue.  The rest of the code looks like this.
DataTarget dataTarget = DataTarget.LoadCrashDump(pathToFile);
ClrInfo clrInfo = dataTarget.ClrVersions[0];
string dacLocation = clrInfo.TryGetDacLocation();

When testing this code, I get the following error in the command window:
Error processing directory: System.ArgumentOutOfRangeException.  Index was out of range. Must be non-negative and less than the size of the collection.  Parameter name: index.
I'm assuming it's something to do with the ClrVersions[0] bit but can't for the life of me pin it down.
Any help would be appreciated.
Current Status
When running the following command (which fails)
ClrRuntime rt = dataTarget.CreateRuntime("path\to\mscordawks.dll");

I receive the following error in cmd
mismatched architecture between this process and the dac
Cheers
Anyone?

A: If the TryGetDacLocation succeeded then you should be able to do
ClrRuntime rt = dataTarget.CreateRuntime(dacLocation);
so you get the correct dacLocation.
Was the dump you are analysing generated on same machine where you are analysing it?
Also what are the bitnesses of the process the dump was generated from, the process in which the CLRMD code is running and the debugger utility used to generate the dump?
Generally you want to be matching the bitnesses all round (x86/x64).
Doug

A: I was having the same issue reading a dump file generated on the same computer.  There were two problems, first bitness (should have been 64, was running in 32) and the second harder problem that the proper DLL could not be located.  To fix the second problem I created a method that tries all of the properly named DLLs it can find:
private static ClrRuntime GetRuntime(DataTarget target)
{
    ClrInfo version = target.ClrVersions[0];

    string dacLocation = version.TryGetDacLocation();

    // If we don't have the dac installed, we will use the long-name dac in the same folder.
    if (!string.IsNullOrEmpty(dacLocation))
        dacLocation = version.DacInfo.FileName;

    try  // try the one it should be
    {
        return target.CreateRuntime(dacLocation);
    }
    catch (Exception e)
    {
    }

    // can't find the one it should be, try'em all
    string fileName = "mscordacwks.dll";
    string[] searchLocations = new[]
    {
        @"C:\Windows\Microsoft.NET\",
        @"C:\Windows\winsxs\"
    };

    foreach (string searchLocation in searchLocations)
    {
        foreach (string file in Directory.GetFiles(searchLocation, fileName, SearchOption.AllDirectories))
        {
            try
            {
                return target.CreateRuntime(file);
            }
            catch (Exception e)
            {
            }
        }
    }
    throw new Exception("No found valid runtimes");
}

A: I followed this artificial to get the mscordacwks.dll when dealing with platform differences between where the dmp file was taken and the machine doing the analysis.
http://chentiangemalc.wordpress.com/2014/04/16/obtaining-correct-mscordacwks-dll-for-net-windbging/#comment-3380
and followed the steps including renaming the file to include the architecture and version information.
After that I just http://chentiangemalc.wordpress.com/2014/04/16/obtaining-correct-mscordacwks-dll-for-net-windbging/#comment-3380ut the full path of the file as dacLocation in the script.
After that it worked!
I suspect that putting it on the path could be made to work.


text:
Q: execute grep regular expression involving `|` using ssh on remote host I am trying to run grep command involving regular expression '|' on a server using ssh.
ssh rpatil@192.168.1.5 grep -E "GapEvent|GapFilled" "$logFile" > $server-$testName.log
now '|' in the command is being treated as pipe and error "no command GapFilled" is being raised.
I tried 'GapEvent|GapFilled' or '(GapEvent|GapFilled)'
so how should regular expression "GapEvent|GapFilled" should be written so that | is not treated as pipe?

A: You need two levels of quotes since the command line is evaluated twice (once locally when ssh is executed and once when grep is executed on the remote side). You can use one of these patterns:
  "'a|b'"
  '"a|b"'
  "\"a|b\""

A: Escape the | like this  \|
grep -E "GapEvent\|GapFilled" "$logFile" file

A: Simply use two expressions:
grep -E -e "GapEvent" -e "GapFilled" "$logFile"

-E may no longer be needed here. -F may also be a preference.


text:
Q: Some exported symbols disappear after creating a dynamic framework with the ios_framework rule I am facing quite a strange situation trying to build a mixed-language dynamic iOS framework with Bazel.
The source code of the framework consists of *.c, *.cpp, *.m, *.mm, *.h, *.hpp files.
My first naive attempt was to declare a single objc_library rule referencing all the sources. That failed with an error message reading something about conflicting rules. Then I declared four distinct objc_library rules for *.m, *.mm, *.c, and *.cpp files respectively, and then referenced all these four rules as dependencies for the final ios_framework rule.
At this point, everything compiled and linked just fine (barring several compiler warnings which were expected). However, now the black magic begins:

*

*The static library resulting from compiling ObjectiveC++ sources does contain all the necessary symbols (verified with the "nm" tool)

*The .apple_binary_lipobin file resulting from the linking phase does not contain symbols from ObjectiveC++ sources

I believe I carefully went through the command lines used for compiling and linking, both for Bazel and xcodebuild.
The only anomalies I was able to spot:

*

*xcodebuild passes a -single_module argument when linking, while Bazel cross tool does not.

*Bazel cross tool adds '-stdlib=libc++' '-std=gnu++11' command line arguments when invoking wrapped_clang_pp during linking, while xcodebuild does not pass these arguments. I guess Bazel does this because there're these lines in the default Apple CROSSTOOL:
action_config {
  config_name: "objc++-executable"
  action_name: "objc++-executable"
  tool {
    tool_path: "wrapped_clang_pp"
    execution_requirement: "requires-darwin"
  }
  flag_set {
    flag_group {
    flag: "-stdlib=libc++"
    flag: "-std=gnu++11"
  }
but I am not sure if these flags are really needed when invoking the linker.
I must admit I've run out of ideas except for trying to patch the CROSSTOOl file to make it behave as close as xcodebuild as possible.
Please help.

A: Can you try adding alwayslink = 1 to the objc_library target containing the C++ symbols? The linker is deadstripping the C++ symbols as they are not being referenced anywhere in the binary.


text:
Q: Scala - Case Sequence I just read about case sequence as partial functions and the syntax is a little bit strange.
For example
def test: Int => Int = {
  case 1 => 2
  case 2 => 3
  case _ => 0
}

I would expect that test has no arguments and would return a function of type Int => Int
But after some testing it seems that it takes an int as an argument and returns an int, so I rewrote it to...
def test1(i: Int): Int =
  i match {
    case 1 => 2
    case 2 => 3
    case _ => 0
  }

Are test and test1 equal?

A: They are not equal. test is a method that returns a Function1[Int,Int] and test1 is a method that takes an Int and returns an Int. This is also completely unrelated to the pattern matching expression.

A: The former code does return a function of type Int => Int.
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

def test: Int => Int = {
case 1 => 2
case 2 => 3
case _ => 0
}

// Exiting paste mode, now interpreting.

test: Int => Int

scala> test
res0: Int => Int = <function1>

scala> test.apply(1)
res1: Int = 2

Perhaps what is confusing is that apply can be called directly:
scala> test(1)
res2: Int = 2

A: test is a function of type "Int => Int"
test1 is a method that uses a partial function (the match expression) internally.
So they are not equal.
If you want to check Types use the REPL:
:type test
Int => Int

:type test1 _
Int => Int


text:
Q: Is there a Visual Studio C# equivalent of the Visual Studio C++ Makefile project In Visual C++ inside Visual Studio, one of the project subtypes is a "Makefile Project".
But there doesn't seem to be an equivalent for Visual C# inside Visual Studio?

BTW, a Makefile project is:

If you have a project that you build from the command line with a
  makefile, then the Visual Studio development environment will not
  recognize your project. To open and build your project using Visual
  Studio, first create an empty project containing the appropriate build
  settings using the Makefile Project Wizard. You can then use this
  project to build your project from the Visual Studio development
  environment.
The project displays no files in Solution Explorer. The project
  specifies the build settings, which are reflected in the project's
  property page.

A: The equivalent of make in Visual Studio world is msbuild. Visual Studio does not use make. .csproj, .vbproj etc. are input files for msbuild. You can do pretty much the same stuff in them as in conventional makefiles, including command line building, custom targets etc.

A: There's nothing C++-specific about the Makefile project type; it just runs a command line.  It's just that it's listed along with the Visual C++ project types. You can add one to a solution that otherwise contains nothing but C# projects.
Alternatively, you could set up a pre-build step in your C# project that directly runs nmake, msbuild or even NAnt.

A: Msbuild is what is used to build your projects when you hit the Play button. Personally I like NAnt + NantContrib it was easier for me to pick up and start using right away. For all new projects I use tree surgeon this tool creates a default build script and proper build tree with testing project and code coverage report.


text:
Q: Why my CNN returns always the same result? I'm trying to build a CNN that classify object in 3 main classes.The three objects consist of a lamborghini , cylinder head and a piece of plane. My data set consists of 6580 images , almost 2200 image for each class.You can see my dataset on google drive dataset.
The architecture of my CNN is AlexNet , but I've modified the output of fully connected layer 8 from 1000 to 3.
I have used these settings for training
test_iter:1000
test_interval:1000
base_lr:0.001
lr_policy:"step"
gamma:0.1
stepsize:2500
max_iter:40000
momentum:0.9
weight_decay:0.0005

But , the problem is when I deploy my model after training the result is always the following {'prob': array([[ 0.33333334,  0.33333334,  0.33333334]], dtype=float32)}.
the code below , is my script to load the model and output the vector of probabilities.
import numpy as np
import matplotlib.pyplot as plt
import sys
import caffe
import cv2

MODEL_FILE ='deploy_ex0.prototxt'
PRETRAINED='snapshot_ex0_1_model_iter_40000.caffemodel'

caffe.set_mode_cpu()
net = caffe.Net(MODEL_FILE, PRETRAINED, caffe.TEST)

#preprocessing

transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})

#mean substraction

mean_file = np.array([104,117,123])
transformer.set_mean('data', mean_file)

transformer.set_transpose('data', (2,0,1))
transformer.set_channel_swap('data', (2,1,0))
transformer.set_raw_scale('data', 255.0)

#batch size
net.blobs['data'].reshape(1,3,227,227)

#load image in data layer

im=cv2.imread('test.jpg', cv2.IMREAD_COLOR)
img =cv2.resize(im, (227,227))

net.blobs['data'].data[...] = transformer.preprocess('data', img)

#compute

out=net.forward()

print out

I am wondering why I have a result like this ? would you help me to debug my CNN ?
Also, after training I got these results
I0421 06:56:12.285953  2224 solver.cpp:317] Iteration 40000, loss = 5.06557e-05
I0421 06:56:12.286027  2224 solver.cpp:337] Iteration 40000, Testing net (#0)
I0421 06:58:32.159469  2224 solver.cpp:404]     Test net output #0: accuracy = 0.99898
I0421 06:58:32.159626  2224 solver.cpp:404]     Test net output #1: loss = 0.00183688 (* 1 = 0.00183688 loss)
I0421 06:58:32.159643  2224 solver.cpp:322] Optimization Done.
I0421 06:58:32.159654  2224 caffe.cpp:222] Optimization Done.

Thank you
EDIT AFTER ANSWER OF 11 MAY :
I used a simple model 1 conv , 1 reul , 1 pool and 2 fully connected layers.. The code below is the architecture specification :
name:"CNN"
layer {
  name: "convnet"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
    mirror:true
    crop_size:227
    mean_value:87.6231
    mean_value:87.6757

    mean_value:87.1677
    #mean_file:"/home/jaba/caffe/data/diota_model/mean.binaryproto"
  }
  data_param {
    source: "/home/jaba/caffe/data/diota_model/train_lmdb"
    batch_size: 32
    backend: LMDB
  }
}

layer {
  name: "convnet"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    mirror:true
    crop_size:227
    mean_value:87.6231
    mean_value:87.6757

    mean_value:87.1677
    #mean_file:"/home/jaba/caffe/data/diota_model/mean.binaryproto"
  }
  data_param {
    source: "/home/jaba/caffe/data/diota_model/val_lmdb"
    batch_size: 20
    backend: LMDB
  }
}

layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param {
    lr_mult: 1
  }
  param {
    lr_mult: 2
  }
  convolution_param {
    num_output: 20
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}

layer {
  name: "relu1"
  type: "ReLU"
  bottom: "conv1"
  top: "conv1"
}

layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}

layer {
  name: "ip1"
  type: "InnerProduct"
  bottom: "pool1"
  top: "ip1"
  param {
    lr_mult: 1
  }
  param {
    lr_mult: 2
  }
  inner_product_param {
    num_output: 300
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}

layer
{
   name:"ip2"
   type:"InnerProduct"
   bottom:"ip1"
   top:"ip2"
   param
   {
    lr_mult:1
   }
   param
   {
    lr_mult:2
   }
   inner_product_param
   {
    num_output: 3
        weight_filler {
          type: "xavier"
        }
        bias_filler {
          type: "constant"
        }
   }

}
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip1"
  bottom: "label"
  top: "accuracy"
  include {
    phase: TEST
  }
}

layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip1"
  bottom: "label"
  top: "loss"
}

I trained this CNN for 22 epochs and I got accuracy 86 %. For the solver parameters I used :
net: "/home/jaba/caffe/data/diota_model/simple_model/train_val.prototxt"
test_iter: 50
test_interval: 100
base_lr: 0.00001
momentum: 0.9
weight_decay: 0.0005
lr_policy: "inv"
gamma: 0.0001
power: 0.75
display: 100
max_iter: 3500
snapshot: 100
snapshot_prefix: "/home/jaba/caffe/data/diota_model/simple_model/snap_shot_model"
solver_mode: GPU

Now , when I deploy the model it does not return the same vector of probabilities. But , there is one issue , is when I loaded the model and I tested it on validation_lmdb folder , I did not get the same accuracy value , I got almost 56% .
I used the script below to calculate the accuracy :
import os
import glob
#import cv2
import caffe
import lmdb
import numpy as np
from caffe.proto import caffe_pb2

MODEL_FILE ='deploy.prototxt'
PRETRAINED='snap_shot_model_iter_3500.caffemodel'

caffe.set_mode_cpu()
#load_model

net = caffe.Net(MODEL_FILE, PRETRAINED, caffe.TEST)

#load input and configure preprocessing

#mean_file = np.array([104,117,123])

transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
#transformer.set_mean('data', mean_file)
transformer.set_transpose('data', (2,0,1))
transformer.set_channel_swap('data', (2,1,0))
transformer.set_raw_scale('data', 255.0)

#fixing the batch size

net.blobs['data'].reshape(1,3,227,227)

lmdb_env=lmdb.open('/home/jaba/caffe/data/diota_model/val1_lmdb')

lmdb_txn=lmdb_env.begin()

lmdb_cursor=lmdb_txn.cursor()

datum=caffe_pb2.Datum()

correct_predictions=0

for key,value in lmdb_cursor:

    datum.ParseFromString(value)

    label=datum.label
    data=caffe.io.datum_to_array(datum)

    image=np.transpose(data,(1,2,0))

    net.blobs['data'].data[...]=transformer.preprocess('data',image)

    out=net.forward()
    out_put=out['prob'].argmax()
    if label==out_put:
    correct_predictions=correct_predictions+1

print 'accuracy :'
print correct_predictions/1002.0

I changed the size of the data set 1002 for testing and 4998 for learning .
Would you give me some suggestions to solve the issue ?
Thanks !

A: I think I see two distinct problems, different forms of over-fitting.  WIth 85% of your 6580 images for training, you have 5593 in training, 987 in testing.
ONE
40000 iterations * (256 images/iteration) * (1 epoch/5593 images) ~= 1831 epochs.
On the ILSVRC data set (1.28M images), AlexNet trains for only 40-50 epochs (depending on scale-out).
Your model finished with a loss of effectively 0 and got only 1 photo wrong in the entire testing set.
TWO
AlexNet's widths (filters per layer) are tuned for the 1000 classes and myriad features of the ILSVRC data set.  You haven't scaled it down for your data.  Layer 5 broadens to 4096 filters: that's nearly one for each image.  Where ILSVRC trains Alexnet to recognize features such as a feline face, one side of a wheeled vehicle, etc. -- your model will train to recognize a dark blue Lambourghini from an angle of 30 degrees off front, 8 degrees above horizontal, with grass in the background and a poplar tree in the background on the driver's side.
In other words, your trained AlexNet fits the training data set like a pour-on plastic shell.  It's not going to fit anything except the initial data set.
I'm mildly surprised that it doesn't do a little better on other autos, other cylinder heads, and plane pieces.  However, I've seen enough over-fitted models that had effectively random output.

First, reduce the length of training.  Second, try reducing the num_output size of each layer.

EDIT AFTER OP's COMMENTS 11 MAY
Yes, you have to reduce the number of kernels/filters/outputs in each layer.  Layer 5, in particular, has 4K filters, which means that the network can allocate almost 1 filter per photo in your data set.  This does not make for effective learning: instead of having a handful of filters that learn features of gaskets, you have over 1000 filters, each learning one very specific feature of a particular gasket photo.
AlexNet, GoogleNet, ResNet, VGG, et alia were all built and tuned for a problem of general discrimination of still images over a wide variety of objects.  You can certainly use the general concepts, but they are not good topologies to use for a problem that is so much smaller and better defined.


text:
Q: Nested attribute validations not being called I've been struggling with this for some time now. I'm just trying to get nested attributes to validate on Rails 3.2 with no luck. It's like it's just completely ignoring validations for the nested attributes. Below is an example validation that's not working:
class Invoice < ActiveRecord::Base
  validates :description, :presence => true
  belongs_to  :client_branch
  has_many    :invoice_items

  accepts_nested_attributes_for :invoice_items, :allow_destroy => true
end

class InvoiceItem < ActiveRecord::Base
  belongs_to  :invoice
  validate :thisisatest

  def thisisatest
    errors.add(:qty, 'QTY NOT VALIDATING TEST.')
  end
end

When saving an Invoice with some InvoiceItems, it saves it successfully, even though the custom validation is clearly adding an error for the :qty attribute. Is there something I should be adding to my models for nested validation to work, or am I perhaps missing something else?

A: Actually, I'm being daft. I changed the model name, along with all references to it and it took me this long to miss one reference still pointing to the old model in the javascript. Thus, items being added dynamically weren't named correctly, causing the validation not to trigger. :/


text:
Q: Combine String with Variable Twig I'm new to twig and i am trying to combine a variable and a string and send it too a function, without much look,
{{key "/uploads"|app }}

here is code, i've tried
{{key ~ "/uploads"|app }}

{{"`key`/uploads"|app }}

Any suggestions?

A: You simply add parentheses like this
{{ ( key ~ "/uploads" ) |app }}


text:
Q: Cursor, Sqlite. How do I get the row for ID? How do I get the row for ID ?
I try so it is impossible .
case R.id.buttonTest: {

            String[] projection = {DbTest.NAME};
            String selection = "_id = ?";
            String[] selectionArgs = { String.valueOf(1) };
             Cursor c = sqdb.query(DbTest.TABLE_NAME,projection,selection,selectionArgs ,null,null,null);
             if (c.moveToFirst()) {
                    String name = c.getString(c.getColumnIndex(DbTest.NAME));
                    textView1.setText(name);
                    }
            }

            break;


text:
Q: Error with code to make bufferedImage smaller I have an image (147 KB), and I want to downsize it to under 100KB. The code below attempts to do this, however when the image comes out on the other side, the widht and height are scaled down, but the disk space on the image goes from 147 to 250!  It's supposed to get smaller not higher...
Can you please tell me why this code isn't doing this?
Thanks
//Save image
        BufferedImage resizeImagePng = resizeImage(originalImage, type, newLargeImageLocation);

    //Resize and save
    ImageIO.write(resizeImagePng, "png", new File(newSmallImageLocation));

//Create new image
    private static BufferedImage resizeImage(BufferedImage originalImage, int type, String newLargeLocation) throws Exception{

            //Get size of image
            File file =new File(newLargeLocation);

            //File size in KBs
            double bytes = file.length();
            double kiloBytes = bytes/1024;

            double smallWidth = originalImage.getWidth();
            double smallHeight = originalImage.getHeight();

            double downMult = 1;

            //If image is too large downsize to fit the size
            if (kiloBytes>MAX_IMAGE_SIZE_IN_KYLOBITES) {

                downMult = MAX_IMAGE_SIZE_IN_KYLOBITES/kiloBytes;

                smallWidth *= downMult;
                smallHeight *= downMult;
            }

            //Final dimensions
            int finalHeight = (int)smallHeight;
            int finalWidth = (int)smallWidth;

            //Init after
            BufferedImage after = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_ARGB);

            //Scale
            AffineTransform at = new AffineTransform();
            at.scale(downMult, downMult);

            //Scale op
            AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            after = scaleOp.filter(originalImage, after);

            //Return after
            return after;
        }

A: 2 issues, I also have a resizing program but I resize the images a bit different:
First I create a Dimension object (not really needed but designwise it seems a bit better) starting from a BufferedImage object called original
final int width = original.getWidth();
final int height = original.getHeight();
final Dimension d = new Dimension(width, height);

In my case it is not about filesize but about maximum width and/or height, so without getting into details I calculate a new Dimension object based upon the one created above.
The new Dimension object is called scaled.
This is how I obtain a new scaled buffered image:
public BufferedImage resizeExact(final BufferedImage original, final Dimension scaled, final Dimension offset) {
    final Image newImage = original.getScaledInstance(scaled.width, scaled.height, Image.SCALE_SMOOTH);
    final BufferedImage bufferedImage = new BufferedImage(newImage.getWidth(null),
                                                          newImage.getHeight(null),
                                                          BufferedImage.TYPE_INT_BGR);
    bufferedImage.createGraphics().drawImage(newImage, offset.width, offset.height, null);
    return bufferedImage;
}

Using this code I obtain a BufferedImage called resizedImage that needs to get written to an OutputStream out, for this I use this code:
ImageIO.write(resized, "jpg", out);
out.close();

And here I am about the 2nd issue: I use the standard ImageIO class to write the BufferedImage as a jpeg file. The issue here is that JPEG encoders typically use a compression factor, the higher the factor the smaller the resulting file but the more quality loss in the resulting file. The code uses a default compression factor of 70%. which suits me fine. However if yoy want to change this, this reference explains how to do this: Setting jpg compression level with ImageIO in Java. Note that here changing it to 100% is essentially a lower compression factor.
Your code snippet doesn't show how eventually you create the jpeg file (I assume you use jpeg as well). If your original image is compressed say with a ratio of 40% (unlikely because then you get a lousy image I assume) so un-jpeged you have 100%, if you wanted to reduce the file size to 80% you reduce the image size to 80%, if you then compress it using 70% compression factor your end result will be aroung 56% which is bigger than the 40%.
Hope this helps. But if you specify how you write the jeg image (maybe using another library than the standard of javax.imageio) there might be another way to specify the compression factor.


text:
Q: Optimal way of multiple threads' referencing singleton object at the same time I've been developing a web services using Java/axis2/ActiveMq
which involves the interchange of massive message objects between system and user.
The number of logged user is equal to that of session objects(within SessionObjectSpace). For example,
if ( UserManager.getInstance().isLoggedIn( "userIdentifier" ) == true )
{
    SessionObjectSpace.getInstance().getUserSession( "userIdentifier" ).doSomething();
        :
        :
}

Accessing each user's session object is done as above and it happens a lot of
times in many threads throughout the codes.
Since it uses singleton pattern, a single static object may have to talk to many requests (seemingly) at the same time as the count of logged users grow.
For shared objects I think I've fully protected the system by synchronization
techniques provided by Java.
Is accessing session objects that way reasonable?
Is there a better way?


text:
Q: ExecutorService, Future, Threads appears Actives when all Runnables must be finished I have a complex program, using Runnable, ExecutorService and Future.
I want to know why the Runnable/Threads appears running, and my application still running, when I hope all they must be finished.
The Complete Code You can Copy & Paste, and Run, all you need is here.
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TestFutureExecutorService {

  public static void main(String... args) {

    List<Future<?>> futureList = new ArrayList<>();
    ExecutorService executorService = Executors.newCachedThreadPool();

    RunnableTest rt = new RunnableTest("rt", futureList, executorService);

    new Timer(false).schedule(new TimerTask() {
      @Override
      public void run() {
        rt.stop();
      }
    }, ThreadLocalRandom.current().nextLong(100L, 500L));

    System.out.println("Let's go to check the threads status.\n");
    for (int i = 0; i < futureList.size(); i++) {//Working!
      try {
        if (futureList.get(i) != null) {
          futureList.get(i).get();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Apparently everything is finished.\n");

    boolean allDone = true;
    for (int i = 0; i < futureList.size(); i++) {
      if (futureList.get(i) != null) {
        allDone &= futureList.get(i).isDone(); // check if future is done
      }

    }
    System.out.println("Is everything really finished?:" + allDone + ".\n");
    //executorService.shutdown();

    Thread thisThread = Thread.currentThread();
    thisThread.setName("Admin Thread");
    thisThread.setPriority(1);
    System.out.println("Thread = " + thisThread);

    int count = Thread.activeCount();
    System.out.println("currently active threads = " + count);

    Thread activeThreadsArray[] = new Thread[count];
    Thread.enumerate(activeThreadsArray);
    // prints active threads
    for (int i = 0; i < count; i++) {
      System.out.println(i + ": " + activeThreadsArray[i]);
    }

  }

  public static class RunnableTest implements Runnable {
    private final String name;
    private final List<Future<?>> futureList;
    private final ExecutorService executorService;
    private volatile boolean isRunning = false;

    public RunnableTest(String name, List<Future<?>> futureList, ExecutorService executorService) {
      this.name = name;
      this.futureList = futureList;
      this.executorService = executorService;
      this.futureList.add(this.executorService.submit(this));
    }

    @Override
    public void run() {
      Thread.currentThread().setName(Thread.currentThread().getName() + this.getClass().getSimpleName() + ":" + name);
      isRunning = true;
      while (isRunning) {
        try {
          Thread.sleep(50);
          new Processor(this.futureList, this.executorService);
        } catch (Exception ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
      }
        System.out.println("Finishing:" + Thread.currentThread().getName());
    }

    public void stop() {
      isRunning = false;
    }

  }

  public static class Processor implements Runnable {

    private final List<Future<?>> futureList;
    private final ExecutorService executorService;

    public Processor(List<Future<?>> futureList, ExecutorService executorService) {
      this.futureList = futureList;
      this.executorService = executorService;
      this.futureList.add(this.executorService.submit(this));
    }

    @Override
    public void run() {
      String hour = new SimpleDateFormat("_yyyyMMdd-HHmmss.SSSS_").format(new Date());
      Thread.currentThread().setName(hour + this.getClass().getSimpleName());
        try {
          int timeSleeping = ThreadLocalRandom.current().nextInt(100, 300);
          Thread.sleep(timeSleeping);
        } catch (Exception ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Finishing:" + Thread.currentThread().getName());
    }
  }

}

Now, the output....
Let's go to check the threads status.

Finishing:_20190923-203808.0435_Processor
Finishing:_20190923-203808.0437_Processor
Finishing:_20190923-203808.0489_Processor
Finishing:pool-1-thread-1->RunnableTest:rt
Finishing:_20190923-203808.0695_Processor
Finishing:_20190923-203808.0544_Processor
Finishing:_20190923-203808.0593_Processor
Finishing:_20190923-203808.0746_Processor
Finishing:_20190923-203808.0645_Processor
Apparently everything is finished.

Is everything really finished?:true.

Thread = Thread[Admin Thread,1,main]
currently active threads = 8
0: Thread[Admin Thread,1,main]
1: Thread[pool-1-thread-1->RunnableTest:rt,5,main]
2: Thread[Timer-0,5,main]
3: Thread[_20190923-203808.0593_Processor,5,main]
4: Thread[_20190923-203808.0695_Processor,5,main]
5: Thread[_20190923-203808.0746_Processor,5,main]
6: Thread[_20190923-203808.0544_Processor,5,main]
7: Thread[_20190923-203808.0645_Processor,5,main]

When I run the application, in my IDE, remain something "running", But all Runnable must be finished!
Why Threads appears active? What means that?
How finishes all?

A: You are using ExecutorService. ExecutorService keep the threads alive to be ready for the next tasks. You have to tell ExecutorService that you don't have anymore task and it can discards the threads.
You can do this by calling method
 `shutdown() or shutdownNow()`

So uncomment the line in your code after done check:
 System.out.println("Is everything really finished?:" + allDone + ".\n");
    //executorService.shutdown();

Your application will still not finish because you create the timer thread as non-deamon thread, that means JVM will not stop if running non-deamon thread exists in your application.
You can create the timer as deamon thread like this:
new Timer(true).schedule(new TimerTask() {


text:
Q: Work from home in hotel room So I'm thinking about getting a room at an extended stay hotel but they only offer WiFi and the company I work for from home requires a direct connection how can I accomplish this if I move?

A: I suspect you mean a VPN (Virtual Private Network) connection. If the company has any competence and an ongoing requirement for home workers then they should be implementing their own and should be able to instruct you on what to do.

A: Hotel rooms and like connections may introduce a double NAT so the VPN client you use for travelling must accommodate (work through) double NAT.  I also suggest that you ask your company IT department.


text:
Q: how to store url on mongoDB? i want to know what its the correct type to store an image url on mongoDB
i try this using a type: string, but doesn`t work, when is saved on the data base does not appear nothin like a string, instead of that it shows  :  url: "false".
i need this to save the url on mongodb and upload the images on another platform.
Url:{
    type:String,
    default:false
},

after of define this on my backend, i  sent the argument whit an url on POSTMAN and this was the result on mongoDB compass.
url:"false"

A: *

*Try matching your key you are sending from frontend "Url" or "url" and send it in string format from postman

*This should work Url:{ type:String, default:"" }


text:
Q: Ubuntu 16 - shutdown logs Is there any file in Ubuntu 16 that records the shutdown logs? I'm stuck with some kind of error in my laptop, my disk is encrypted and Ubuntu is not able to either reboot or shutdown properly, so I'd like to check what's going on.
$ hostnamectl
   Static hostname: resilva-Inspiron-5548
         Icon name: computer-laptop
           Chassis: laptop
        Machine ID: 3cd0030af8a7459c985a7c2662f865f3
           Boot ID: f2e930d1b0b645cd9942f7d0416f86aa
  Operating System: Ubuntu 16.10
            Kernel: Linux 4.8.0-32-generic
      Architecture: x86-64

Thanks!


text:
Q: Chess position representation for non-playing software I'm looking for an efficient way to represent a chess position.
my "efficiency" criteria are these:

*

*requires as little memory as possible

*given a position representation and a legal move (represented in the usual way, e.g. as in pgn format) it is easy to compute the resulting poisition representation. that is, the function   new_position = compute_position(old_position, move) can be (or is already) implemented in a very efficient way (from a run-time perspective).

*it is easy to compare two positions to see if they are identical

The reason I try to deviate from standard representations is that my requirements are slightly different. Specifically, I am not trying to develop a chess engine, so move generation and related issues are not required. I only need to follow some existing games, and represent certain positions, and store them in a database.
If there is a software package that that already gives this functionality, that would be great. if you have ideas on how to do it, I'd be happy to develop it :)
Thanks...

A: I'll offer some possible solutions that use "as little memory as possible" as per your specification. I know that you can make some of these more compact, but doing so makes it much more difficult to work with.

*

*64 bits: I don't know what kind of information you need to be able to retrieve from the representation, but a technique that fulfills all your given requirements is Zobrist hashing. It requires very little memory (you can use a 64 bit key and then store 232 positions before a collision is expected to occur). It is very easy and efficient to update incrementally (bitwise XOR operations) and of course easy to compare. However, if you need to display the position or retrieve any information about pieces, this leaves you out of luck.

*328 bits: you can use a piece list, with each piece (4 bits) located at a square (6 bits). Since there are 32 pieces, and you need to keep track of castling rights (4 bits), en passant file (3 bits), and side to move (1 bit).

*468 bits: bitboard representation. I know you're not developing a chess engine but this is still a very compact representation. You need 7 bitboards (all white, all black, all queens, all rooks, all bishops, all knights, all pawns), keep track of kings separately (12 bits), and all the other miscellaneous information. Yes this would be a bit of work to implement, but this allows you to do many things not possible in other representations, so this is great if you need to analyze positions.

A: There's a free PGN viewer here: http://chesstempo.com/pgn-viewer.html
Regarding the space requirement, you could compress FEN using a compression algorithm of your choice, without losing the ability to check for equality.  Depending how the moves are encoded (g1f3 versus Nf3) you may require a legal move generator for requirement 2).


text:
Q: How to web scrape and access
A: For this web site you need to target  with id="ProductJson-product-template". It contains JSON with all variants:
import bs4 as bs
import urllib.request
import json

link = urllib.request.urlopen('https://www.deadstock.ca/products/adidas-futurepacer-grey-one').read()

soup = bs.BeautifulSoup(link,'lxml')

variant = soup.find('script', id='ProductJson-product-template')
data = json.loads(variant.text)

print(json.dumps(data, indent=4, sort_keys=True))

Prints:
{
    "available": true,
    "compare_at_price": null,
    "compare_at_price_max": 0,
    "compare_at_price_min": 0,
    "compare_at_price_varies": false,
    "content": "
adidas digs into its vault to redesign the 1984 Micropacer, a computerized shoe that was designed to track running statistics. Today, the adidas Futurepacer takes cues from the Micropacer, and the more recent NMD collection, to deliver a futuristic lifestyle runner. Featuring a premium leather upper, complete with a modernized lace cover, the adidas Futurepacer sits on a Boost midsole for lightweight cushioning and responsiveness. NMD inspired bumpers are found at the heel and forefoot for added style and stability.
\n
\n
Premium leather upper
\n
Premium leather lace cover
\n
Subtle adidas branding
\n
Boost midsole
\n
adidas midsole plugs
\n
Grey One
\n
\n
Product Code: AQ0907
",
    "created_at": "2018-03-05T14:23:57-08:00",
    "description": "
adidas digs into its vault to redesign the 1984 Micropacer, a computerized shoe that was designed to track running statistics. Today, the adidas Futurepacer takes cues from the Micropacer, and the more recent NMD collection, to deliver a futuristic lifestyle runner. Featuring a premium leather upper, complete with a modernized lace cover, the adidas Futurepacer sits on a Boost midsole for lightweight cushioning and responsiveness. NMD inspired bumpers are found at the heel and forefoot for added style and stability.
\n
\n
Premium leather upper
\n
Premium leather lace cover
\n
Subtle adidas branding
\n
Boost midsole
\n
adidas midsole plugs
\n
Grey One
\n
\n
Product Code: AQ0907
",
    "featured_image": "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one.jpg?v=1530313621",
    "handle": "adidas-futurepacer-grey-one",
    "id": 223724142613,
    "images": [
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one.jpg?v=1530313621",
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one_1.jpg?v=1531247436",
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one_2.jpg?v=1531247441",
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one_3.jpg?v=1531247444",
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one_4.jpg?v=1531247447",
        "//cdn.shopify.com/s/files/1/0616/3517/products/aq0907_adidas_futurepacer_grey_one_5.jpg?v=1531247449"
    ],
    "options": [
        "US Size"
    ],
    "price": 26000,
    "price_max": 26000,
    "price_min": 26000,
    "price_varies": false,
    "published_at": "2018-07-14T12:00:00-07:00",
    "tags": [
        "07142018",
        "cf-type-footwear-qs",
        "cf-us-size-10",
        "cf-us-size-10-5",
        "cf-us-size-11",
        "cf-us-size-12",
        "cf-us-size-13",
        "cf-us-size-8",
        "cf-us-size-8-5",
        "cf-us-size-9",
        "cf-us-size-9-5",
        "cf-vendor-adidas",
        "free_shipping",
        "limit-quantity",
        "plsmerch"
    ],
    "title": "adidas Futurepacer / Grey One",
    "type": "Footwear - QS",
    "variants": [
        {
            "available": true,
            "barcode": "193050061142",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231774741,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 3,
            "name": "adidas Futurepacer / Grey One - 8",
            "option1": "8",
            "option2": null,
            "option3": null,
            "options": [
                "8"
            ],
            "price": 26000,
            "public_title": "8",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-8",
            "taxable": true,
            "title": "8",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061159",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231807509,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 2,
            "name": "adidas Futurepacer / Grey One - 8.5",
            "option1": "8.5",
            "option2": null,
            "option3": null,
            "options": [
                "8.5"
            ],
            "price": 26000,
            "public_title": "8.5",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-8.5",
            "taxable": true,
            "title": "8.5",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061166",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231840277,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 6,
            "name": "adidas Futurepacer / Grey One - 9",
            "option1": "9",
            "option2": null,
            "option3": null,
            "options": [
                "9"
            ],
            "price": 26000,
            "public_title": "9",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-9",
            "taxable": true,
            "title": "9",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061173",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231873045,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 5,
            "name": "adidas Futurepacer / Grey One - 9.5",
            "option1": "9.5",
            "option2": null,
            "option3": null,
            "options": [
                "9.5"
            ],
            "price": 26000,
            "public_title": "9.5",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-9.5",
            "taxable": true,
            "title": "9.5",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061180",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231905813,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 6,
            "name": "adidas Futurepacer / Grey One - 10",
            "option1": "10",
            "option2": null,
            "option3": null,
            "options": [
                "10"
            ],
            "price": 26000,
            "public_title": "10",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-10",
            "taxable": true,
            "title": "10",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061197",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231938581,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 6,
            "name": "adidas Futurepacer / Grey One - 10.5",
            "option1": "10.5",
            "option2": null,
            "option3": null,
            "options": [
                "10.5"
            ],
            "price": 26000,
            "public_title": "10.5",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-10.5",
            "taxable": true,
            "title": "10.5",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061203",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063231971349,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 1,
            "name": "adidas Futurepacer / Grey One - 11",
            "option1": "11",
            "option2": null,
            "option3": null,
            "options": [
                "11"
            ],
            "price": 26000,
            "public_title": "11",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-11",
            "taxable": true,
            "title": "11",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061210",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063232004117,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 4,
            "name": "adidas Futurepacer / Grey One - 12",
            "option1": "12",
            "option2": null,
            "option3": null,
            "options": [
                "12"
            ],
            "price": 26000,
            "public_title": "12",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-12",
            "taxable": true,
            "title": "12",
            "weight": 0
        },
        {
            "available": true,
            "barcode": "193050061227",
            "compare_at_price": null,
            "featured_image": null,
            "id": 3063232036885,
            "inventory_management": "shopify",
            "inventory_policy": "deny",
            "inventory_quantity": 1,
            "name": "adidas Futurepacer / Grey One - 13",
            "option1": "13",
            "option2": null,
            "option3": null,
            "options": [
                "13"
            ],
            "price": 26000,
            "public_title": "13",
            "requires_shipping": true,
            "sku": "AQ0907-Grey One-13",
            "taxable": true,
            "title": "13",
            "weight": 0
        }
    ],
    "vendor": "Adidas"
}


text:
Q: R- choropleth maps- choroplethr package Im trying to make a choropleth map of the european countries according to some metric (percentage of the population that have experienced an accident  at work) using the new choroplethr package.
Here's a reproducible example to demonstrate the 2 problems I need to solve.
a<-c(4.1,2.5,0.4,6.4,1.4,1.8,3.8,1.3,2.3,8.4,5.2,1.9,0.8,1.5,2.1,1.2,3.8,1.4,3.1,0.8,4.0,1.3,4.8,2.6,2.8,2.3,3.1,2.5)
    target<-c("austria","belgium","bulgaria","switzerland","cyprus","czech republic","denmark",
"estonia","spain","finland","france","greece","croatia","hungary","ireland","italy",
"lithuania","luxembourg","latvia","norway","poland","portugal","romania","sweden",
"slovenia","slovakia","turkey","united kingdom")
datas<-data.frame(region=target,value=a)
datas$region<-as.character(datas$region)

install.packages("choroplethr")
install.packages("choroplethrMaps")
library(choroplethr);library(choroplethrMaps)
data(country.map)
data(country.regions)

country_choropleth(datas,legend="%",num_colors=1,zoom=target)

1) The first profound problem that i come upon is these extra areas that belong to some countries(e.g france) and don't let the map zoom entirely on europe .
I gave zoom parameter the whole vector of the countries that exist in the data frame .
if i tried to country_choropleth(datas,legend="%",num_colors=1,zoom="switzerland")
then it would zoom only on switzerland

The problem arrives from countries such as france where
country_choropleth(datas,legend="%",num_colors=1,zoom="france")

So i need a way to disengage the areas that belong to european countries and are not in the European area . Any ideas?
2) The second problem that i have is that inside country.regions$region where the available regions to be used with the package exist , malta is missing. Its a single blot on the map , but still i cant skip it .
Is there any way to add a country ?

A: You should probably make this two questions. You can augment the output of the choropleth pkg with other ggplot layers/aesthetics. To "zoom in" and use close to a proper projection you can do:
library(ggplot2)

gg <- country_choropleth(datas,legend="%",num_colors=1,zoom=target)
gg <- gg + xlim(-31.266001, 39.869301)
gg <- gg + ylim(27.636311, 81.008797)
gg <- gg + coord_map("lambert", lat0=27.636311, lat1=81.008797)
gg

(and you can play with the bounding box coords to get in a bit tighter)\


text:
Q: Mallocing nested structs If if write the following code:
struct _one
{
    int x;
};
struct _two
{
    struct _one one;
};
struct _three
{
   struct _two two;
};

Then in main I call a user defined functions that malloces the _three structure, and returns the pointer to main, is the x variable in the heap?
Because you access it this way:
three->two.one.x;

Because when you access it with the dot operator, that usually means it is static, as opposed to dynamic. The -> operator usually means that it is dynamically allocated. I was wondering if something weird was going on behind the scenes (maybe).

A: "Heap" is a colloquialism for the memory managed by the memory management routines (malloc, free, and family). At one time, that memory may have been managed with a heap structure, but modern routines are more complicated. A proper term for this memory is "dynamically allocated memory."
Generally, whether the routines use a heap or other data structure to manage memory, they have a database of memory available to be allocated. For example, they may have a list (whether it is in a heap, tree, hash table, bit map, some other structure, or some combination of structures) of blocks that were once allocated by have since been freed, so they can be given out again. Or the list may include memory that is available because a large amount was obtained from the operating system to satisfy an earlier request, but only part of it was needed for the specific request, so the remainder is available for future requests.
What this means for your question, is the member x (and the structure it is in) in the heap, is that when memory is allocated, it is actually removed from the heap or other database. It is no longer available to give out, so it is not in the database of available memory.
This means memory you have allocated is not in the heap.
At that point, it is your program's responsibility to keep track of that memory and to release it with free at an appropriate time. That will return it to the database of available memory. (An appropriate time might be never, if your program finishes its job and is exiting. In general-purpose multiuser operating systems, there is no need to free allocated memory when exiting; the operating system will reclaim it.)
However, the memory you have allocated is dynamically allocated memory, and it might be consider "part of" the pool of such memory in some sense. That is, even though it is not currently part of the database of available memory, it is part of all of the memory that is dynamically allocated and freed.
More particularly, your structure struct _three is defined to include a member two of type struct _two, and that includes a member one of type struct _one, and that includes a member x of type int. All of these form one struct _three object. C does not treat them as separate things that can be split apart in memory and managed separately. Only if you have pointers can a structure have a member that connects to a separate thing in memory. In that case, your program will be allocating that memory separately; it will have to use malloc or a related routine to get memory for that separate thing and set the pointer member to point to that other memory.


text:
Q: MySQL Error : Can't create/write to file '/var/mysqltmp/#sql_1fbd_0.MYI' (Errcode: 13) yesterday i got bad getway error while browsing my vb forum
and today my forum back to work ... but most of links give this error
MySQL Error   : Can't create/write to file '/var/mysqltmp/#sql_1fbd_0.MYI' (Errcode: 13)

i search for simillar problem and got that this is premission problem
using FTP account i didnt found this directory "var/mysqltmp"  so i made it and set premission to 777
but problem not solved
i read that this must fixed using Shell SSH ... but i didnt found a good explain about hoe to use shell SSH , because im Win Xp user :(
does this problem can be solved from FTP or Cpanel ?
or its a server problem ?
thanks for help in advance

A: It looks like your permissions on /tmp are wrong. They really should be read/write/execute for everyone with the sticky bit set.
chmod 1777 /tmp
The sticky bit add some restrictions to how other users interact with files not created or owned by them, so there's no reason to worry.
If you wish, you may also create a seperate directory owned and writeable by the mysql user and specify that directory in my.cnf to be used instead of the system wide /tmp.

A: just use
REPAIR TABLE tablename

Docs http://dev.mysql.com/doc/refman/5.1/en/repair-table.html
Of course you must find what table is corrupted.
In most cases its server problem (disk error)

A: Try to run mysql tool that finds corrupted tables:
    mysqlcheck dbname -uusernamae -p
In my case i didn't receive any errors, but after that the issue with tmpdir was fixed.


text:
Q: Determining whether input ids are persists in directory items collection Imagine I have a List<string> = _checkList which represents ids for some check.
Also I have IReadOnlyCollection<IWorkItem> = _workItems with some work items.
Declaration of IWorkItem
 public interface IWorkItem : IDirectoryItem, INavigationItem
    {
        string ID { get; set; }

        string WorkId { get; set; }

        string Brief { get; set; }
    }

I need to check if all of items with WorkId from checkList are persists in collection _workItems.
Should be tricky with LINQ.
Thanks for any help!

A: You can try the next:
if(_checkList.All(workId => _workItems.Any(wi => wi.ID == workId))) { ... }


text:
Q: code in c on local machine is fine but runtime error on hackerrank in algorithm warm up exercise "angry children"? i uploaded a code in c for problem "angry children" in algorithm section of hackerrank. for testcase #2 it is showing runtime error while on my local machine(ubuntu 14.04, x86) in gcc it is giving answer 1335 which is correct ans according to the testcase #2 output given by them. please tell me what to do to make hackerrank accept my code perfectly it is working for all other testcaases.
#include<stdio.h>
#include<assert.h>
long long int *insertion(long long int ar[],long long int n)
{
    long long int i,j,v;
    for(i=2;i<=n;i++)
    {
        v=ar[i];j=i;
        while(ar[j-1]>v){
            ar[j]=ar[j-1];j--;
            }
            ar[j]=v;
            }return ar;
}
int main()
{
long long int i,a,b,c,temp;
long long int n,k;
scanf("%lld",&n);
long long int ar[n+1];
assert(1<=n<=100000);
scanf("%lld",&k);
assert(1<=k<=n);
for(i=1;i<=n;i++)
{
    scanf("%lld",&ar[i]);
    assert(0<= ar[i] <=1000000000);
    }
insertion(ar,n);
//for(i=1;i<=n;i++)
//{
//  printf("%lld\n",ar[i]);}
long long int f,min=9999999999;
for(i=1;i<=n-k+1;i++)
{
f=ar[i+k-1]-ar[i];
if(f<min)
    min=f;
}
printf("%lld\n",min);
return 0;
}

this is my code in c please tell me why it is shoeing segmentation fault on hackerrank compiler?

A: There's a bug in your insertion sort function, which doesn't check to see if j becomes less than 1. As a result, your code is liable to go marching off into the wilderness whenever it tries to insert a value at the start of the list.
The fix is simple. Just change
        while(ar[j-1]>v){

to
        while(j>1 && ar[j-1]>v){

Or alternatively, instead of re-inventing the wheel, use one of the library functions provided in stdlib, like qsort(), for example. Much more efficient, and much less prone to errors. You'll have to adjust your code to use zero-based indexing, but you should be doing that anyway, really.


text:
Q: Dismiss AlertDialog from within it's button's callback I want to be able to dynamically dismiss an AlertDialog from within it's own button callback:
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if (/* if some condition is met */) {
                // dismiss the alert
            } else {
                // keep the alert open
            }
        }
    });
    final AlertDialog alert_dialog = alert.create();
    alert_dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
    alert_dialog.setCanceledOnTouchOutside(false);
    alert_dialog.show();

I know that I can call dismiss() on alert_dialog but I cannot put this call within the very code that creates it.

A: The DialogInterface in the callback is the Dialog itself (Dialog implements DialogInterface), so all you have to do is call the DialogInterface#dismiss() method:
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        if (/* if some condition is met */) {
            dialog.dismiss(); // dismiss the alert
        } else {
            // keep the alert open
        }
    }
});


text:
Q: How to calculate the period of this pendulum I have a pendulum with the following properties:

*

*The diameter of the sphere is 1 meter.

*The sphere of the pendulum is made of pure titanium.

*The pendulum is connected to the roof with a rigid string 12 meters long. It does not have mass. The union between the string and the sphere is rigid, so it cannot rotate.

*The oscillation angle is 60 degrees from the vertical.

We suppose there's no air, so there's no friction.
With this data, I need to know the period of this pendulum. I have not worked with pendulums so I do not know how to start. Any hint/guide?
I know that with 1. and 2. we can obtain the mass of the pendulum, using the density of the Titanium, $d_{titanium}=4506\;kg/m^3$. The volume of the sphere is $V=\frac{4}{3}\pi$, so the mass is $m=d\cdot V=4506\cdot\frac{4}{3}\pi=6803\pi$.

A: Let's assume that the gravitational acceleration $g$ is known. You did not specify where the string is connected to the sphere (center or a point on the surface). I will use the center. If it's at the surface, all you need to do is change the distance to the center by adding half the diameter. The moment of inertia of the sphere with respect to the center of the mass is $$I_{CM}=\frac 25 MR^2$$
With respect to the point on the roof around which it oscillates it is $$I=I_{CM}+ML^2=M\left(\frac25 R^2+L^2\right)$$
If you want, you can say that $R^2\ll L^2$. In that case the problem will not depend on the radius of the sphere.
Then using the zero of potential energy at $\theta=0$, where $\theta$ is measured from the vertical axis, you have $$MgL(1-\cos\theta)+\frac12I\dot\theta^2=MgL(1-\cos\theta)+\frac12M\left(\frac25 R^2+L^2\right)\dot\theta^2=MgL(1-\cos\theta_0)$$
$\theta_0$ is the initial angle of $60^\circ$.
Calculating $\dot\theta$ from here, you get
$$\dot\theta=\sqrt{\frac{2gL}{\frac25 R^2+L^2}(\cos\theta-\cos\theta_0)}$$
Using $\dot\theta=\frac{d\theta}{dt}$, you get $dt=\frac{d\theta}{\dot\theta}$. To get the period$$T=2\int_{-\theta_0}^{\theta_0}\frac{d\theta}{\dot\theta}=2\sqrt{\frac{L^2+\frac25R^2}{2Lg}}\int_{-\theta_0}^{\theta_0}\frac{d\theta}{\sqrt{\cos\theta-\cos\theta_0}}$$


text:
Q: Angular hide/show based on radio button Plunker
How can i make yes radio button to be checked on page load and show/hide the field-set accordingly. Currently on load radio button is checked but its not showing the fieldset.
Html
  <form name="myform" class="form "  novalidate >
 <fieldset>
       Would you like a receipt sent to you?

        <input type="radio" name="receiptConfirmation" id="receiptAffirm"  ng-model="reciept" value="yes" ng-checked="true">
        Yes

      <input type="radio" name="receiptConfirmation" id="receiptDeny" ng-model="reciept" value="no">
            No

 </fieldset>
 <fieldset class="fieldset" ng-show="reciept=='yes'">
    <legend class="isVisuallyHidden">Email Receipt</legend>

         First Name
         <input id="Text4" class="form__input form__input--textfield" type="text" >

           Email Address
           <input id="email1" class="form__input form__input--textfield" type="email">

 </fieldset>

</form>

A: Do not mix ng-checked with ng-model. Setting ng-checked will not update the model, it will just update the element's checked property. Instead set the ng-model reciept to the desired value.
Remove ng-checked from input:-
 <input type="radio" name="receiptConfirmation" id="receiptAffirm"
        ng-model="reciept" value="yes">

In your controller set the model:-
app.controller('MainCtrl', function($scope) {
 $scope.reciept = "yes";
});

Demo

A: Just set $scope.reciept = 'yes'; in your controller?
You have spelt receipt wrong also.


text:
Q: netcat working on localhost but not from remote host I have two machines (Machine1 & Machine2) on the same subnet. Machine1 has a tool installed that returns some data. for example if I run the following command, it returns some data.
printf "get:info\nend\n" | nc localhost 1234

However if do the same on Machine2, of course changing localhost to machine1, nothing happens. Any Idea what can be the problem?
printf "get:info\nend\n" | nc machine1 1234

A: After investigating alot I finally managed to find the reason why I was not able to communicate  to the other machine on the specific port.
Iptables setting in my machine1 was not allowing machine1 to listen. I turned off of the iptables and everthing worked fine.
But its not a good idea to turn off the iptables. So for the next step I allowed port 1234 for machine1.
sudo iptables -A INPUT -p tcp --dport 1234 -j ACCEPT

You can find more information about iptables on the link below:
https://help.ubuntu.com/community/IptablesHowTo


text:
Q: Showing Time line using d3js I am new to d3js, trying to display a graph with X axis having time series, 00:00 to 23:59.
Trying to configure d3js to parse time as below
var parseTime = d3.time.format("%H%M").parse;
var mytime = "2045"; // I expect it to be 8 45 PM
mytime = parseTime(mytime);
alert(JSON.stringify(mytime));

But the alert shows "1900-01-01T15:15:00.000Z" instead of 20:45. I know something is terribly wrong, may be my understanding itself is wrong.
Any pointers to have timeseries data on x series would be helpful.

A: Try to add .tickFormat(d3.timeFormat("%H%M")) in your x-axis declaration.
For a more general explanation of tickformat you can read this post:
https://bl.ocks.org/mbostock/9764126


text:
Q: Iteration convergence. How can I solve this problem?

Let $$x(n+1)=-\frac{\exp(x(n)/2)}{5}$$ be a given sequence. Prove using the Banach contraction principle that this sequence converges to some fixed point $X$ with $x(0)$ in some interval $[a,0]$ where $a<-1/5$.

A: As julien says, consider the function $f(x) = -\frac{1}{5} e^{x/2}$ and note that if $x\in [a,0]$ for some $a < -1/5,$ then $a < -\frac{1}{5} \le f(x) \le -1/5 e^{a/2} < 0,$ so $f(x) \in [a,0],$ from which any number of iterations of $f$ applied to $x$ will still be in the interval. Hence, our sequence is contained in $[a,0]$ and $x(n+1) = f(x(n)).$
Consider $f^{\prime}(x) = -1/10 e^{x/2}$ and note that in the interval $[a,0],$ $-1/10 \le f^{\prime}(x) \le -1/10 e^{a/2},$ so $|f^{\prime}(x)| \le 1/10.$ By the Mean Value Inequality, $|f(x) - f(y)| \le 1/10 |x-y|$ in the interval. Using the Banach fixed point theorem gives that the sequence $x(0), f(x(0)) = x(1), \ldots, f(x(n)) = x(n+1), \ldots$ converges to a point in $[a,0].$


text:
Q: Detecting the vehicle signal light of a moving vehicle using Matlab Hi i m really really new to image processing and matlab.
i tried to detect vehicle of a traffic video using 'vision.forgroundDetector'in matlab.
But now i want to identify the vehicle signal light is on or off when the vehicle is turning.
i tried some codes but it never work and i dont know where to write the code also the written code didn't work.
Can someone please help me to identify the signal light of moving vehicle.
you can find the video that i have used through this link
 "https://www.youtube.com/watch?v=jjlBnrzSGjc"
Here is my code:
    foregroundDetector = vision.ForegroundDetector('NumGaussians', 3, ...'NumTrainingFrames', 50);

videoReader = vision.VideoFileReader('vi.mp4');
for i = 1:150

    figure; imshow(frame); title('Video Frame');
figure; imshow(foreground); title('Foreground');

    videoPlayer = vision.VideoPlayer('Name', 'Detected Cars');
    videoPlayer.Position(3:4) = [650,400];  % window size: [width, height]
    se = strel('square', 3); % morphological filter for noise removal

    no = {'0','00-0000'};
    num =1;
    k = 10;
    m=0

    while ~isDone(videoReader)

    frame = step(videoReader); % read the next video frame

    % Detect the foreground in the current video frame
    foreground = step(foregroundDetector, frame);

    % Use morphological opening to remove noise in the foreground
    filteredForeground = imopen(foreground, se);

    blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
    'AreaOutputPort', false, 'CentroidOutputPort', false, ...
    'MinimumBlobArea', 150);

    % Detect the connected components with the specified minimum area, and
    % compute their bounding boxes
    bbox = step(blobAnalysis, filteredForeground);

    % Draw bounding boxes around the detected cars
    result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');

    % Display the number of cars found in the video frame
    numCars = size(bbox, 1);
    m = m+ numCars;
%st = {'JRW-2731','BCR-5890','WJ-6629','MW-5587','RV-6929','BN-8944','AN-7037','BI-7899','BI-7899','RX-7294','TL-9090'};
 noplat;

    result = insertText(result, [10 50; 10 100], no, 'BoxOpacity', 1, ...
        'FontSize', 14);

    step(videoPlayer, result);  % display the results
%    step(videoPlayer, result1);
end

release(videoReader); % close the video file

This is the next File;
    if m>6800 && k == 10
        no = {'1','DAE-4321'};
        k = k-1;
        end
     if m>9600 && k==9
        no = {'2','204-0024'};
        k = k-1;
        end
     if m>15000 && k==8
        no = {'3','QK-BG18'};
        k = k-1;
        end
     if m>23700 && k==7
        no = {'4','KT-7349'};
        k = k-1;
        end
     if m>25000 && k==6
        no = {'5','K2-1479'};
        k = k-1;
     end
     if m>25800 && k==5
        no = {'6','BG-5218'};
        k = k-1;
        end
     if m>33300 && k==4
        no = {'7','B2-8697'};
        k = k-1;
        end
     if m>37900 && k==3
        no = {'8','PQ-1374'};
        k = k-1;
     end
     if m>90500 && k==2
        no = {'9','RX-7294'};
        k = k-1;
     end
     if m>97000 && k==1
        no = {'10','TL-9090'};;
        k = k-1;
     end


text:
Q: How to construct a contractible space but not locally path connected? I am looking for a space which is contractible and not locally path connected.
I know the cone $CX$ of every space $X$  is contractible. Besides, it seems that if $X$ is locally path connected, so is $CX$. Therefore, I need to find a space which is not locally path connected.
Therefore, I tried $\sin(1/x)$-space and considered its cone.
Since $X$ can be topologically embedded in $CX$, $\sin(1/x)$-space is a subspace of its cone. It seems that open subsets of a locally path connected space are again locally path connected. However, $X$ is not open in $CX$.
Therefore, I am not sure whether it is locally path connected or not.
Any help will be appreciated. (I prefer some simple examples of such spaces, since I am a beginner in algebraic topology.)

A: The union of all the lines $y = mx$ with $m \in \mathbb Q$ with the topology of subspace of $\mathbb R^2$ is a contractible space but is not locally path connected.
The verification of the properties are trivial.

A: If $X$ is not locally path-connected, then there is a point $x$ and a neighborhood $U$ of $x$, which does not contain a path-connected neighborhood. Now choose $0<\epsilon<1$. The subspace $U\times[0,ϵ)$ of $X\times I$ is also a subspace of the cone $C(X)$. If it had a path-connected neighborhood $V$ of $(x,0)$, then the projection of $V$ onto $X\times\{0\}$ would be a path-connected neighborhood of $x$ within $U$ (since the projection is continuous and open). That's why the cone isn't locally path-connected either.
On the other hand, if $X$ is locally (path-)connected, then so is $X\times I$ as $I$ is locally path-connected. This property then carries over to the cone $C(X)$ since quotient maps preserve local (path-)connectedness.


text:
Q: How do I get the current URL of my script using PHP? How do I get the current URL of my script using PHP?

A: For www.example.com/files/script.php
$_SERVER['SCRIPT_NAME']
 = /files/script.php
and if you want the current directory url:
dirname($_SERVER['SCRIPT_NAME']) = /files

A: Please see PHP Get Current URL:

Sometimes it is not as straightforward
  as one may think to get the current
  url to use it inside your application.
  Here is a snippet that I use to fetch
  the current URL and use it in a
  script. The current url (whether http
  or https) is now a local variable that
  you can do with as you please.

$url = "http".(!empty($_SERVER['HTTPS'])?"s":"").
"://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

Note: You should groom this value before using in anything sensitive, like a sql query.

A: If you want to know the script name on your server, then..
$file = $_SERVER["SCRIPT_NAME"];
echo $file;

$_SERVER["SCRIPT_NAME"] will give you the current executed script path, which related on your server not on the browser's url.

A: Whe you need info like this its often convenient to look at the output of phpinfo() and then read the docs on those items that seems good.
Keep in mind that some of them might be correct on your server, but slightly different on others.. Depending on os, http server etc.

A: suppose you were accessing
How do I get the current URL of my script using PHP?
then
echo $_SERVER['SERVER_NAME']; // This will return u the hostname that is:-
stackoverflow.com/
and
echo $_SERVER['REQUEST_URI']; // It will return only the file name from current url
will return below "/questions/1871770/how-do-i-get-the-current-url-of-my-script-using-php" and not the hostname.

A: Hi this is the solution of your problem
//fetch page url by this
$url=$_SERVER['REQUEST_URI'];
echo "$url
";

//it will print
//fetch host by this
$host=$_SERVER['HTTP_HOST'];
echo "$host
";

//you can fetch full url by this
$fullurl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;


text:
Q: Big Latency using Azure Database for PostgreSQL flexible server I have a PostgreSQL database deployed on Azure using Azure Database for PostgreSQL flexible server.
I have the same database created locally and queries that takes 70ms locally, takes 800ms on the database deployed on Azure.
The latency happens if I query the database from my local machine or from an app deployed in Azure Service.
Any clue what may be the issue or how this can be improved?
The compute tier I am using in Azure is the following (I know it's the worst one but I still think it shouldn't take almost a second to query a table that has 50 records in it and two columns):

Burstable (1-2 vCores) - Best for workloads that don't need the full
CPU continuously
Standard_B1ms (1 vCore, 2 GiB memory, 640 max iops)

This is what Azure is showing me in the overview (so that's why I am guessing the problem should be network related and not CPU/memory related):

A: Burstable sku's are for testing and small workloads changing to General purpose will improve.


text:
Q: Saving data after read I'm trying to save data after the same model read it. Here's my code:
public function partner($postid, $partner){
    $this->Partner->id = $postid;
    $this->Partner->id = $partner;
    $this->Partner->ip = $_SERVER['REMOTE_ADDR'];
    $result = $this->Partner->read();
    if($result){
        $time = $result['Partner']['time'];
        pr($result);
    }

    $data = array('id' => $partner,
                  'post' => $postid,
                  'time' => time(),
                  'cash' => '0.001',
                  'ip' => $_SERVER['REMOTE_ADDR']);
    $this->Partner->save($data);
}

It just updates the data, but doesn't save it as a new row

A: Before $this->Partner->save($data);, call $this->Parter->create();, that will set the Partner model to save a new row.
EDIT: Unless id is your model's primary key and you're setting it to a value that already exists in the database, in that case it will update regardless of whether you use $model->create() or not. (I think).


text:
Q: Windows scheduled task - .bat runs forever I've a scheduled task to clean up folders on a hard drive automatically; it removes files older than a certain amount of days.
Basically it runs a .bat file  full of lines that looks like this:
FORFILES /P "D:\Folder1\SubFolder1" /D -30 /C "cmd /c del /F /Q @path"
FORFILES /P "D:\Folder1\SubFolder4" /D -30 /C "cmd /c del /F /Q @path"

I've noticed that the task often never ends; and I don't know why. The .bat file ends in a couple of minutes when run manually and the folders are cleaned up afterwards.
I guess the reason might be that sometimes a prompt may appear:

Delete [...] are you sure? (Y/N): _

because of recursive deletion in subfolders. Notice I added /F and /Q switches to the del command.
How can I make sure that the task automatically answers Y to any prompt that may appear? Or is this not the path I should take to solve my problem - should I improve my .bat file?

A: Your problem seems to be that forfiles finds both files and directories, and you are only looking to delete files.
Please try this in the /C command:
"cmd /c if @isdir==FALSE del @path"
This will only fire the del command if the forfiles iterator does NOT point to a directory.
I would leave out the -q, at least for now, to see if this goes ok. But I think you shouldn't need/want to muzzle confirmation questions if you target the right things.
Also, the /f is only required if you want to delete read-only files. Only force if you are sure it's necessary :)
Good luck, hope this helps.


text:
Q: Is there a pre-existing flight controller framework similar to DJI Go? Hello DJI SDK Community,
I'm looking to essentially write a simple plugin for DJI Go (Android) that takes live flight data from the drone and sends it to the internet. From what I can tell, DJI Go doesn't allow plugins, so I'd have to write a flight controller app using the SDK from the ground up and then build my plugin on that.
That sounds like a monumental task, and way out of my league. Does anyone have any ideas for something I could use as a framework that acts as DJI Go (even super basic flight functionality would be great) that I could write my plugin on top of?
My drone:
Phantom 3 Pro
Thanks!

A: You could start with the Android Mobile SDK sample app which has many of the basic functionality for flight control already coded in.