Q: Post data in C# and use response in CefSharp I'm trying to post parameters to a website and use the response in my CefSharp browser. Using my current code it posts the data and loads the html in CefSharp. The html page that loads is exactly what I want meaning the post works but as soon as I click a button it just loads up the website without an of the parameters I posted. How could I use the cookies from the request so that if I click the button everything should remain the way it was posted.
Here is the code i'm using to post:
using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { },
        { },
        { },  <----- Parameters go here
        { },
        { },
    };

    //WebClient client2 = new WebClient();

    client.DefaultRequestHeaders.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync("URL", content);
    var responseString = await response.Content.ReadAsStringAsync();
    CookieContainer cookies = new CookieContainer();
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = cookies;
    chrome.LoadHtml(responseString, "URL");


Q: How to make Recycle Bin in ASP.Net i want to create a Recycle Bin in my web project, i use a Details View with EDIT and DELETE option to present and edit data from database and its worked perfectly but want a Recycle Bin for Deleted Data and if Owner wants to delete completely Delete from Recycle .
if u have some codes or  idea or some links help me please !

A: You shall have a field in db which means isDeteled or isRecycled and when it is set to 1 show it in recycleBin/ if user finally deletes record delete if from db.
Better choice is to have status field for enum Active/Archived/Deleted or Active/Archived/Deleted/Purged
when the record in last state of this enum delete it in real time, or by SQL clean-up job or something like this.


Q: Losing custom gridview font when new page selected I am using this code to change the font color in a grid view for a single column depending on value:
       For Each row As GridViewRow In gvSearch.Rows
           If row.Cells(8).Text.Trim = "Used" Then
               row.Cells(8).CssClass = "CautionRow"
           End If
        Next

This code runs after the gridview databind.  However, the gridview has pages available and this code only changes the first page of the grid view.  I can resolve the problem by not allowing pages, but this is a tacky solution.  Any suggetions?

A: Register PageIndexChanging event
onpageindexchanging="gvSearch_PageIndexChanging"

Then in event handler do your font changing logic like
Sub gvSearch_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
{
         For Each row As GridViewRow In gvSearch.Rows
           If row.Cells(8).Text.Trim = "Used" Then
               row.Cells(8).CssClass = "CautionRow"
           End If
        Next
}

A: Actually found my own answer thanks to help from my fellow programmer.  Here's what really works:
In the style sheet (.css) add this:
.CautionRow {
    color: red;
}

... then add this to your code:
Protected Sub gvSearch_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViwRowEventArgs) Handles gvSearch.RowDatabound

    If e.Row.Cells.Count > 1 Then
        If e.Row.Cells(8).Text.ToString.ToLower.Trim = "used" Then
            e.Row.Cells(8).CssClass = "CautionRow"
        End If
    End If
End Sub


Q: Can't attach Unity script to a GameObject I'm a new Unity user, and I'm having issues when trying to attach a C# script to a GameObject:

Can't add script component XYZ, because the script class cannot be found. Make sure there are no errors and that the file name and class name match.

Searching online this issue usually happens when the class name and file name are different, but I've checked that and they are the same. I even tried creating a new empty/default C# script and tried attaching that, but no luck. This is completely empty project, and there are no other scripts with compile errors. GIF showing the error

Any ideas, help would be appreciated?
I'm running Unity 2019.1.of2 Personal on Ubuntu 19.04

A: I managed to solve the issue with help from the comments above. The issue was that Unity was unable to compile/build the project, hence as 3Dave and Corey Smith said - if there are any compile errors you are unable to attache scripts to GameObjects.
I also realized I was unable to run the project. I first though it might be an issue with .NET versions on Ubuntu, but it turned out to be issue with libssl1.0 library (if you have a greater version then Unity won't work on Ubuntu 19.04). See this post for reference: https://forum.unity.com/threads/empty-log-errors-in-2019-1-0f2.669961/#post-4545013
Installing libssl1.0 solved the compile issues, I'm now able to attache scripts to GameObjects and run the project.

A: Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.


Q: Javascript not working on mobile site I'm using JavaScript to submit the current URL, all works fine until I enter to mobile screen, then the JavaScript appears to be gone, this is not only for "mobile" apparently the problem is based on the screen width.
 $( document ).ready(function() {
    $( "#widgetu117_input" ).keyup(function( event ) {
       var getUrl = window.location;
       var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
    })
})

This is my code.
The form was build using muse (not my doing)

A: I found a solution, it works for me. instead of using document ready, i changed everything to be a function and then, call it with settimeout at 7 seconds (tried with 3 but the problem persisted).
Hope nobody has this problem it was tricky to solve.


Q: Returning a strongly typed promiseValue from angular $modalInstance with TypeScript TypeScript newb Question.  I'm trying to return a strongly typed promise from angular's $modalInstance.
I have something similar to:
this.$modal.open(options).result.then(result => {
    Currently result is type 'any'.
    How do I cast it or affect it to be of type MyType?  (see below)
});

interface myType {
    a: string,
    b: number
}

result: myType;
...

$modalInstance.close(this.result)

A: I actually had to wrap the $modal and $modalInstance services to take a type T. The above answer (which I had initially tried) will not work because the $modalInstance result is a promise of type 'any'. The wrapped $modalInstance is a promise of type T.
module my.interfaces {

export interface IMyModalService<T> {
    open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>;
}

export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope {
    $dismiss(reason?: any): boolean;
    $close(result?: T): boolean;
}

export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance {
    close(result?: T): void;
    dismiss(reason?: any): void;
    result: angular.IPromise<T>;
    opened: angular.IPromise<any>;
    rendered: angular.IPromise<any>;
}

A: this.$modal.open(options).result.then((result: myType) => {
    Now result is declared to be of your type
});


Q: Transition not working properly on vue when div is being hiding I have simple transition to toggle a div text, however the transition works only when the text is being hiding, however when I click to show the text the transition doesn't work here it is my code:
<template>

    <transition name="fade">

My name is Simon

    </transition>
    <button @click="showName = !showName">Toggle</button>

</template>

A:

My name is Simon

You should open a p tag under the div tag


Q: Crash startActivityForResult(intent,1); I have a problem in my android application, I have a hand page, I change my business with
startActivityForResult (intent, CODE_DE_MON_ACTIVITE).

It works, but then when I replace this page since the second activity with the same code but nothing works. The application crashes.
Knowing that I have all the activities in the Manifest.
Log:
06-28 13:09:47.765: D/AndroidRuntime(254): Shutting down VM
06-28 13:09:47.765: W/dalvikvm(254): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
06-28 13:09:47.765: E/AndroidRuntime(254): Uncaught handler: thread main exiting due to uncaught exception
06-28 13:09:47.775: E/AndroidRuntime(254): java.lang.RuntimeException: Unable to start activity ComponentInfo{referencehit.android/referencehit.android.AddTournamentActivity}: java.lang.NullPointerException
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.os.Looper.loop(Looper.java:123)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.main(ActivityThread.java:4363)
06-28 13:09:47.775: E/AndroidRuntime(254):  at java.lang.reflect.Method.invokeNative(Native Method)
06-28 13:09:47.775: E/AndroidRuntime(254):  at java.lang.reflect.Method.invoke(Method.java:521)
06-28 13:09:47.775: E/AndroidRuntime(254):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-28 13:09:47.775: E/AndroidRuntime(254):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-28 13:09:47.775: E/AndroidRuntime(254):  at dalvik.system.NativeStart.main(Native Method)
06-28 13:09:47.775: E/AndroidRuntime(254): Caused by: java.lang.NullPointerException
06-28 13:09:47.775: E/AndroidRuntime(254):  at referencehit.android.AddTournamentActivity.onCreate(AddTournamentActivity.java:38)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
06-28 13:09:47.775: E/AndroidRuntime(254):  ... 11 more
06-28 13:09:47.788: I/dalvikvm(254): threadid=7: reacting to signal 3
06-28 1
3:09:47.788: E/dalvikvm(254): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

Have you an idea of my problem?

A: Have you actually assigned a value to the Intent? Simply coding Intent intent; will throw a NullPointerException when you call startActivity(intent); like the one you got. Alternately, have you added your second activity to the Manifest file? Android won't launch an Activity that isn't in its Manifest.

A: Add followin permission to ur AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If u have forgotten to add it, then add it.


Q: Function with arguments in requestAnimationFrame I'm trying to define a recursive function with arguments using "requestAnimationFrame".
animate(frameElapsed,points,canvas){
        console.log("test");
        if(frameElapsed<points.length-1){
            requestAnimationFrame(this.animate(frameElapsed+1,points,canvas));
        }
        ...
}

When I do this, i get the error "Argument of type 'void' is not assignable to parameter of type 'FrameRequestCallback'. So I tried to define an anonymous function that calls animate to solve this problem.
animate(frameElapsed,points,canvas){
        console.log("test");
        if(frameElapsed<points.length-1){
            requestAnimationFrame(function() {
                this.animate(frameElapsed+1,points,canevas);
            });
        }
        ...
}

Then, I get "ERROR TypeError: Cannot read property 'animate' of undefined" in my web console. I can't manage to solve this problem.
Is there a way to pass arguments to af function called back by requestAnimationFrame ?
Thank you for your help !

A: user120242's solution worked for me !
    animate(frameElapsed, points, canvas) {
        console.log("test");
        if(frameElapsed < points.length - 1) {
            requestAnimationFrame(() => {
                this.animate(frameElapsed + 1, points, canvas);
            });
        }
        ...
    }

Thank you for your help !


Q: Codeigniter - array of json objects in post In fire bug I view my jquery post request parameters, its like this
adults            1
applicants[]    [object Object]
attendees   1
children    0

In this post request the array called applicants contains json object which I want ti iterate over and pull out values in my codeigniter controller. The json string may look like this
({attendees:"2",
  adults:"2",
  children:"0",
  grptype:"2",
  'applicants[]':[{firstname:"John", lastname:"Doe", age:"33", allergies:"true", diabetic:"true",    lactose:"false", note:"nuts"}, {firstname:"Jane", lastname:"Doe", age:"34", allergies:"true", diabetic:"false", lactose:"false", note:"pollen"}]
})

Look at the applicants[] above, see I have info for two people as a json object. I am not sure how access the data in my controller. see this
$applicants = $this->input->post('applicants');
$this->output->append_output("
Here: " . $applicants[0].firstname );

I was thinking $applicants[0] woild refer to the json object and I could just pull outs values on demand. Not sure hat I am doing wrong. Thanks guys.
EDIT
So I have adjusted my json and it looks like this
adults  2
applicants[]    {firstname:"John", lastname:"Doe", age:"23", allergies:"true", diabetic:"true", lactose:"false", note:"nuts"}
applicants[]    {firstname:"Jane", lastname:"Doe", age:"23", allergies:"false", diabetic:"false", lactose:"false", note:""}
attendees   2
children    0

Now I am still getting an error saying
**Message: json_decode() expects parameter 1 to be string, array given**

Any ideas ?
EDIT 2
Ok mu data now liiks like this
adults  1
applicants[]    {"firstname": "John", "lastname": "Doe", "age": "34", "allergies": "true", "diabetic": "true", "lactose": "false", "note": "nuts"}
attendees   1
children    0

In the controller id did this
$applications = $this->input->post('applicants');
foreach ( $applications as $item)
{
  $item = json_decode($item, true);
  $this->output->append_output(print_r($item));
}

This is the result of that logic
Array
(
    [firstname] => John
    [lastname] => Doe
    [age] => 34
    [allergies] => true
    [diabetic] => true
    [lactose] => false
    [note] => nuts
)

Not sure what I am doing wrong, no matter what I do to access the dater I get an error to the effect that I cannot access it like that. How do I pull out the values ?

A: You have to decode it on the server using
$applications = json_decode($this->input->post('applicants'), true);

So, it'll become an associative array and you can use it like an array, without the second argument (true) in json_decode the json will be converted to an object. Until you decode it, it's only a string (json/java script object notation  string).
Update: Since it's already an array of objects then you don't need to use json_decode, just loop the array in your view like
foreach($applicants as $item)
{
     echo $item->firstname . '
';
     echo $item->lastname . '
';
     // ...
}

According to the edit 2 it should be access as an array
echo $item['firstname'] . '
'

A: try this plz
$applicants = $this->input->post('applicants');
$json_output = json_decode($applicants );
foreach ( $json_output as $person)
{
  $this->output->append_output("
Here: " . $person->firstname );
}

or
$json_output = json_decode($applicants,TRUE );
echo $json_output[0][firstname] ;


Q: Race conditions I'm currently stuck trying to understand two things related to race conditions.
Issue 1:
I have been presented with the following question:
We consider the digital circuit and the value of its inputs a,
and b as given below. For all logic gates, we assume that
there is a gate delay of exactly one time unit (i.e. the gate
delay equals the time between two dotted lines in the
diagram). Give the values of c, d, e, f in the digital circuit for
every point of time between 0 and 8.

And the answer given is as follows:

How exactly is this achieved? This is what I think so far:

*

*c starts at 1 because a start at 0

*d starts at 0 because b start at 1

*When time is equal to 2 a becomes 1... there is a propogation delay of 1 for c to switch over to 0 hence it becomes 0 at 3 time units

*Same logic applies to d

*e and f are meant to be constant 1 or 0 but seem to be affected by something.

What's really going on here? Is it related to a boolean function or soemthing. If so what?
Issue 2:
Does anyone have a simple way or logical approach in which to produce a simple circuit (using XOR, AND, OR, NOT, NAND boolean functions with:

*

*static race condition - when the value is meant to be constant

*dynamic race condition - when a value is expected to change

Many thanks in advance!

A: Okay, so race conditions in asynchronous circuits happen when inputs change at different times  for a gate. Let's say your logical function looks like this
λ = ab + ~b~a

the most straightforward way to implement this function with gates looks like
NOTE: I assume your basic building blocks are AND, OR, and NOT. Obviously in CMOS circuits, NAND, NOR and NOT is how you build circuits, but the general principal stays the same. I also assume AND, NOR, and NOT have the same delay when in reality NAND and NOR have different delays if the output goes form 0 to 1 or 1 to 0, and NOT is about 20% faster than NAND or NOR.
a ->| AND |-------->| OR | -> λ
b ->|  1  |         |    |
                    |    |
a ->| NOT |->|AND|->|    |
b ->| NOT |->| 2 |  |    |

Now, assume that AND and NOT both have a delay of 2ns. That means the OR gate sees the value at it's first position change 2 ns before it sees the value at its second position change.
Which means if a and b both go from 1 to 0, you would expect λ to stay the same, since the output of the first AND gate is going from 1 to 0, but the output of the AND gate goes from 0 to 1, meaning the OR condition stays true.
However, if you get the output from the second AND gate a little bit after the first AND gate, then your OR gate will momentarily see 0,0 at it's input while transitioning from 1,0 to 0,1. Which means λ will have a momentary dip and it'll look like
     __
   a   |___________
     __
   b   |___________
     ____
AND1     |_________
            _______
AND2 ______|
     ______   _____
   λ       |_|

If you look at the inputs of the OR gate right between when AND1 goes down and AND2 goes up, it propagates a 0 through the OR gate, and sure enough, there's a dip in the output 2ns later.
That's a general overview for how race conditions arise. Hope that helps you understand your question.


Q: How to Write a Data Trigger to open Popup by Clicking dynamic Button in WPF? I'm having a dynamic Button in my WPF application, while clicking any one of the button the popup should open and the corresponding Button should turn the Background Color to Orange and rest of the Button should be in default Backgroud Color using DataTrigger and one more condition, at the time of Popup close, the corresponding Button Background Color should turn to the Default Color.

Note: I Can't able to give Name for the Buttons because of Dynamic
  Creation. Here I placed 5 Buttons without Name Property, Consider the
  Button as Dynamic Creation

My XAML Source Code is
<Grid>
    <Grid Height="30px" VerticalAlignment="Top" Margin="0,50,0,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
        </Grid.ColumnDefinitions>
        <Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Two" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Three" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Four" Grid.Column="3" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Five" Grid.Column="4" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
    </Grid>
    <Grid>
        <Popup Name="sPop" Placement="Mouse" StaysOpen="False">
            <Grid>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/>
            </Grid>
        </Popup>
    </Grid>
</Grid>

A: You cannot do it using DataTriggers. DataTriggers are for Data-Based scenarios, so if you are using DataBinding, then use them.
Recommended approach :
Assign a name to your Popup. And use Behaviors.
<Button ...>
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:Interaction.Behaviors>
                <ei:ConditionBehavior>
                    <ei:ConditionalExpression>
                        <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/>
                    </ei:ConditionalExpression>
                </ei:ConditionBehavior>
            </i:Interaction.Behaviors>
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

To use Blend assemblies :
Add reference to System.Windows.Interactivity and Microsoft.Expression.Interactions and following namespaces :
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

To revert back old Background of the source Button :
<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:Interaction.Behaviors>
                <ei:ConditionBehavior>
                    <ei:ConditionalExpression>
                        <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/>
                    </ei:ConditionalExpression>
                </ei:ConditionBehavior>
            </i:Interaction.Behaviors>

            <!-- Store Button's old Background -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="Tag" Value="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/>

            <!-- Change Button's Background -->
            <ei:ChangePropertyAction PropertyName="Background" Value="Purple"/>

            <!-- Open Popup -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/>

            <!-- Save this Button, Popup will use it to revert back its old Background -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="PlacementTarget" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/>

        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

<Popup x:Name="Popup1" Placement="Mouse" StaysOpen="False">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closed">
            <ei:ChangePropertyAction
                        TargetObject="{Binding PlacementTarget, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}"
                        PropertyName="Background"
                        Value="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/>
    </Grid>
</Popup>

A: I tried to achieve what you asking for without using DataTrigger.
This is simple style trigger for changing background:
<Style TargetType="Button">
    <Style.Triggers>
        <Trigger Property="Button.IsFocused" Value="True">
            <Setter Property="Button.Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

Each your button can handle Click event:
<Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Button_Click" />
...

And we need to take your Popup somehow. I just named it:
<Popup Name="popup" Placement="Mouse" StaysOpen="False">
...

Click event is simple:
private void Button_Click(object sender, RoutedEventArgs e) {
    var button = sender as Button;
    if (popup.IsOpen) { popup.IsOpen = false; }
    popup.PlacementTarget = button;
    popup.IsOpen = true;
}

So it works like you want.


Q: Expensive to set UILabel.attributedText to the same value? I have a view controller within my app that I use for debugging purposes to display some of the internals of the app (only for local xcode builds, the app store version doesn't have this controller).
In this controller, I have a label which I want to reflect the state of an internal component (specifically, I want it to display whether that component is enabled or disabled).
My questions:
#1: Is it expensive to set the .attributedText property of a UILabel to the same value as it was before, or should I cache the old value and only set the property when it changes?
#2: What about the .text (non-attributed) property?
I'm currently using the following code:
// Schedule timer to update the control panel. (This is debug-only, so not worth
// the complexity of making this event-based)
Timer.scheduledTimer(withTimeInterval: 0.5,
                 repeats: true) { [weak self] timer in

    DispatchQueue.main.async {

        // Stop timer if we've been dealloced or are no longer being presented
        guard let strongSelf = self,
              strongSelf.isBeingPresented else
        {
            timer.invalidate()
            return
        }

        // "Something Enabled / Disabled" label
        let somethingIsEnabled = strongSelf.someDepenency.isEnabled
        let somethingEnabledString = NSMutableAttributedString(string: "Something ")

        somethingEnabledString.append(NSAttributedString(string: isEnabled ? "Enabled" : "Disabled",
                                                         attributes: isEnabled ? nil : [NSForegroundColorAttributeName: UIColor(xtHardcodedHexValue: "0xCD0408")]))
        strongSelf.somethingEnabledLabel?.attributedText = somethingEnabledString

    }
}

A: Before I share some numbers, I'd highly recommend to not perform such premature optimizations. Consider the following code:
private func getAttributedString() -> NSMutableAttributedString{
    let attributedString = NSMutableAttributedString(string: "Something ")
    attributedString.append(NSAttributedString(string: "Enabled",
                                                     attributes:  [NSForegroundColorAttributeName: UIColor(rgb: 0xCD0408)]))
    return attributedString
}

//overwrites attributed text 100000 times
@IBAction func overwriteAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite attributed text is ")
    for _ in 1 ... 100000{
        label.attributedText = getAttributedString()
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites attributed text 100 times
@IBAction func cacheAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to selectively overwrite attributed text is ")
    for i in 1 ... 100000{
        if i % 1000 == 0 {
            label.attributedText = getAttributedString()
        }
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites text 100000 times
@IBAction func overWriteText(_ sender: Any) {
    let defaultText = "Hello World"
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite text is ")
    for _ in 1 ... 100000{
        label.text = defaultText
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

Here are the results:
Time taken to overwrite attributed text is 0.597925961017609
Time taken to selectively overwrite attributed text is 0.004891037940979
Time taken to overwrite text is 0.0462920069694519

The results speak for themselves, but I leave it you if such optimizations are even needed.

A: While 7to4 is correct in regards to premature optimizations, the demo code he's using is misleading.  The .attributedText setter itself is actually faster than setting .text; creating the attributed string is the bottleneck.  Here's a modified version of his code that includes a method where the attributed string is pre-cached:
private func getAttributedString() -> NSMutableAttributedString{
    let attributedString = NSMutableAttributedString(string: "Something ")
    attributedString.append(NSAttributedString(string: "Enabled",
                                               attributes:  [NSAttributedStringKey.foregroundColor: UIColor.red]))
    return attributedString
}

//overwrites attributed text 100000 times
@IBAction func overwriteAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite attributed text is ")
    for _ in 1 ... 100000{
        label.attributedText = getAttributedString()
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites attributed text 100000 times with a cached string
@IBAction func overwriteAttributedTextWithCachedString(_ sender: Any) {
    let timeBeforeAction = Date.init()
    let attributedString = getAttributedString()
    print ("Time taken to overwrite attributed text with cached string is ")
    for _ in 1 ... 100000{
        label.attributedText = attributedString
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites text 100000 times
@IBAction func overWriteText(_ sender: Any) {
    let defaultText = "Hello World"
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite text is ")
    for _ in 1 ... 100000{
        label.text = defaultText
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

Results:
Time taken to overwrite attributed text is
0.509455919265747
Time taken to overwrite attributed text with cached string is
0.0451710224151611
Time taken to overwrite text is
0.0634149312973022

On average, the .attributedText setter itself is about 30~40% faster than the .text setter.  That said, take note that it probably takes a lot of labels before this actually becomes a bottleneck.  Also remember that (if by some crazy circumstance) this is your bottleneck, this optimization is only effective if the attributed string is pre-allocated ahead of time.


Q: NVARCHAR to VARCHAR2 insert I have the following table structure:
UDA_ID (NUMBER)
Translation (NVARCHAR2)

I need to insert in the table
UDA_ID (NUMBER)
Translation (VARCHAR2)

How do i convert NVARCHAR2 to VARCHAR2 ?

A: You can try like this:
insert into mytable(Translation)
(select to_char(Translation) from sometable);

or like
insert into mytable(Translation)
(select to_char('yourValue') from dual);


Q: VB 6.0 debugging breakpoint doesn't hit I have a VB 6.0 Project having Class (cls) files. When I start (Debug) my project, and try to execute following statement in Classic ASP page,
Set objMyObject = Server.CreateObject("ProjName.ClassName")

No breakpoint is hit and following error occurs.

Microsoft VBScript runtime error '800a01ad'  ActiveX component can't
  create object

While if I use the same statement in another VB Project (test project) then breakpoint hits with no error.
Can anyone help ?

A: Well you are trying to create an instance of a COM object with the name  'ProjName.ClassName' - which is unlikely to be a real COM object.
Either your COM class needs to be one that has been registered in Windows, or it needs to be a class defined within your VB project.
The example in MSDN is:
 Sub CreateADODB()
    Dim adoApp As Object
    adoApp = CreateObject("ADODB.Connection")
End Sub

Where ADODB.Connection is a COM class that has been previously registered in Windows.  The code you have provided above is trying to instantiate a non existant class (unless it is already within the same VB project).
You say that the other project this works, then I will hazard a guess that the test project has a class called ClassName.
Ok -Updated.  The error code is not 'DLL Missing' - It is likely to be some reason why the COM object could not be instantiated.  The following Microsoft support page suggests some reasons and ways of tracking down the problem.  Its likely to be some sort of missing dependency to the DLL.
http://support.microsoft.com/kb/194801


Q: Line Chart (Currency) I'm trying to develop a line chart using a third-party API and I'm using both react-chartjs-2 and chart.js
The problem is, the line doesn't appear in the chart and I assume the reason is: the date. This is my first time to develop a web application using Chart.js. Also, I read the documentations and couldn't find a solution.
dateDate which is an array that contains all dates. The Array has dates inside of it, not objects.
I console.log'd the date in using the map loop and it worked, but it doesn't appear in the chart. I don't know the reason behind it.
Here is the console.log:
2023-01-10 App.jsx:66 2023-01-11 App.jsx:66 2023-01-12 App.jsx:66 2023-01-13 App.jsx:66 2023-01-14 App.jsx:66 2023-01-15 App.jsx:66 2023-01-16 App.jsx:66 2023-01-17 App.jsx:66 2023-01-18 App.jsx:66 2023-01-19 App.jsx:66 2023-01-20 App.jsx:66 2023-01-21 App.jsx:66 2023-01-22 App.jsx:66 2023-01-23
RESTful API
When you check the picture of the API, you'll find out that the date is the key and its value is an object of all costs. So, I have to separate them all.
Line Chart
function App() {
  const [euroCurrencyData, setEuroCurrencyData] = useState([]);
  const [dateData, setDateData] = useState([]);
  const [candianCurrencyData, setCandianCurrencyData] = useState([]);

  // CHART DATA
  const [chartData, setChartData] = useState({
    labels: dateData.map((date) => date),
    datasets: [
      {
        label: "EUR",
        data: euroCurrencyData.map((currency) => currency.EUR),
        backgroundColor: ["red", "green", "blue", "black"],
      },
      {
        label: "CAD",
        data: candianCurrencyData.map((currency) => currency.CAD),
        backgroundColor: ["green", "blue", "yellow", "green"],
      },
    ],
  });

  // EURO FETCH

  const getEuroData = async () => {
    const res = await axios.get(
      "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=EUR&date_from=2022-12-23T07%3A50%3A10.865Z&date_to=2023-01-23T07%3A50%3A10.866Z"
    );

    const data = res.data.data;
    const euroCurrency = Object.values(data);
    const currencyDate = Object.keys(data);

    setEuroCurrencyData(euroCurrency);

    setDateData(currencyDate);
  };

  // CANDIAN FETCH

  const getCandianData = async () => {
    const res = await axios.get(
      "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=CAD&date_from=2022-12-23T13%3A05%3A35.472Z&date_to=2023-01-23T13%3A05%3A35.473Z"
    );

    const data = res.data.data;
    const candianCurrency = Object.values(data);

    setCandianCurrencyData(candianCurrency);
  };

  useEffect(() => {
    getEuroData();
    getCandianData();
  }, []);

  return (

        <LineChart chartData={chartData} />

  );
}

import { Line } from "react-chartjs-2";
import { Chart as ChartJS } from "chart.js";
import Chart from "chart.js/auto";
const LineChart = ({ chartData }) => {
  return <Line data={chartData} />;

};


Q: gperftools: modify makefile to install in a different folder? I was installing  gperftools:
https://code.google.com/p/gperftools/
Everything worked, and I see that the project links to /usr/local/lib
I'd like to put the library in a folder local to my project, instead.
The reasoning behind this is that I'm putting the project on different machines, and I just need to link against the libprofiler and libtcmalloc libraries, instead of the entire package, that also comes with the pprof and such.
The machines also have different architectures, so I actually need to build into that directory, instead of copy-pasting over
Is this a trivial thing to do?

A: gperftools uses autoconf/automake, so you can do
./configure --prefix=/path/to/whereever
make
make install

This works for all autotools projects, unless they are severely broken.
On that note, it is generally a good idea to read the INSTALL file in a source tree to find out about this sort of stuff. There is one in the gperftools sources, and this is documented there.


Q: Microsoft.EntityFrameworkCore dont have method IsOptional() for PropertyBuilder I try transfer my solution from .Net Framowork to .Net Core.When I did mapping and I dint found method IsOptional() for PropertyBuilder:
.Net Framowork:
    public class PictureMap : EntityTypeConfiguration<PictureExt>
{
    public PictureMap()
    {
        this.ToTable("Picture");
        this.HasKey(p => p.Id);
        this.Property(p => p.SeoFilename).HasMaxLength(300);
        this.Property(p => p.ExternalUrl).IsOptional();
    }
}

and its work , but use EntityFrameworkCore:look in image
where I might found IsOptional()?

A: There is not IsOptional in EntityFrameworkCore but there is IsRequired to do the oposite. By default field are nullable if the C# type is nullable.

A: You can achieve the same effect with IsRequired(false).  This will override annotations like [Required] so be careful.  On another thread, it was pointed out that annotations that affect EF models or make no sense [Display...] should not be part of the EF model.  Move them to a ViewModel or DTO object.


Q: Reading multiple offline html files to a list in R I have rawdata as 20 offline html files stored in following format
../rawdata/1999_table.html
../rawdata/2000_table.html
../rawdata/2001_table.html
../rawdata/2002_table.html
.
.
../rawdata/2017_table.html

These files contain tables that I am extracting and reshaping to a particular format.
I want to read these files at once to a list and process them one by one through a function that I have written.
What I tried:
I put the names of these files into an Excel file called filestoread.xlsx and used a for loop to load these files using the names mentioned in the sheet. But it doesn't seem to work
filestoread <- fread("../rawdata/filestoread.csv")

x <- list()
for (i in nrow(filestoread)) {
  x[[i]] <- read_html(paste0("../rawdata/", filestoread[i]))
}

How can this be done?
Also, after reading the HTML files I want to extract the tables from them and reshape them using a function I wrote after converting it to a data table.
My final objective is to rbind all the tables and have a single data table with year wise entries of the tables in the html file.

A: First save path of your data on one of the following ways.
Either, hardcoded
filestoread <- paste0("../rawdata/", 1999:2017, "_table.html")

or reading all html files in the directory
filestoread <- list.files(path = "../rawdata/", pattern="\\.html$")

Then use lapply()
library(rvest)
lapply(filestoread, function(x) try(read_html(x)))

Note: try() runs the code even when there is a file missing (throwing error).
The second part of your question is a little broad, depends on the content of your files, and there are already some answers, you could consider e.g. this answer. In principle you use a combination of ?html_nodes and  ?html_table.


Q: deleting arrays during run time in C++ to spare some memory I have a C++ script running with a C++98 version on a microcontroller ( No upgrade is possible). In this script I need to initialize two vectors of doubles of 405 already existing elements each. I tried initializating two arrays : double a[405]= {7.05925826e+07, ...}; and double b [405]= {arr[0], arr[0]*arr[1]...};. a[405] is defined in the following way:
double a[405] = {a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19], a[20], a[21], a[22], a[23], a[24], a[25], a[26], a[0]*a[0], a[0]*a[1], a[0]*a[2], a[0]*a[3], a[0]*a[4], a[0]*a[5], a[0]*a[6], a[0]*a[7], a[0]*a[8], a[0]*a[9], a[0]*a[10], a[0]*a[11], a[0]*a[12], a[0]*a[13], a[0]*a[14], a[0]*a[15], a[0]*a[16], a[0]*a[17], a[0]*a[18], a[0]*a[19], a[0]*a[20], a[0]*a[21], a[0]*a[22], a[0]*a[23], a[0]*a[24], a[0]*a[25], a[0]*a[26], a[1]*a[1], a[1]*a[2], a[1]*a[3], a[1]*a[4], a[1]*a[5], a[1]*a[6], a[1]*a[7], a[1]*a[8], a[1]*a[9], a[1]*a[10], a[1]*a[11], a[1]*a[12], a[1]*a[13], a[1]*a[14], a[1]*a[15], a[1]*a[16], a[1]*a[17], a[1]*a[18], a[1]*a[19], a[1]*a[20], a[1]*a[21], a[1]*a[22], a[1]*a[23], a[1]*a[24], a[1]*a[25], a[1]*a[26], a[2]*a[2], a[2]*a[3], a[2]*a[4], a[2]*a[5], a[2]*a[6], a[2]*a[7], a[2]*a[8], a[2]*a[9], a[2]*a[10], a[2]*a[11], a[2]*a[12], a[2]*a[13], a[2]*a[14], a[2]*a[15], a[2]*a[16], a[2]*a[17], a[2]*a[18], a[2]*a[19], a[2]*a[20], a[2]*a[21], a[2]*a[22], a[2]*a[23], a[2]*a[24], a[2]*a[25], a[2]*a[26], a[3]*a[3], a[3]*a[4], a[3]*a[5], a[3]*a[6], a[3]*a[7], a[3]*a[8], a[3]*a[9], a[3]*a[10], a[3]*a[11], a[3]*a[12], a[3]*a[13], a[3]*a[14], a[3]*a[15], a[3]*a[16], a[3]*a[17], a[3]*a[18], a[3]*a[19], a[3]*a[20], a[3]*a[21], a[3]*a[22], a[3]*a[23], a[3]*a[24], a[3]*a[25], a[3]*a[26], a[4]*a[4], a[4]*a[5], a[4]*a[6], a[4]*a[7], a[4]*a[8], a[4]*a[9], a[4]*a[10], a[4]*a[11], a[4]*a[12], a[4]*a[13], a[4]*a[14], a[4]*a[15], a[4]*a[16], a[4]*a[17], a[4]*a[18], a[4]*a[19], a[4]*a[20], a[4]*a[21], a[4]*a[22], a[4]*a[23], a[4]*a[24], a[4]*a[25], a[4]*a[26], a[5]*a[5], a[5]*a[6], a[5]*a[7], a[5]*a[8], a[5]*a[9], a[5]*a[10], a[5]*a[11], a[5]*a[12], a[5]*a[13], a[5]*a[14], a[5]*a[15], a[5]*a[16], a[5]*a[17], a[5]*a[18], a[5]*a[19], a[5]*a[20], a[5]*a[21], a[5]*a[22], a[5]*a[23], a[5]*a[24], a[5]*a[25], a[5]*a[26], a[6]*a[6], a[6]*a[7], a[6]*a[8], a[6]*a[9], a[6]*a[10], a[6]*a[11], a[6]*a[12], a[6]*a[13], a[6]*a[14], a[6]*a[15], a[6]*a[16], a[6]*a[17], a[6]*a[18], a[6]*a[19], a[6]*a[20], a[6]*a[21], a[6]*a[22], a[6]*a[23], a[6]*a[24], a[6]*a[25], a[6]*a[26], a[7]*a[7], a[7]*a[8], a[7]*a[9], a[7]*a[10], a[7]*a[11], a[7]*a[12], a[7]*a[13], a[7]*a[14], a[7]*a[15], a[7]*a[16], a[7]*a[17], a[7]*a[18], a[7]*a[19], a[7]*a[20], a[7]*a[21], a[7]*a[22], a[7]*a[23], a[7]*a[24], a[7]*a[25], a[7]*a[26], a[8]*a[8], a[8]*a[9], a[8]*a[10], a[8]*a[11], a[8]*a[12], a[8]*a[13], a[8]*a[14], a[8]*a[15], a[8]*a[16], a[8]*a[17], a[8]*a[18], a[8]*a[19], a[8]*a[20], a[8]*a[21], a[8]*a[22], a[8]*a[23], a[8]*a[24], a[8]*a[25], a[8]*a[26], a[9]*a[9], a[9]*a[10], a[9]*a[11], a[9]*a[12], a[9]*a[13], a[9]*a[14], a[9]*a[15], a[9]*a[16], a[9]*a[17], a[9]*a[18], a[9]*a[19], a[9]*a[20], a[9]*a[21], a[9]*a[22], a[9]*a[23], a[9]*a[24], a[9]*a[25], a[9]*a[26], a[10]*a[10], a[10]*a[11], a[10]*a[12], a[10]*a[13], a[10]*a[14], a[10]*a[15], a[10]*a[16], a[10]*a[17], a[10]*a[18], a[10]*a[19], a[10]*a[20], a[10]*a[21], a[10]*a[22], a[10]*a[23], a[10]*a[24], a[10]*a[25], a[10]*a[26], a[11]*a[11], a[11]*a[12], a[11]*a[13], a[11]*a[14], a[11]*a[15], a[11]*a[16], a[11]*a[17], a[11]*a[18], a[11]*a[19], a[11]*a[20], a[11]*a[21], a[11]*a[22], a[11]*a[23], a[11]*a[24], a[11]*a[25], a[11]*a[26], a[12]*a[12], a[12]*a[13], a[12]*a[14], a[12]*a[15], a[12]*a[16], a[12]*a[17], a[12]*a[18], a[12]*a[19], a[12]*a[20], a[12]*a[21], a[12]*a[22], a[12]*a[23], a[12]*a[24], a[12]*a[25], a[12]*a[26], a[13]*a[13], a[13]*a[14], a[13]*a[15], a[13]*a[16], a[13]*a[17], a[13]*a[18], a[13]*a[19], a[13]*a[20], a[13]*a[21], a[13]*a[22], a[13]*a[23], a[13]*a[24], a[13]*a[25], a[13]*a[26], a[14]*a[14], a[14]*a[15], a[14]*a[16], a[14]*a[17], a[14]*a[18], a[14]*a[19], a[14]*a[20], a[14]*a[21], a[14]*a[22], a[14]*a[23], a[14]*a[24], a[14]*a[25], a[14]*a[26], a[15]*a[15], a[15]*a[16], a[15]*a[17], a[15]*a[18], a[15]*a[19], a[15]*a[20], a[15]*a[21], a[15]*a[22], a[15]*a[23], a[15]*a[24], a[15]*a[25], a[15]*a[26], a[16]*a[16], a[16]*a[17], a[16]*a[18], a[16]*a[19], a[16]*a[20], a[16]*a[21], a[16]*a[22], a[16]*a[23], a[16]*a[24], a[16]*a[25], a[16]*a[26], a[17]*a[17], a[17]*a[18], a[17]*a[19], a[17]*a[20], a[17]*a[21], a[17]*a[22], a[17]*a[23], a[17]*a[24], a[17]*a[25], a[17]*a[26], a[18]*a[18], a[18]*a[19], a[18]*a[20], a[18]*a[21], a[18]*a[22], a[18]*a[23], a[18]*a[24], a[18]*a[25], a[18]*a[26], a[19]*a[19], a[19]*a[20], a[19]*a[21], a[19]*a[22], a[19]*a[23], a[19]*a[24], a[19]*a[25], a[19]*a[26], a[20]*a[20], a[20]*a[21], a[20]*a[22], a[20]*a[23], a[20]*a[24], a[20]*a[25], a[20]*a[26], a[21]*a[21], a[21]*a[22], a[21]*a[23], a[21]*a[24], a[21]*a[25], a[21]*a[26], a[22]*a[22], a[22]*a[23], a[22]*a[24], a[22]*a[25], a[22]*a[26], a[23]*a[23], a[23]*a[24], a[23]*a[25], a[23]*a[26], a[24]*a[24], a[24]*a[25], a[24]*a[26], a[25]*a[25], a[25]*a[26], a[26]*a[26]};

and then converting them using this function:
std::vector<double > ArrayToVector(double* arr, size_t arr_len) {
return std::vector<double>(arr, arr + arr_len);
}

std::vector<double> vec1= ArrayToVector(a,405);
std::vector<double> vec2= ArrayToVector(b,405);

The conversion of the arrays into a vectors causes memory problems. I am looking for a way to delete the first array a[405] just after converting it to vector in order to spare some memory for the second array conversion. I tried using new operator but that didn't work for me . Any other solution to reduce memory usage is appreciated.
Then I use a[] and b[] to calculate their scalar product using this function:
double scalar_product(std::vector<double> a, std::vector<double> b)
{
    if( a.size() != b.size() ) // error check
    {
        //puts( "Error a's size not equal to b's size" ) ;
        return -1 ;  // not defined
    }
    // compute
    double product = 0;
    for (unsigned int i = 0; i <= a.size() - 1; i++)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

A: As some people have already suggested in comments, you don't really need to convert your arrays to vectors - just work directly with the arrays. All you need to add is the size of the arrays as a third parameter to your function. For that you obviously need to know the size, but since this is running on a microcontroller, where memory budget is tight, I'm relatively certain that you have access to the size info. So it could look like:
double scalar_product(double a[], double b[], unsigned int size)
{
    // compute
    double product = 0;
    for (unsigned int i = 0; i <= size - 1; i++)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

I'm assuming that their sizes are the same (they should) but even if not, you could use this to calculate a (partial) scalar product for two differently sized arrays, by supplying the shorter one's size.

A: You are not allocating your double[] arrays dynamically via new[], so they cannot be freed dynamically.  They are being declared in automatic memory, so they will be freed only when they go out of scope.
Since you are concerned with limited memory usage, your best option is to simply not convert your double[] arrays to std::vector<double> at all. Change your scalar_product() function instead so it can handle the original double[] arrays as-is, eg:
double scalar_product(const double *a, size_t a_size, const double *b, size_t b_size)
{
    if( a_size != b_size ) // error check
    {
        //puts( "Error a's size not equal to b's size" ) ;
        return -1 ;  // not defined
    }
    // compute
    double product = 0;
    for (size_t i = 0; i < a_size; ++i)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

double a[405] = ...;
double b[405] = ...;
double product = scalar_product(a, 405, b, 405);

/*
if, for some reason, you also needed to get the product of vectors,
you can do this:

double scalar_product(const std::vector<double> &a, const std::vector<double> &b)
{
    return scalar_product(&a[0], a.size(), &b[0], b.size());
}

vector<double> a = ...;
vector<double> b = ...;
double product = scalar_product(a, b);
*/

Or:
double scalar_product(const double *a, const double *b, size_t n)
{
    // compute
    double product = 0;
    for (size_t i = 0; i < n; ++i)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

double a[405] = ...;
double b[405] = ...;
double product = scalar_product(a, b, 405);

/*
if, for some reason, you also needed to get the product of vectors,
you can do this:

double scalar_product(const std::vector<double> &a, const std::vector<double> &b)
{
    return (a.size() == b.size())
        ? scalar_product(&a[0], &b[0], a.size())
        : -1.0;
}

vector<double> a = ...;
vector<double> b = ...;
double product = scalar_product(a, b);
*/

Alternatively, you can let the compiler deduce the array sizes for you, if you are passing in the original arrays directly, and not passing in pointers to the arrays:
template<size_t a_size, size_t b_size>
double scalar_product(const double (&a)[a_size], const double (&b)[b_size])
{
    if( a_size != b_size ) // error check
    {
        //puts( "Error a's size not equal to b's size" ) ;
        return -1 ;  // not defined
    }
    // compute
    double product = 0;
    for (size_t i = 0; i < a_size; ++i)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

double a[405] = ...;
double b[405] = ...;
double product;

product = scalar_product(a, b); // OK

double *pa = a;
double *pb = b;
product = scalar_product(pa, pb); // COMPILER ERROR

/*
this approach doesn't work with vectors, so you will need a
separate overload of scalar_product() for that...
*/

Or:
template<size_t N>
double scalar_product(const double (&a)[N], const double (&b)[N])
{
    // compute
    double product = 0;
    for (size_t i = 0; i < N; ++i)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

double a[405] = ...;
double b[405] = ...;
double product;

product = scalar_product(a, b); // OK

double c[404] = ...;
double d[405] = ...;

product = scalar_product(c, d); // COMPILER ERROR

/*
this approach doesn't work with vectors, so you will need a
separate overload of scalar_product() for that...
*/

Otherwise, if the array size is constant at compile-time, then just hard-code it:
const size_t ArrSize = 405;

double scalar_product(const double (&a)[ArrSize], const double (&b)[ArrSize])
{
    // compute
    double product = 0;
    for (size_t i = 0; i < ArrSize; ++i)
        product += (a[i])*(b[i]); // += means add to product
    return product;
}

double a[ArrSize] = ...;
double b[ArrSize] = ...;
double product = scalar_product(a, b);

/*
this approach doesn't work with vectors, so you will need a
separate overload of scalar_product() for that...
*/

A: An array must be dynamically allocated (using the new[] operator) in order to use the delete[] operator to free it. As the comments have mentioned, you should post how you create your arrays so we can get a better understanding of how they are stored in memory.
double a* = new double[size];
// do stuff with a
delete[] a;

The above example is legal and will do what you asked.


Q: How to find the distribution in python? I have data set from Goodreads with Number of books read over a year with details like number of pages of the each book, date read etc. I want to know in which month/week I have read most/least. How do I do that in Python ?


Q: iCloud - Moving the file completed I can able to move a file from the local directory to iCloud using the condition setUbiquitous:YES. The file has been moved successfully. If the file size is large, it takes certain time to complete moving. Is there any method to identify, if the file has completed moving to iCloud? Thanks in advance for your answers.

A: Note: I haven't done this myself, so all the info below is purely from reading the documentation:
The NSMetadataItem class has, among others, an attribute key called NSMetadataUbiquitousItemIsUploadedKey. Knowing this, you should be able to set up an NSMetadataQuery that notifies you once the item has been uploaded.

A: You can check with NSUURL getResourceValue:forKey:error: method
NSURLUbiquitousItemIsUploadedKey—Indicates that locally made changes were successfully uploaded to the iCloud server.
NSURLUbiquitousItemIsUploadingKey—Indicates that locally made changes are being uploaded to the iCloud server now.
NSURLUbiquitousItemPercentUploadedKey—For an item being uploaded, indicates what percentage of the changes have already been uploaded to the server.
For details: https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40007072-CH5-SW1


Q: OSX equivalent of SymGetLineFromAddr or SymGetLineFromAddr64 I want to add source file and line numbers to my backtraces, on Windows there is a nice function SymGetLineFromAddr64 which provides such information if available. I can't find something similar on mac.
dladdr outputs only symbol name without file information.

A: There is no public equivalent to SymGetLineFromAddr64 on OS X, but you can get source file and line number with the atos(1) developer tool.
Here is some sample code to get a fully symbolized backtrace.
#import <Foundation/Foundation.h>

static NSArray * Backtrace(NSArray *callStackReturnAddresses)
{
    NSMutableArray *backtrace = [NSMutableArray new];
    for (NSNumber *address in callStackReturnAddresses)
    {
        NSString *hexadecimalAddress = [NSString stringWithFormat:@"0x%0*lx", (int)sizeof(void*) * 2, address.unsignedIntegerValue];
        NSTask *task = [NSTask new];
        NSPipe *pipe = [NSPipe pipe];
        task.launchPath = @"/usr/bin/xcrun";
        task.arguments = @[ @"atos", @"-d", @"-p", @(getpid()).description, hexadecimalAddress ];
        task.standardOutput = pipe;
        NSString *symbol = @"???";
        @try
        {
            [task launch];
            NSData *data = [pipe.fileHandleForReading readDataToEndOfFile];
            symbol = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
            symbol = [symbol stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
            [task waitUntilExit];
        }
        @catch (NSException *exception) {}
        [backtrace addObject:[NSString stringWithFormat:@"%@ %@", hexadecimalAddress, symbol]];
    }
    return [backtrace copy];
}

static void test(void)
{
    NSLog(@"%@", Backtrace([NSThread callStackReturnAddresses]));
}

int main(int argc, const char * argv[])
{
    test();
    return 0;
}

Running this code will produce the following output:
0x000000010000134e test (in a.out) (main.m:31)
0x000000010000131b main (in a.out) (main.m:36)
0x00007fff8c0935fd start (in libdyld.dylib) + 1


Q: Rubycas-server character encoding issue (Internal server error) Since a couple of months ago we are using in production environment a rubycass-server 1.0 validating against Active directory (Microsoft 2008 r2 server). We are using ruby 1.9.2p180, sinatra-1.1.3...  We are having problems with Spanish and Catalan languages. If a user types ñ or ç … in the login or password field when he sends the form it produces an “internal server error” message. I have activated the debug mode in the config.yml options but when this error rises it does not appear any hint into the log file. A couple of days ago I tried the last version of rubycas 1.1.0 and this error (Internal server..) didn’t happen but if the login/password had any of this characters the validation always failed with the message “password incorrect”. I think it is an encoding error.
Has anybody found a solution to this problem?
Thanks in advance,

A: Solved. Problem was caused because we were using an old version of net-ldap (0.1.1). I updated this gem to the last version (0.3.1) and works like a charm.


Q: alternative method for getting http response in android I get the null response with
HttpResponse response = client.execute(post);

This method some time give correct response but mostly give the null response without any code change. I also tried it using the AsyncTask, but got same behavior. Following is my code with AsyncTask. If any suggestion please tell me.
Thank you.
protected void onPreExecute() {
     client = new DefaultHttpClient();
     HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT_MS);
     HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT_MS);
     post = new HttpPost("http://www.google.co.in/m");
     pairs = new ArrayList<NameValuePair>();
     pairs.add(new BasicNameValuePair("hl", "en"));
     pairs.add(new BasicNameValuePair("gl", "us"));
     pairs.add(new BasicNameValuePair("source", "android-launcher-widget"));
     pairs.add(new BasicNameValuePair("q", "persistent"));
     try {
            post.setEntity(new UrlEncodedFormEntity(pairs));
            SystemClock.sleep(400);

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    this.dialog.setMessage("starts...");
    this.dialog.show();

}
@Override
protected HttpResponse doInBackground(Void... arg0) {
    try {
        HttpResponse response = client.execute(post); //this returns null responce
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
             return response;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        //Toast.makeText(url.this, "problem in execute....", 20).show();
        // TODO Auto-generated catch block
        //put the balance is empty dialog box here.
        e.printStackTrace();
    }catch(NullPointerException e)
    {
        e.printStackTrace();
    }

    return null;
}

my log says..
04-20 20:19:55.877: WARN/System.err(365): java.net.UnknownHostException: www.google.co.in
04-20 20:19:55.897: WARN/System.err(365): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)

04-20 20:19:55.897: WARN/System.err(365): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)

04-20 20:19:55.907: WARN/System.err(365): at java.net.InetAddress.getAllByName(InetAddress.java:256)

04-20 20:19:55.907: WARN/System.err(365): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)

04-20 20:19:55.907: WARN/System.err(365): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)

04-20 20:19:55.927: WARN/System.err(365): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-20 20:19:55.927: WARN/System.err(365): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)

04-20 20:19:55.937: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

04-20 20:19:55.937: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

04-20 20:19:55.947: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

04-20 20:19:55.947: WARN/System.err(365): at comm.sample.Urlasync$AddStringTask.doInBackground(Urlasync.java:82)

04-20 20:19:55.947: WARN/System.err(365): at comm.sample.Urlasync$AddStringTask.doInBackground(Urlasync.java:1)

04-20 20:19:55.947: WARN/System.err(365): at android.os.AsyncTask$2.call(AsyncTask.java:185)

04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)

04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.FutureTask.run(FutureTask.java:138)

04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)

04-20 20:19:55.967: WARN/System.err(365): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)

04-20 20:19:55.967: WARN/System.err(365): at java.lang.Thread.run(Thread.java:1019)

A: I ran into this same problem a few days ago. Running the HttpResponse on its own thread fixed the Null response. Try using java threading instead of the android async task.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html


Q: Testing ServiceLoader in Eclipse Plugins I have four Eclipse plugin projects (create a new Java Project, right-click, configure, Convert to Plugin Project) in my workspace. The first (my.runtime) contains an interface (MyFactoryInterface) and a class (MyClient) that defines a method (List<String> getAllFactoryNames()) that loads all implementations of that interface via java.util.ServiceLoader and calls a method (String getName()) on them, collecting the results and returning them in a list.
To test that class, I have a JUnit test in the second project (my.runtime.test, set up with my.runtime as Fragment-Host), checking if the name returned by a dummy implementation(MyDummy, returning "Dummy") I have in the my.runtime.test project is in the list returned by MyClient.getAllFactoryNames(). So far, it works fine.
In the third project (my.extension, with my.runtime as dependency) I have a class (MyHello) that uses the names returned by MyClient.getAllFactoryNames() to return a list of greetings ("Hello "+name).
Again, to test this, I have a project (my.extension.test, with my.extension as Fragment-Host) containing another Implementation (MyWorld, returning "World" as name) and a JUnit test case checking if "Hello World" is in the greetings returned by MyHello.getGreetings(). This test fails, as MyClient still only finds the MyDummy implementation, and not the MyWorld implementation. Both implementations are accompanied by matching entries in META-INF/services/my.runtime.MyFactoryInterface files.
I currently use the following code to load the implementations:
ServiceLoader<MyFactoryInterface> myFactoryLoader = ServiceLoader.load(MyFactoryInterface.class);
    for (MyFactoryInterface myFactory : myFactoryLoader) {

I know that I can supply a ClassLoader as a second argument to ServiceLoader.load, but I have no idea how to get one that knows all plugin projects... any suggestions? Or is ServiceLoader not the right tool for this problem?

A: If anyone stumbles over the same problem: the combination of ServiceLoader.load(MyFactoryInterface.class, Thread.currentThread().getContextClassLoader()) in MyClient and Thread.currentThread().setContextClassLoader(MyWorld.class.getClassLoader()); in the second test did the job.


Q: Return from function or pass into function? What would be the better way to process this data? Is this just a matter of personal preference? Guessing 2 is less prone to accidently modifying the monday...friday arrays and there is less code at this layer. Is there a best practices approach? Is there a performance difference?

*

*Like this?

        // Arrays to hold what stock price belongs to what day of the week - Note these arrays are used some way down the line
        var monday = [], tuesday = [], wednesday = [], thursday = [], friday = []

        // Sort each stock date into a day of the week
        FindDayFromDate(historyData, monday, tuesday, wednesday, thursday, friday);

        // Find the average price for each day of the week
        const avgPrices = FindAveragePricePerDay(monday, tuesday, wednesday, thursday, friday);

*Like this?

        // Sort each stock date into a day of the week - sortedDays contains arrays of monday...friday
        const sortedDays = FindDayFromDate(historyData);

        // Find the average price for each day of the week - Expand sortedDays inside function to access monday...friday
        const avgPrices = FindAveragePricePerDay(sortedDays);

A: A good function should always be free from side-effects. It should be pure and just do one specific job at a time. As a software programmer/developer, we must write source code that actually produce the output based on input. Such kind of strong pure function actually avoid all kind of side effects and code smell. Let's look at few examples to understand this.
Assume we have a function named as Greeting like below
function Greeting(name) {
  return `Hello ${name}`;
}

It is pure because you will always get the output Hello {name} for the name passed via parameter. Let's have a look at another version of same function with many side-effects.
var greeting = "Hey";

function Greeting(name) {
  return `${greeting} ${name}`;
}

Now, this function is not pure. Guess why ? Because we are not sure what output we will receive because function is actually dependent on the outer variable named as greeting . So if someone change the value of variable greeting to something else let's say Hello then obviously the output of function will change. So the function is now tightly coupled with the outer variable. That's why it is not pure function anymore.
So to conclude, you must have to write your function in such a way that there is no dependency and no side-effect and it will always do one job.
That is the best practice :)
Happy Coding :)

A: I believe the second Function "FindAveragePricePerDay" calling can be adjusted to act on single day, so that it can be reused on other places
    const avgPrices = sortedDays.map(day => FindAveragePricePerDay(day));
    /* you can also simplify the FindAveragePricePerDay using the reduce method
     following this parameters array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
so all the second line would be */
    const avgPrices = day.reduce((t,c,i,arr) => t + c/arr.length, 0);

for more info about array.reduce check this


Q: Joining multiple columns into one with union, exclude results with same id I want to join columns from multiple tables to one column, in my case column 'battery_value' and 'technical_value' into column 'value'. I want to fetch data for only given category_ids, but because of UNION, I get data from other tables as well.
I have 4 tables:
Table: car
car_id   model_name
1        e6

Table: battery
battery_category_id    car_id    battery_value
1                      1         125 kW

Table: technical_data
technical_category_id  car_id    technical_value
1                      1         5
3                      1         2008

Table: categories
category_id     category_name     category_type
1               engine power      battery
1               seats             technical
3               release year      technical

From searching, people are suggesting that I use union to join these columns. My query now looks like this:
SELECT CARS.car_id
       category_id,
       CATEGORIES.category_name,
       value,
FROM   CARS
           left join (SELECT BATTERY.battery_category_id AS category_id,
                             BATTERY.car_id              AS car_id,
                             BATTERY.value               AS value
                      FROM   BATTERY
                      WHERE `BATTERY`.`battery_category_id` IN (1)
                      UNION
                      SELECT TECHNICAL_DATA.technical_category_id AS category_id,
                          TECHNICAL_DATA.car_id            AS car_id,
                          TECHNICAL_DATA.value             AS value
                      FROM   TECHNICAL_DATA
                      WHERE `TECHNICAL_DATA`.`technical_category_id` IN (3))
    tt
                     ON CARS.car_id = tt.car_id
           left join CATEGORIES
                     ON category_id = CATEGORIES.id

So the result I want is this, because I only want to get the data where category_id 1 is in battery table:
car_id   category_id   category_name   technical_value
1        1             engine power    125 kW
1        3             release year    2008

but with the query above I get this, category_id 1 from technical table is included which is not something I want:
car_id   category_id   category_name   value
1        1             engine power    125 kW
1        1             seats           125 kW
1        3             release year    2008

How can get exclude the 'seats' row?

A: For the results you want, I don't see why the cars table is needed.  Then, you seem to need an additional key for the join to categories based on which table it is referring to.
So, I suggest:
SELECT tt.*, c.category_name
FROM ((SELECT b.battery_category_id AS category_id,
              b.car_id AS car_id, b.value AS value,
              'battery' as which
       FROM BATTERY b
       WHERE b.battery_category_id IN (1)
      ) UNION ALL
      (SELECT td.technical_category_id AS category_id,
              td.car_id AS car_id, td.value AS value,
              'technical' as which
       FROM TECHNICAL_DATA td
       WHERE td.technical_category_id IN (3)
      )
     ) tt LEFT JOIN
     CATEGORIES c
     ON c.id = tt.category_id AND
        c.category_type = tt.which;

That said, you seem to have a problem with your data model, if the join to categories requires "hidden" data such as the type.  However, that is outside the scope of the question.


Q: Accessing bazel files outside the docker I am quite new to docker environment and need help in understanding / fixing the below issue.
Scenario:
I am running an application (assume App1) inside the docker.
This application/docker uses bazel framework. So the run time files (some C++ .h and .cc files) which are getting generated are saved inside directory Bazel-App1.
I can use those generated files in some other code inside the docker. However I am not able to link those files (which are inside the bazel-App1 directory) to the codes which I am writing outside the docker.
Is there a way I can get access to those files?
Kindly let me know if you need more details to suggest me a fix.


Q: What does the dot do in Racket? I know the dot for creating a procedure, which can take an arbitrary amount of arguments, but I saw several other examples, which use the dot in other places. One example is from the docs of csv-reading:

(define next-row
  (make-csv-reader
   (open-input-file "fruits.csv")
   '((separator-chars            #\|)
     (strip-leading-whitespace?  . #t)
     (strip-trailing-whitespace? . #t))))

To me this looks like a list of configuration parameters is "set", but what does the dot do there?
Another example is from a web application tutorial from the docs (in the formlet section) as well:

; new-post-formlet : formlet (values string? string?)
; A formlet for requesting a title and body of a post
(define new-post-formlet
  (formlet
   (#%# ,{input-string . => . title}
        ,{input-string . => . body})
   (values title body)))

My guess for this example is, that the dots somehow allow to write => as an infix operator. I was able to put the => at the front of the lists and leave the dots away and it still worked at some point. I didn't try with the final version of the tutorial's code though.
However, this "infixing" wouldn't fit the first example, I think.

A: The dot is not uniquely a racket thing, but a lisp thing. A list is made out of pairs and one pair has the literal form (car . cdr) and a list of the elements 2, 3 is made up like (2 . (3 . ())) and the reader can read this, however a list that has a pair as it's cdr can be shown without the dot and the parens such that (2 . (3 . ())) is the same as (2 3 . ()). Also a dot with the special empty list in the end can be omitted so that (2 3) is how it can be read and the only way display and the REPL would print it.
What happens if you don't have a pair or null as the cdr? Then the only way to represent it is as a dotted. With (2 . (3 . 5)) you can only simplify the first dot so it's (2 3 . 5).
The literal data structure looks like an assoc with pairs as elements where the car is the key and cdr is the value. Using a new pair is just wast of space.
As an parameter list an interpreter looks at the elements and if it's a pair it binds the symbol in car, but if it's not a pair it is either finished with null or you have a rest argument symbol. It's convenient way to express it. Clojure that don't have dotted pairs use a & element while Common Lisp does dotted in structures, but not as a parameter specification since it supports more features than Scheme and Clojure and thus use special keywords to express it instead.
The second is #lang racket specific and is indeed used to support infix. If you write (5 . + . 6) a reader extension will change it to (+ 5 6) before it gets evaluated. It works the same way even if it's quoted or actual code and curlies are of course equal to normal and square parentheses so the second one actually becomes:
(define new-post-formlet
  (formlet
   (#%# ,(=> input-string title)
        ,(=> input-string body))
   (values title body)))

If you were to use #!r5rs or #!r6rs in racket (5 . + . 6) will give you a read error.


Q: What is the C++ equivalent of Python's "in" operator? What is the C++ way of checking if an element is contained in an array/list, similar to what the in operator does in Python?
if x in arr:
    print "found"
else
    print "not found"

How does the time complexity of the C++ equivalent compare to Python's in operator?

A: I guess one might make use of this thread and create a custom version of in function.
The main idea is to use SFINAE (Substitution Failure Is Not An Error) to differentiate associative containers (which have key_type member) from sequence containers (which have no key_type member).
Here is a possible implementation:
namespace detail
{
    template<typename, typename = void>
    struct is_associative : std::false_type {};

    template<typename T>
    struct is_associative<T,
        std::enable_if_t<sizeof(typename T::key_type) != 0>> : std::true_type {};

    template<typename C, typename T>
    auto in(const C& container, const T& value) ->
        std::enable_if_t<is_associative<C>::value, bool>
    {
        using std::cend;

        return container.find(value) != cend(container);
    }

    template<typename C, typename T>
    auto in(const C& container, const T& value) ->
        std::enable_if_t<!is_associative<C>::value, bool>
    {
        using std::cbegin;
        using std::cend;

        return std::find(cbegin(container), cend(container), value) != cend(container);
    }

}

template<typename C, typename T>
auto in(const C& container, const T& value)
{
    return detail::in(container, value);
}

Small usage example on WANDBOX.

A: This gives you an infix *in* operator:
namespace notstd {
  namespace ca_helper {
    template<template<class...>class, class, class...>
    struct can_apply:std::false_type{};
    template<class...>struct voider{using type=void;};
    template<class...Ts>using void_t=typename voider<Ts...>::type;

    template<template<class...>class Z, class...Ts>
    struct can_apply<Z,void_t<Z<Ts...>>, Ts...>:std::true_type{};
  }
  template<template<class...>class Z, class...Ts>
  using can_apply = ca_helper::can_apply<Z,void,Ts...>;

  namespace find_helper {
    template<class C, class T>
    using dot_find_r = decltype(std::declval<C>().find(std::declval<T>()));
    template<class C, class T>
    using can_dot_find = can_apply< dot_find_r, C, T >;
    template<class C, class T>
    constexpr std::enable_if_t<can_dot_find<C&, T>{},bool>
    find( C&& c, T&& t ) {
      using std::end;
      return c.find(std::forward<T>(t)) != end(c);
    }
    template<class C, class T>
    constexpr std::enable_if_t<!can_dot_find<C&, T>{},bool>
    find( C&& c, T&& t ) {
      using std::begin; using std::end;
      return std::find(begin(c), end(c), std::forward<T>(t)) != end(c);
    }
    template<class C, class T>
    constexpr bool finder( C&& c, T&& t ) {
      return find( std::forward<C>(c), std::forward<T>(t) );
    }
  }
  template<class C, class T>
  constexpr bool find( C&& c, T&& t ) {
    return find_helper::finder( std::forward<C>(c), std::forward<T>(t) );
  }
  struct finder_t {
    template<class C, class T>
    constexpr bool operator()(C&& c, T&& t)const {
      return find( std::forward<C>(c), std::forward<T>(t) );
    }
    constexpr finder_t() {}
  };
  constexpr finder_t finder{};
  namespace named_operator {
    template<class D>struct make_operator{make_operator(){}};

    template<class T, char, class O> struct half_apply { T&& lhs; };

    template<class Lhs, class Op>
    half_apply<Lhs, '*', Op> operator*( Lhs&& lhs, make_operator<Op> ) {
      return {std::forward<Lhs>(lhs)};
    }

    template<class Lhs, class Op, class Rhs>
    auto operator*( half_apply<Lhs, '*', Op>&& lhs, Rhs&& rhs )
    -> decltype( named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) )
    {
      return named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
    }
  }
  namespace in_helper {
    struct in_t:notstd::named_operator::make_operator<in_t> {};
    template<class T, class C>
    bool named_invoke( T&& t, in_t, C&& c ) {
      return ::notstd::find(std::forward<C>(c), std::forward<T>(t));
    }
  }
  in_helper::in_t in;
}

On a flat container, like a vector array or string, it is O(n).
On an associative sorted container, like a std::map, std::set, it is O(lg(n)).
On an unordered associated container, like std::unordered_set, it is O(1).
Test code:
std::vector<int> v{1,2,3};
if (1 *in* v)
    std::cout << "yes\n";
if (7 *in* v)
    std::cout << "no\n";
std::map<std::string, std::string, std::less<>> m{
    {"hello", "world"}
};

if ("hello" *in* m)
    std::cout << "hello world\n";

Live example.
C++14, but mainly for enable_if_t.
So what is going on here?
Well, can_apply is a bit of code that lets me write can_dot_find, which detects (at compile time) if container.find(x) is a valid expression.
This lets me dispatch the searching code to use member-find if it exists.  If it doesn't exist, a linear search using std::find is used instead.
Which is a bit of a lie.  If you define a free function find(c, t) in the namespace of your container, it will use that rather than either of the above.  But that is me being fancy (and it lets you extend 3rd party containers with *in* support).
That ADL (argument dependent lookup) extensibity (the 3rd party extension ability) is why we have three different functions named find, two in a helper namespace and one in notstd.  You are intended to call notstd::find.
Next, we want a python-like in, and what is more python like than an infix operator?  To do this in C++ you need to wrap your operator name in other operators.  I chose *, so we get an infix *in* named operator.

TL;DR
You do using notstd::in; to import the named operator in.
After that, t *in* c first checks if find(t,c) is valid.  If not, it checks if c.find(t) is valid.  If that fails, it does a linear search of c using std::begin std::end and std::find.
This gives you very good performance on a wide variety of std containers.
The only thing it doesn't support is
if (7 *in* {1,2,3})

as operators (other than =) cannot deduce initializer lists I believe.  You could get
if (7 *in* il(1,2,3))

to work.

A: The time complexity of Python's in operator varies depending on the data structure it is actually called with. When you use it with a list, complexity is linear (as one would expect from an unsorted array without an index). When you use it to look up set membership or presence of a dictionary key complexity is constant on average (as one would expect from a hash table based implementation):

*

*https://wiki.python.org/moin/TimeComplexity
In C++ you can use std::find to determine whether or not an item is contained in a std::vector. Complexity is said to be linear (as one would expect from an unsorted array without an index). If you make sure the vector is sorted, you can also use std::binary_search to achieve the same in logarithmic time.

*

*http://en.cppreference.com/w/cpp/algorithm/find

*Check if element is in the list (contains)

*Check if element found in array c++

*http://en.cppreference.com/w/cpp/algorithm/binary_search
The associative containers provided by the standard library (std::set, std::unordered_set, std::map, ...) provide the member functions find() and count() and contains() (C++20) for this. These will perform better than linear search, i.e., logarithmic or constant time depending on whether you have picked the ordered or the unordered alternative. Which one of these functions to prefer largely depends on what you want to achieve with that info afterwards, but also a bit on personal preference. (Lookup the documentation for details and examples.)

*

*How to check that an element is in a std::set?

*How to check if std::map contains a key without doing insert?

*https://en.wikipedia.org/wiki/Associative_containers

*http://en.cppreference.com/w/cpp/container
If you want to, you can use some template magic to write a wrapper function that picks the correct method for the container at hand, e.g., as presented in this answer.

A: You can use std::find from <algorithm>, but this works only for datatypes like: std::map and std::vector (etc).
Also note that this will return, iterator to the first element that is found equal to the value you pass, unlike the in operator in Python that returns a bool.

A: You can approach this in two ways:
You can use std::find from <algorithm>:
auto it = std::find(container.begin(), container.end(), value);
if (it != container.end())
    return it;

or you can iterate through every element in your containers with for ranged loops:
for(const auto& it : container)
{
    if(it == value)
        return it;
}

A: Python does different things for in depending on what kind of container it is. In C++, you'd want the same mechanism. Rule of thumb for the standard containers is that if they provide a find(), it's going to be a better algorithm than std::find() (e.g. find() for std::unordered_map is O(1), but std::find() is always O(N)).
So we can write something to do that check ourselves. The most concise would be to take advantage of C++17's if constexpr and use something like Yakk's can_apply:
template <class C, class K>
using find_t = decltype(std::declval<C const&>().find(std::declval<K const&>()));

template <class Container, class Key>
bool in(Container const& c, Key const& key) {
    if constexpr (can_apply<find_t, Container, Key>{}) {
        // the specialized case
        return c.find(key) != c.end();
    } else {
        // the general case
        using std::begin; using std::end;
        return std::find(begin(c), end(c), key) != end(c);
    }
}

In C++11, we can take advantage of expression SFINAE:
namespace details {
    // the specialized case
    template <class C, class K>
    auto in_impl(C const& c, K const& key, int )
            -> decltype(c.find(key), true) {
        return c.find(key) != c.end();
    }

    // the general case
    template <class C, class K>
    bool in_impl(C const& c, K const& key, ...) {
        using std::begin; using std::end;
        return std::find(begin(c), end(c), key) != end(c);
    }
}

template <class Container, class Key>
bool in(Container const& c, Key const& key) {
    return details::in_impl(c, key, 0);
}

Note that in both cases we have the using std::begin; using std::end; two-step in order to handle all the standard containers, raw arrays, and any use-provided/adapted containers.

A: I think one of the nice features of the "in" operator in python is that it can be used with different data types (strings v/s strings, numbers v/s lists, etc).
I am developing a library for using python constructions in C++. It includes "in" and "not_in" operators.
It is based on the same technique used to implement the in operator posted in a previous answer, in which make_operator<in_t> is implemented. However, it is extended for handling more cases:

*

*Searching a string inside a string

*Searching an element inside vector and maps

It works by defining several overloads for a function: bool in__(T1 &v1, T2 &v2), in which T1 and T2 consider different possible types of objects. Also, overloads for a function: bool not_in__(T1 &v1, T2 &v2) are defined. Then, the operators "in" and "not_in" call those functions for working.
The implementation is in this repository:
https://github.com/ploncomi/python_like_cpp


Q: Angular 2 How to make singleton service available to lazy loaded modules According to my understanding of Angular 2 rc5, to make a service from another module (not AppModule) available as a singleton to every component, even those lazy-loaded, we don't include the service in the providers array of that other module. We instead export it with RouterModule.forRoot() and import the result in AppModule
According to the docs:

The SharedModule should only provide the UserService when imported by
  the root AppModule. The SharedModule.forRoot method helps us meet this
  challenge...the SharedModule does not have providers...When we add
  the SharedModule to the imports of the AppModule, we call forRoot. In
  doing so, the AppModule gains the exported classes and the
  SharedModule delivers the singleton UserService provider at the same
  time

I'm really struggling with how to make a 3rd-party service (a service used by a module in the imports array of my AppModule) available to lazy loaded routes. I have no control over this 3rd-party module, so I cannot just remove that service from the NgModule.providers array of that module and place it inside RouterModule.forRoot() as I would with one of my services.
The specific service is MdIconRegistry, which is in providers for the MdIconModule of Angular Material 2 alpha 7-3.  This service is used to register svg icons that can then be displayed on the page with the <md-icon svgIcon='iconName'> tag. So:

*

*I imported MdIconModule in my root AppModule

*I used the service in question to register svg icons in my AppComponent
The icon is visible and works well, but only in the modules that were loaded at launch.  Lazy-loaded modules cannot see these icons, so I suspect that the Angular injector is not injecting the same instance of the MdIconRegistry service.
tl;dr: How can I make the service from a 3rd-party module a singleton available to my lazy-loaded components?
Here is a plunker that demonstrates the problem (coded in typescript).
PS: This just got the attention of the MdIconModule developer on github.

A: I do not think it has anything to do with the component being lazy-loaded.

LazyLoadedComponent is not part of the AppModule – it is part of the LazyModule. According to the docs, a component can only be part of one module. If you try adding LazyLoadedComponent to AppModule also, you would get an error to that effect. So LazyLoadedComponent is not even seeing MdIconModule at all. You can confirm this by looking at the template output in the debugger – it is unchanged.
<md-icon svgIcon="play"></md-icon>

The solution appears to be adding the MdIconModule to the LazyModule, and while this alone does not fix the problem, it does add an error to the output.

Error retrieving icon: Error: Unable to find icon with the name ":play"

And the template output now looks like this, so we know it is loading.
<md-icon role="img" svgicon="play" ng-reflect-svg-icon="play" aria-label="play"></md-icon>

I added the call to addSvgIconSet from LazyLoadedComponent, and that got it working… so this proves there is an instance of the MdIconRegistry service per component – not what you want, but may point you in the right direction.
Here’s the new plunk - http://plnkr.co/edit/YDyJYu?p=preview
After further review, I found this in the docs:

Why is a service provided in a lazy loaded module visible only to that module?
Unlike providers of the modules loaded at launch, providers of lazy loaded modules are module-scoped.

Final Update! Here is the answer. MdIconModule is not properly setup for lazy loaded components... but we can easily create our own module that IS properly set up and use that instead.
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { MdIcon } from '@angular2-material/icon';
import { MdIconRegistry } from '@angular2-material/icon';

@NgModule({
  imports: [HttpModule],
  exports: [MdIcon],
  declarations: [MdIcon]
})
export class MdIconModuleWithProviders {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MdIconModuleWithProviders,
      providers: [ MdIconRegistry ]
    };
  }
}

Plunk updated and fully working. (sorry, updated the same one) -> http://plnkr.co/edit/YDyJYu?p=preview
One might submit a pull request such that Angular Material exports modules of both styles.

A: New to Angular 6 there is a new way to register a provider as a singleton. Inside the @Injectable() decorator for a service, use the providedIn attribute. Set its value to 'root'. Then you won't need to add it to the providers list of the root module, or in this case you could also set it to your MdIconModuleWithProviders module like this:
@Injectable({
  providedIn: MdIconModuleWithProviders // or 'root' for singleton
})
export class MdIconRegistry {
...


Q: Exit position Pine Script How can I exit or close a position on a specific time of exchange in Pine Script.
Example
I have long position and want to close it on or before 1500 hrs as per Indian Time Zone.
Please help?

A: You can use the time() function for that.
Here is an example where it marks candles between 1200 and 1500. It shouldn't be difficult to adapt according to your needs.
//@version=5
indicator("My Script", overlay=true)

timeAllowed = input.session("1200-1500", "Allowed hours")

// Check to see if we are in allowed hours using session info on all 7 days of the week.
timeIsAllowed = time(timeframe.period, timeAllowed + ":1234567")

plotchar(timeIsAllowed, size=size.small)


Q: Android device how to run one program? Here is the question I have android device version 4.1.1 and ı want change the android working style. For example I restart my android device and want to see my application on screen just one. Another app for example camera or notepad ı dont want to see that just one program in my android device and I use that . How can ı programming that ?
ı will try again ı wanna root my android device for my claims how can ı do that


Q: How to automatically drop down DateTimePicker in Vb.net through a Citrix client Through a variety of reasons I am forced to use the incredibly frustrating vb.net DateTimePicker control, in the even more frustrating Citrix client, for an application. This isn't actually my main problem, the problem is, I have to make the datetimepicker automatically drop down when the user presses any button (besides tab, escape, etc).
I really need to get this to work, the users won't really take no for an answer. I would prefer to not get a new custom control, but if one exists that is easy to implement (and doesn't allow the user to type in the date) then I would be open to it.
This is what I've done so far, it works perfectly well outside of Citrix, but when it triggers in Citrix the DateTimePicker doesn't refresh when the user navigates around it. Meaning the square is over the current date, and the user can press arrow keys to their heart's content, but it never shows this to the user. (Even if the user uses the mouse to drop it down.)
Again outside of Citrix this works fine.
'Used to manually dropdown datetimepickers
Private dateTimePickerControl As DateTimePicker
Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

Public Sub DropDownCalendar()
    Const WM_LBUTTONDOWN As Int32 = &H201
    Const WM_LBUTTONUP As Int32 = &H202

    Dim x As Integer = Me.dateTimePickerControl.Width - 10
    Dim y As Integer = CInt(Me.dateTimePickerControl.Height / 2)
    Dim lParam As Integer = x + y * &H10000

    'click down, and show the calendar
    SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr))

    'Click-up, and activate the calendar (without this the calendar is shown, but is not active, and doesn't work as expected)
    SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr))
End Sub

Private Sub dteDate_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dteDate.KeyDown
    Try
        If e.KeyCode = Keys.Delete Then
            sender.customFormat = " "
            e.Handled = True
        ElseIf e.KeyCode <> Keys.Tab And e.KeyCode <> Keys.ShiftKey Then
            sender.focus()
            dateTimePickerControl = sender
            DropDownCalendar()
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

I'm completely at a loss. Is such a thing even possible in Citrix? In a previous attempt I used SendKeys("{F4}") which worked fine outside of Citrix, but in Citrix would just drop down a frozen white background.
Does anyone have any ideas that could help me out here?

A: Sometimes we've had to add DoEvents when sending messages like this in our VB app hosted on Citrix. See if this works for you:
Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

Private Sub DropDownCalendar(ctl As DateTimePicker)
    Const WM_LBUTTONDOWN = &H201
    Const WM_LBUTTONUP = &H202

    If ctl Is Nothing Then
        Exit Sub
    End If

    ctl.Select()

    Dim lParam = (ctl.Width - 10) + (CInt(ctl.Height / 2) * &H10000)

    'click down, and show the calendar
    SendMessage(ctl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr))

    Application.DoEvents()

    'Click-up, and activate the calendar (without this the calendar is shown, but is not active, and doesn't work as expected)
    SendMessage(ctl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr))
End Sub

Private Sub dteDate_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dteDate.KeyDown
    Try
        If e.KeyCode = Keys.Delete Then
            CType(sender, DateTimePicker).CustomFormat = " "
            e.Handled = True
        ElseIf e.KeyCode <> Keys.Tab And e.KeyCode <> Keys.ShiftKey Then
            DropDownCalendar(CType(sender, DateTimePicker))
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub


Q: Xamarin Forms OnAppLinkRequestReceived event - Shell.Current is null I am testing App Links / Deep Linking / Universal Links on my Xamarin Forms app. I have an app that correctly intercepts URLs as expected, but when I go to navigate to the page using Shell in my app, Shell.Current is null.
Visual Studio 2022, Android Pixel 4 emulator, Xamarin Forms version 5.0.0.2291
Setup: Simple onAppLinkRequestReceived handler. The debugger executes and breaks at this code, so I know my applinks are set up properly.
protected override async void OnAppLinkRequestReceived(Uri uri)
{
    base.OnAppLinkRequestReceived(uri);

    var shellRoute = uri.PathAndQuery;
    try
    {
        Log.Information("User followed applink for {shellRoute}", shellRoute);
        Shell.Current.GoToAsync(shellRoute);
    }
    catch(Exception ex)
    {
        Log.Error(ex, "User encountered an error attempting to navigate to an applink request", shellRoute);
    }
}

The problem here is that Shell.Current is null so I nullref. I expect shell.current should always be valid?
I am testing this using Android's suggested test technique, found here:
.\adb shell am start -W -a android.intent.action.VIEW -d "my-url" my-package-id
a null shell current value appears unexpected especially when other examples on the web indicate that navigation straight from the applinkrequest event should be valid?


Q: How to set up the event Datagridviewcombobox cell selectionchanged? I have a DataGridViewComboBoxCell control with some items into it. I would like to get the values when user chooses a value from the dropdown. I cant use DataGridViewComboBoxColumn where EditingControlShowing can be used. I need similar event handler for DataGridViewComboBoxCell. Can anyone help pls.
Please find code sample below:
private DataGridViewComboBoxCell NameDropDown = new DataGridViewComboBoxCell();

public void SetDropDown(int index)
      {
         NameDropDown = new DataGridViewComboBoxCell();
         DropDownValues(index);
         for (int j = 0; j < DropDownOld.Items.Count; j++)
         {
            NameDropDown.Items.Add(DropDownOld.Items[j]);
         }
         dataGridView1.Rows[index].Cells[4] = NameDropDown;
      }

A: Yes, you can use the EditingControlShowing event to get a handle to the combobox.
Then hook up an event handler for the SelectedIndexChanged or whatever event you want and code it..!
DataGridViewComboBoxEditingControl cbec = null;

private void dataGridView1_EditingControlShowing(object sender,
                           DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        cbec = e.Control as DataGridViewComboBoxEditingControl;
        cbec.SelectedIndexChanged -=Cbec_SelectedIndexChanged;
        cbec.SelectedIndexChanged +=Cbec_SelectedIndexChanged;
    }
}

private void Cbec_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cbec != null) Console.WriteLine(cbec.SelectedItem.ToString());
}