text:
Q: Did the Terminator in Judgement day burn himself in this scene? In this scene did the Terminator receive burns and his hands and legs/feet?
This has always bothered me when watching Judgment day, considering that the terminator is living flesh over a metal endoskeleton, when he is sent back in time and arrives it leaves a huge hole in the ground and around him.

In the scene you see the red hot metal on the truck and the red hot glow on the ground. He stays there for a while so I can't understand how he does not receive burns. The red glow is from heat as you can see the metal cool down:
At 1:30 he arrives:

I can't seem to find anything that shows he was burnt here, was there ever anything mentioned in or out universe?

A: I think the answer lies not in looking at the Terminator, but at the humans.  Several times in the series, humans have transported, appearing on bare ground (unfortunately, Kyle Reese is NOT an example as he appears in mid-air and falls):
In Terminator: The Sarah Connor Chronicles we see humans travel to the future at least twice, in the first episode and the last.  In the last, you can see, they land on the ground.  Now, the ground is not red-hot, but they are there signs of fire around the immediate area.

In Terminator: Genisys we see Sarah and Kyle travel into the future, landing on a freeway (much like in the pilot of SCC, but with more action):

Again, no visible glowing dent in the ground that I could spot... but it looks like roughly the same material as where the T-800 landed (asphalt) and the humans don't seem adversely affected (then again, Sarah gets hit by a car and is walking a few minutes later, so, movie magic!)
So, in neither of these cases do the humans seem to have any trouble as you might expect from someone who had their bare feet in contact with something extremely hot.
I think the logical conclusion is that, looks aside, the area immediately around a time travel arrival is NOT hot enough to burn or severely hurt human flesh.   Perhaps the "red hot" appearance is some artifact of time travel, excess low-wavelength photons bleeding through, or just one of those things that filmmakers throw in because it looks cool but does not accurately represent the "physics" of time travel at all.
It should be noted that in Terminator: Genisys, they do almost a shot-by-shot remake of the two arrivals from the original movie.  You can see a comparison here:

It's uncanny how close they get, but there is one pertinent difference I noticed... in the original, the T-800 does NOT arrive in a glowing depression in the ground, despite arriving in exactly the same location, while the remake follows the convention of the Terminator sequels.  However, the discrepancy does pose a problem if you want to take the "what appears on screen is canon, and on-screen it's red-hot!" approach, because it wasn't what happened in the original movie and now you need an explanation as for why.

A: "Terminator Rules" Time Travel, using Skynet-branded Time Displacement Equipment (TDE), from all relevant sources, tells us that:

*

*Only Living Flesh, "...something about the field generated by a living organism...." can be transported via the "Temporal Bubble"

*The TDE requires obscene, huge amounts of power to function.

Whatever mechanism of physics allows this "Temporal Bubble" to be selective to living tissue reacts to non-living tissue in a violent manner, displacing or disintegrating the matter that would exist within the boundaries of the "Temporal Bubble" at its destination, leaving the matter directly outside of the bubble in an excited state - a state that displays the glowing properties noticed in the time travel scenes. The nature of this state is not determinable, as its effects are only observable.
Due to this effect, we see sections of matter, like the cut-open truck and the concave impression in the ground during the events of Terminator 1, glowing - as if gouged out by a sphere shaped implement.
This glowing effect could be a phosphorescent or light based effect and not a heat effect - it may be only perceived as a heat effect due to the reddish coloration of the visual effects used.
The "Temporal Bubble" is associated with lightning-like effects while being observed, and these elements may be the cause of any fires seen during "Temporal Bubble" scenes, as opposed to a result of the glowing effect.
If the glowing effect is, in fact, indicative of a high temperature, the living tissue of an T-series Infiltration Unit would only be in contact with this for a short duration, and as seen by fire-walking humans, this can be withstood by human flesh for a short duration of time. This assumes that Skynet engineered Terminator flesh has the same exact properties as regular human flesh, and I submit that Skynet engineered it to be better than regular human flesh, therefore higher durability is likely.
A T-series Infiltration unit is designed to mimic human appearance enough to get close to a target while being resistant to damage - something so insignificant as a third degree burn on the feet is not going to be a consideration for the machine, especially since the injury can be covered up by any footwear of appropriate size the infiltration unit can acquire. As demonstrated in several scenes, a T-series infiltration unit is very good at acquiring inventory for a mission.
Skynet is a machine intelligence that is constantly trying to improve its equipment and technology, and I propose that the differences in the effects of the "Temporal Bubble" leave upon its destination are the result of this improvement cycle - leaving less evidence of a "Temporal Bubble" is advantageous as it retains the element of surprise, not giving those sneaky humans any evidence that an infiltration unit, flesh covered weapons pod, mimetic polyalloy, or nanomachine colony has been sent to the target area.
In canon, power generation was always an issue for Skynet, who still competed with humans for resources - a TDE device which wasted less power during temporal insertion, as observed by less of an effect to the target area, would be advantageous in several ways. More temporal insertions could be accomplished with less power, allowing that energy to be put into interdimensional transportation or timeline-altering research processing.


text:
Q: The request was aborted: Could not create SSL/TLS secure channel for HttpWebRequest. (Working from Localhost ASPNET 4.5) but failing from AWS server the code below is working on localhost but failing from the server.
environment:
.NET Framework 4.5
hosted on IIS 8.5 Windows Server core 2012 (AWS)
//using System.Net;
//using RestSharp;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.Expect100Continue = true;

restClient = new RestClient("https://restapi.myapi.com/api/");
var request = new RestRequest("emailconfirmation/{id}", Method.GET);

request.AddParameter(new Parameter
    {
       Name = "id",
       Value = key,
       Type = ParameterType.UrlSegment
    });

return restClient.Execute(request);

A: Solved by setting up a new environment with a more recent IIS and windows server.
New environment: IIS 10.0 Windows Server 2019.
Old environment: IIS 8.5 Windows Server core 2012.
I think the old environment was failing due to a security configuration on the server side which was making the API failing to request.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET - Generating a Web Page based on Dynamic Content Let me explain the scenario that I want to recreate.  I have coded a server application that acts as a middleman between online merchants and their customers.
Basically, the idea is that customers go to buy products on the merchant's website, then the merchant sends the purchase description to the server along with a digital signature.  The server then validates the details and sends a URL to the online merchant.  The online merchant should then redirect the customer to this URL.
Now, my question is, I want the page to where the user is redirected to contain some data in order to help me identify the particular transaction in question.  More specifically, I want to keep track of the vendor_username (the username with which the online merchant registered on the server) and the transaction_id.  Now this would be simply achieved using Sessions if it was my website from where the customers are redirected instead of a third party.
I thought of passing the vendor_username and transaction_id in the URL to the online merchant as a query string, however I know that the query string can be easily edited from the address bar and as such is not an option.  How can I implement it please?  Sorry for the long description but I wanted to explain my situation in detail so that you could understand what I want.  Thank you :)

A: Possibly using a WCF service and tieing the transactions to something like GUIDs? I'm suggesting an N-Teir architecture model, more can be found here: http://www.codeproject.com/Articles/430014/N-Tier-Architecture-and-Tips
This is how we accomplished a similar task in a previous project of mine. This might be an interesting read.
Hope my answer helps get you on the right track for your solution!


text:
Q: Cannot build the Caliburn.Micro.HelloScreen sample due to missing references I've downloaded the source package of Caliburn.Micro from this page, version 1.5.2. I have VS2010 Professional, and I have downloaded and installed the Blend SDK.
I've extracted the entire thing, and was able to build the actual Caliburn.Micro.DLL after removing the projects that aren't supported on my system (meaning I can build Caliburn.Micro.DLL only).
However, I cannot figure out how to properly build the HelloScreens sample. It appears that the sample is configured to use NuGet, but whatever I do I can't seem to get the proper references to work.
I've tried right-clicking the solution end enabling NuGet package restore, hoping that the thing would be smart enough to resolve what it had to resolve, but nope.
The following references have yellow exclamation points on them (and don't exist on disk):

*

*Caliburn.Micro

*Microsoft.Expression.Effects

*Microsoft.Expression.Interactions

*System.Windows.Interactivity

A: Can you remove the Caliburn Nuget package through Visual Studio and reinstall it? Your packages.config might be mixed up. Nuget should then set the references right.

A: The .csproj file for the sample points to ..\..\..\bin\Silverlight\Debug\Caliburn.Micro.dll, which doesn't exist on my file system since I didn't build the Silverlight version. Building that solved the problem.


text:
Q: Concatenating values from one array to another in PHP I have one main array which is the returned data from a MySQL query for user table which looks like this :
array(36) {
  [0]=>
  array(4) {
    ["id"]=>
    string(1) "101"
    ["email"]=>
    string(15) "kkkk@gggg.com"
    ["firstname"]=>
    string(8) "aaaaa"
    ["lastname"]=>
    string(12) "bbbbb"

  }
  [1]=>
  array(4) {
    ["id"]=>
    string(1) "102"
    ["email"]=>
    string(17) "mmmmm@hhhhh.com"
    ["firstname"]=>
    string(12) "vvvv"
    ["lastname"]=>
    string(12) "zzzzz"

  }
  [2]=>
  array(4) {
    ["id"]=>
    string(2) "103"
    ["email"]=>
    string(17) "eeee@gmail.com"
    ["firstname"]=>
    string(6) "ggggg"
    ["lastname"]=>
    string(12) "zzzzz"

And so on...
And a second array which is again MySQL query which is from a table with two foreign keys making relation b/w two table many to many and looks like this:
array(7) {
  [0]=>
  array(2) {
    ["user_id"]=>
    string(3) "101"
    ["group_id"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["user_id"]=>
    string(3) "102"
    ["group_id"]=>
    string(1) "1"
  }
  [2]=>
  array(2) {
    ["user_id"]=>
    string(3) "103"
    ["group_id"]=>
    string(1) "1"
  }

The final goal is to make a 5th key in the first array, something like:

["groups"]=>...

which i can populate with the id's of the groups which every user takes part in and at the end to look like something like this:

["groups"]=>"1,2,3,4"

In other words, because the relation is many to many the user may participate in more than one group when I push the new value I don't want to create a new key with value but instead to concatinate the existing values of the key with the new id.
So far I got something like this:
$query = $this->mUsers->getAll(); //Main query to get users data
          $results = $this->mUsers->getGroupsAndUsers(); //Query for getting the group_id and user_id
        //  Looping both arrays to find matching ID's

          foreach($query as $key=>$value){ //$value['id'] returns the value of the users id from table users
              foreach($results as $row){
                  if ($value['id']==$row['user_id'])
               {
                          array_push($value,"groups",$row['group_id']);

                }

              }

}
But I doesn't work. I tried a few other things but nothing by now.
Thanks
Leron

A: You may be better off doing the heavy lifting in SQL, rather than in PHP.
So, if your users table is like this:

... your groups table is like this:

... and your users_groups table is like this:

... then you could use the following query:
SELECT id,email,firstname,lastname, GROUP_CONCAT(users_groups.group_id) as groups
FROM `users`
JOIN users_groups on users.id = users_groups.user_id
GROUP BY users.id;

(or this one, if you're testing in phpMyAdmin)
SELECT id,email,firstname,lastname, GROUP_CONCAT(CAST(users_groups.group_id AS CHAR)) as groups
FROM `users`
JOIN users_groups on users.id = users_groups.user_id
GROUP BY users.id;

... to produce this output:

Credit to this post for the info on how to produce comma-separated values from SQL, and the comment about using CAST AS CHAR.

A: As now, you're passing a cloned value and not a reference into the foreach. If you run a  foreach($array as $value), $value is a copy. You have to run it as foreach($array as &$value) to actually edit $value. & means you are passing the argument as a reference instead of just cloning it.
Let me demonstrate with a simple example.
$names = array("bob", "joe", "mustafa", "ghandi");
foreach($names as $name) {
    $name = "name: " . $name;
}
print_r($names);
/** prints:
Array
(
    [0] => bob
    [1] => joe
    [2] => mustafa
    [3] => ghandi
)
*/

$names = array("bob", "joe", "mustafa", "ghandi");
foreach($names as &$name) {
    $name = "name: " . $name;
}
print_r($names);
/** prints:
Array
(
    [0] => name: bob
    [1] => name: joe
    [2] => name: mustafa
    [3] => name: ghandi
)
*/

A: It's making your life more difficult, and making the data less useful, to try and construct a comma separated string. It makes much more sense to create a sub-array of values, which you can implode(',', $arr) if you need a string representation down the line. It also makes the job a lot easier, and the data more useable, if your array of user data has the same keys as the user_id field:
// First, get the array of users and format it with sensible keys
$users = array();
foreach ($this->mUsers->getAll() as $user) $users[$user['id']] = array_merge($user, array('groups' => array()));

// Now assign group relationships
foreach ($this->mUsers->getGroupsAndUsers() as $group) {
  $users[$group['user_id']]['groups'][] = $group['group_id'];
}

print_r($users);

A: You're close!
Try:
foreach($query as $key=>$value ) {
    foreach($results as $row) {
        if( $value['id'] == $row['user_id'] ) {
            $query[$key]['groups'][] = $row['group_id'];
        }
    }
}

The empty bracket [] appends to the array


text:
Q: Opening Excel Document using EPPlus I am trying to open an Excel document using EPPlus reference/package. I can't get the Excel application to open. What code am I missing?
protected void BtnTest_Click(object sender, EventArgs e)
{
     FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls");

     ExcelPackage pck = new ExcelPackage(newFile);
     //Add the Content sheet
     var ws = pck.Workbook.Worksheets.Add("Content");
     ws.View.ShowGridLines = false;

     ws.Column(4).OutlineLevel = 1;
     ws.Column(4).Collapsed = true;
     ws.Column(5).OutlineLevel = 1;
     ws.Column(5).Collapsed = true;
     ws.OutLineSummaryRight = true;

     //Headers
     ws.Cells["B1"].Value = "Name";
     ws.Cells["C1"].Value = "Size";
     ws.Cells["D1"].Value = "Created";
     ws.Cells["E1"].Value = "Last modified";
     ws.Cells["B1:E1"].Style.Font.Bold = true;
}

I have tried pck.open(newFile);, but it doesn't allow it ...

A: Try this:
protected void BtnTest_Click(object sender, EventArgs e)
{
    FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls");

    ExcelPackage pck = new ExcelPackage(newFile);
    //Add the Content sheet
    var ws = pck.Workbook.Worksheets.Add("Content");
    ws.View.ShowGridLines = false;

    ws.Column(4).OutlineLevel = 1;
    ws.Column(4).Collapsed = true;
    ws.Column(5).OutlineLevel = 1;
    ws.Column(5).Collapsed = true;
    ws.OutLineSummaryRight = true;

    //Headers
    ws.Cells["B1"].Value = "Name";
    ws.Cells["C1"].Value = "Size";
    ws.Cells["D1"].Value = "Created";
    ws.Cells["E1"].Value = "Last modified";
    ws.Cells["B1:E1"].Style.Font.Bold = true;

    pck.Save();
    System.Diagnostics.Process.Start("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls");
}

Hope this helps!

A: Try this in ASP NET Core to avoid win32 exception:
private void CreateWorkbook(string fileName)
{
    using (var p = new ExcelPackage())
    {
        p.Workbook.Properties.Author = "Barry Guvenkaya";
        p.Workbook.Properties.Title = "MyTitle";
        p.Workbook.Worksheets.Add("MySheet");
        var bin = p.GetAsByteArray();
        File.WriteAllBytes(fileName, bin);

        // Below code opens the excel doc
        var proc = new Process();
        proc.StartInfo = new ProcessStartInfo(fileName)
        {
            UseShellExecute = true
        };
        proc.Start();
    }
}


text:
Q: How to bind an enum to a combobox control in WPF? I am trying to find a simple example where the enums are shown as is. All examples I have seen tries to add nice looking display strings but I don't want that complexity.
Basically I have a class that holds all the properties that I bind, by first setting the DataContext to this class, and then specifying the binding like this in the xaml file:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>

But this doesn't show the enum values in the ComboBox as items.

A: You'll need to create an array of the values in the enum, which can be created by calling System.Enum.GetValues(), passing it the Type of the enum that you want the items of.
If you specify this for the ItemsSource property, then it should be populated with all of the enum's values. You probably want to bind SelectedItem to EffectStyle (assuming it is a  property of the same enum, and contains the current value).

A: I used another solution using MarkupExtension.

*

*I made class which provides items source:
public class EnumToItemsSource : MarkupExtension
{
    private readonly Type _type;

    public EnumToItemsSource(Type type)
    {
        _type = type;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Enum.GetValues(_type)
            .Cast<object>()
            .Select(e => new { Value = (int)e, DisplayName = e.ToString() });
    }
}

*That's almost all... Now use it in XAML:
    <ComboBox DisplayMemberPath="DisplayName"
          ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}"
          SelectedValue="{Binding Path=WhereEverYouWant}"
          SelectedValuePath="Value" />

*Change 'enums:States' to your enum

A: There are many excellent answers to this question and I humbly submit mine.  I find that mine is somewhat simpler and more elegant. It requires only a value converter.
Given an enum...
public enum ImageFormat
{
    [Description("Windows Bitmap")]
    BMP,
    [Description("Graphics Interchange Format")]
    GIF,
    [Description("Joint Photographic Experts Group Format")]
    JPG,
    [Description("Portable Network Graphics Format")]
    PNG,
    [Description("Tagged Image Format")]
    TIFF,
    [Description("Windows Media Photo Format")]
    WDP
}

and a value converter...
public class ImageFormatValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is ImageFormat format)
        {
            return GetString(format);
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string s)
        {
            return Enum.Parse(typeof(ImageFormat), s.Substring(0, s.IndexOf(':')));
        }
        return null;
    }

    public string[] Strings => GetStrings();

    public static string GetString(ImageFormat format)
    {
        return format.ToString() + ": " + GetDescription(format);
    }

    public static string GetDescription(ImageFormat format)
    {
        return format.GetType().GetMember(format.ToString())[0].GetCustomAttribute<DescriptionAttribute>().Description;

    }
    public static string[] GetStrings()
    {
        List<string> list = new List<string>();
        foreach (ImageFormat format in Enum.GetValues(typeof(ImageFormat)))
        {
            list.Add(GetString(format));
        }

        return list.ToArray();
    }
}

resources...
    <local:ImageFormatValueConverter x:Key="ImageFormatValueConverter"/>

XAML declaration...
    <ComboBox Grid.Row="9" ItemsSource="{Binding Source={StaticResource ImageFormatValueConverter}, Path=Strings}"
              SelectedItem="{Binding Format, Converter={StaticResource ImageFormatValueConverter}}"/>

View model...
    private ImageFormat _imageFormat = ImageFormat.JPG;
    public ImageFormat Format
    {
        get => _imageFormat;
        set
        {
            if (_imageFormat != value)
            {
                _imageFormat = value;
                OnPropertyChanged();
            }
        }
    }

Resulting combobox...

A: It works very nice and simple.
xaml
<ComboBox ItemsSource="{Binding MyEnumArray}">

.cs
public Array MyEnumArray
{
  get { return Enum.GetValues(typeof(MyEnum)); }
}

A: All the above posts have missed a simple trick. It is possible from the binding of SelectedValue to find out how to populate the ItemsSource AUTOMAGICALLY so that your XAML markup is just.
<Controls:EnumComboBox SelectedValue="{Binding Fool}"/>

For example in my ViewModel I have
public enum FoolEnum
    {
        AAA, BBB, CCC, DDD

    };

    FoolEnum _Fool;
    public FoolEnum Fool
    {
        get { return _Fool; }
        set { ValidateRaiseAndSetIfChanged(ref _Fool, value); }
    }

ValidateRaiseAndSetIfChanged is my INPC hook. Yours may differ.
The implementation of EnumComboBox is as follows but first I'll need a little helper to get my enumeration strings and values
    public static List<Tuple<object, string, int>> EnumToList(Type t)
    {
        return Enum
            .GetValues(t)
            .Cast<object>()
            .Select(x=>Tuple.Create(x, x.ToString(), (int)x))
            .ToList();
    }

and the main class ( Note I'm using ReactiveUI for hooking property changes via WhenAny )
using ReactiveUI;
using ReactiveUI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Documents;

namespace My.Controls
{
    public class EnumComboBox : System.Windows.Controls.ComboBox
    {
        static EnumComboBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(EnumComboBox), new FrameworkPropertyMetadata(typeof(EnumComboBox)));
        }

        protected override void OnInitialized( EventArgs e )
        {
            base.OnInitialized(e);

            this.WhenAnyValue(p => p.SelectedValue)
                .Where(p => p != null)
                .Select(o => o.GetType())
                .Where(t => t.IsEnum)
                .DistinctUntilChanged()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(FillItems);
        }

        private void FillItems(Type enumType)
        {
            List<KeyValuePair<object, string>> values = new List<KeyValuePair<object,string>>();

            foreach (var idx in EnumUtils.EnumToList(enumType))
            {
                values.Add(new KeyValuePair<object, string>(idx.Item1, idx.Item2));
            }

            this.ItemsSource = values.Select(o=>o.Key.ToString()).ToList();

            UpdateLayout();
            this.ItemsSource = values;
            this.DisplayMemberPath = "Value";
            this.SelectedValuePath = "Key";

        }
    }
}

You also need to set the style correctly in Generic.XAML or your box won't render anything and you will pull your hair out.
<Style TargetType="{x:Type local:EnumComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

and that is that. This could obviously be extended to support i18n but would make the post longer.

A: You can do it from code by placing the following code in Window Loaded event handler, for example:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();

If you need to bind it in XAML you need to use ObjectDataProvider to create object available as binding source:
<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
    <Window.Resources>
        <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="StyleAlias:EffectStyle"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
                  SelectedItem="{Binding Path=CurrentEffectStyle}" />
    </Grid>
</Window>

Draw attention on the next code:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"

Guide how to map namespace and assembly you can read on MSDN.

A: Use ObjectDataProvider:
<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

and then bind to static resource:
ItemsSource="{Binding Source={StaticResource enumValues}}"

based on this article

A: Universal apps seem to work a bit differently; it doesn't have all the power of full-featured XAML.  What worked for me is:

*

*I created a list of the enum values as the enums (not converted to
strings or to integers) and bound the ComboBox ItemsSource to that

*Then I could bind the ComboBox ItemSelected to my public property
    whose type is the enum in question

Just for fun I whipped up a little templated class to help with this and published it to the MSDN Samples pages.  The extra bits let me optionally override the names of the enums and to let me hide some of the enums.  My code looks an awful like like Nick's (above), which I wish I had seen earlier.

A: If you are binding to an actual enum property on your ViewModel, not a int representation of an enum, things get tricky.  I found it is necessary to bind to the string representation, NOT the int value as is expected in all of the above examples.
You can tell if this is the case by binding a simple textbox to the property you want to bind to on your ViewModel.  If it shows text, bind to the string.  If it shows a number, bind to the value. Note I have used Display twice which would normally be an error, but it's the only way it works.
<ComboBox SelectedValue="{Binding ElementMap.EdiDataType, Mode=TwoWay}"
                      DisplayMemberPath="Display"
                      SelectedValuePath="Display"
                      ItemsSource="{Binding Source={core:EnumToItemsSource {x:Type edi:EdiDataType}}}" />

Greg

A: public class EnumItemsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!value.GetType().IsEnum)
            return false;

        var enumName = value.GetType();
        var obj = Enum.Parse(enumName, value.ToString());

        return System.Convert.ToInt32(obj);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Enum.ToObject(targetType, System.Convert.ToInt32(value));
    }
}

You should extend Rogers and Greg's answer with such kind of Enum value converter, if you're binding straight to enum object model properties.

A: I like for all objects that I'm binding to be defined in my ViewModel, so I try to avoid using <ObjectDataProvider> in the xaml when possible.
My solution uses no data defined in the View and no code-behind. Only a DataBinding, a reusable ValueConverter, a method to get a collection of descriptions for any Enum type, and a single property in the ViewModel to bind to.
When I want to bind an Enum to a ComboBox the text I want to display never matches the values of the Enum, so I use the [Description()] attribute (from System.ComponentModel) to give it the text that I actually want to see in the ComboBox. If I had an enum of days of the week, it would look something like this:
public enum DayOfWeek
{
  // add an optional blank value for default/no selection
  [Description("")]
  NOT_SET = 0,
  [Description("Sunday")]
  SUNDAY,
  [Description("Monday")]
  MONDAY,
  ...
}

First I created helper class with a couple methods to deal with enums. One method gets a description for a specific value, the other method gets all values and their descriptions for a type.
public static class EnumHelper
{
  public static string Description(this Enum value)
  {
    var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attributes.Any())
      return (attributes.First() as DescriptionAttribute).Description;

    // If no description is found, the least we can do is replace underscores with spaces
    // You can add your own custom default formatting logic here
    TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
    return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " ")));
  }

  public static IEnumerable<ValueDescription> GetAllValuesAndDescriptions(Type t)
  {
    if (!t.IsEnum)
      throw new ArgumentException($"{nameof(t)} must be an enum type");

    return Enum.GetValues(t).Cast<Enum>().Select((e) => new ValueDescription() { Value = e, Description = e.Description() }).ToList();
  }
}

Next, we create a ValueConverter. Inheriting from MarkupExtension makes it easier to use in XAML so we don't have to declare it as a resource.
[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return EnumHelper.GetAllValuesAndDescriptions(value.GetType());
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    return this;
  }
}

My ViewModel only needs 1 property that my View can bind to for both the SelectedValue and ItemsSource of the combobox:
private DayOfWeek dayOfWeek;

public DayOfWeek SelectedDay
{
  get { return dayOfWeek; }
  set
  {
    if (dayOfWeek != value)
    {
      dayOfWeek = value;
      OnPropertyChanged(nameof(SelectedDay));
    }
  }
}

And finally to bind the ComboBox view (using the ValueConverter in the ItemsSource binding)...
<ComboBox ItemsSource="{Binding Path=SelectedDay, Converter={x:EnumToCollectionConverter}, Mode=OneTime}"
          SelectedValuePath="Value"
          DisplayMemberPath="Description"
          SelectedValue="{Binding Path=SelectedDay, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

To implement this solution you only need to copy my EnumHelper class and EnumToCollectionConverter class. They will work with any enums. Also, I didn't include it here, but the ValueDescription class is just a simple class with 2 public object properties, one called Value, one called Description. You can create that yourself or you can change the code to use a Tuple<object, object> or KeyValuePair<object, object>

For those who wanted to see the ValueDescription class:
public class ValueDescription
{
    public object Value {get; set};
    public object Description {get; set};
}

A: Nick's answer has really helped me, but I realised it could be tweaked slightly, to avoid an extra class, ValueDescription.
I remembered that there exists a KeyValuePair class already in the framework, so this can be used instead.
The code changes only slightly :
public static IEnumerable<KeyValuePair<string, string>> GetAllValuesAndDescriptions<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("TEnum must be an Enumeration type");
        }

        return from e in Enum.GetValues(typeof(TEnum)).Cast<Enum>()
               select new KeyValuePair<string, string>(e.ToString(),  e.Description());
    }

public IEnumerable<KeyValuePair<string, string>> PlayerClassList
{
   get
   {
       return EnumHelper.GetAllValuesAndDescriptions<PlayerClass>();
   }
}

and finally the XAML :
<ComboBox ItemSource="{Binding Path=PlayerClassList}"
          DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=SelectedClass}" />

I hope this is helpful to others.

A: I liked tom.maruska's answer, but I needed to support any enum type which my template might encounter at runtime.  For that, I had to use a binding to specify the type to the markup extension.  I was able to work in this answer from nicolay.anykienko to come up with a very flexible markup extension which would work in any case I can think of.  It is consumed like this:
<ComboBox SelectedValue="{Binding MyEnumProperty}"
          SelectedValuePath="Value"
          ItemsSource="{local:EnumToObjectArray SourceEnum={Binding MyEnumProperty}}"
          DisplayMemberPath="DisplayName" />

The source for the mashed up markup extension referenced above:
class EnumToObjectArray : MarkupExtension
{
    public BindingBase SourceEnum { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
        DependencyObject targetObject;
        DependencyProperty targetProperty;

        if (target != null && target.TargetObject is DependencyObject && target.TargetProperty is DependencyProperty)
        {
            targetObject = (DependencyObject)target.TargetObject;
            targetProperty = (DependencyProperty)target.TargetProperty;
        }
        else
        {
            return this;
        }

        BindingOperations.SetBinding(targetObject, EnumToObjectArray.SourceEnumBindingSinkProperty, SourceEnum);

        var type = targetObject.GetValue(SourceEnumBindingSinkProperty).GetType();

        if (type.BaseType != typeof(System.Enum)) return this;

        return Enum.GetValues(type)
            .Cast<Enum>()
            .Select(e => new { Value=e, Name = e.ToString(), DisplayName = Description(e) });
    }

    private static DependencyProperty SourceEnumBindingSinkProperty = DependencyProperty.RegisterAttached("SourceEnumBindingSink", typeof(Enum)
                       , typeof(EnumToObjectArray), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));

    /// <summary>
    /// Extension method which returns the string specified in the Description attribute, if any.  Oherwise, name is returned.
    /// </summary>
    /// <param name="value">The enum value.</param>
    /// <returns></returns>
    public static string Description(Enum value)
    {
        var attrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs.Any())
            return (attrs.First() as DescriptionAttribute).Description;

        //Fallback
        return value.ToString().Replace("_", " ");
    }
}

A: Simple and clear explanation:
http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
xmlns:local="clr-namespace:BindingEnums"
xmlns:sys="clr-namespace:System;assembly=mscorlib"

...
<Window.Resources>
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:Status"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

...
<Grid>
    <ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150"
              ItemsSource="{Binding Source={StaticResource dataFromEnum}}"/>
</Grid>

A: I'm adding my comment (in VB, sadly, but the concept can be easily replicated over to C# in a heartbeat), because I just had to reference this and didn't like any of the answers as they were too complex. It shouldn't have to be this difficult.
So I came up with an easier way. Bind the Enumerators to a Dictionary. Bind that dictionary to the Combobox.
My combobox:
<ComboBox x:Name="cmbRole" VerticalAlignment="Stretch" IsEditable="False" Padding="2"
    Margin="0" FontSize="11" HorizontalAlignment="Stretch" TabIndex="104"
    SelectedValuePath="Key" DisplayMemberPath="Value" />

My code-behind. Hopefully, this helps someone else out.
Dim tDict As New Dictionary(Of Integer, String)
Dim types = [Enum].GetValues(GetType(Helper.Enumerators.AllowedType))
For Each x As Helper.Enumerators.AllowedType In types
    Dim z = x.ToString()
    Dim y = CInt(x)
    tDict.Add(y, z)
Next

cmbRole.ClearValue(ItemsControl.ItemsSourceProperty)
cmbRole.ItemsSource = tDict

A: Using ReactiveUI, I've created the following alternate solution. It's not an elegant all-in-one solution, but I think at the very least it's readable.
In my case, binding a list of enum to a control is a rare case, so I don't need to scale the solution across the code base. However, the code can be made more generic by changing EffectStyleLookup.Item into an Object. I tested it with my code, no other modifications are necessary. Which means the one helper class could be applied to any enum list. Though that would reduce its readability - ReactiveList<EnumLookupHelper> doesn't have a great ring to it.
Using the following helper class:
public class EffectStyleLookup
{
    public EffectStyle Item { get; set; }
    public string Display { get; set; }
}

In the ViewModel, convert the list of enums and expose it as a property:
public ViewModel : ReactiveObject
{
  private ReactiveList<EffectStyleLookup> _effectStyles;
  public ReactiveList<EffectStyleLookup> EffectStyles
  {
    get { return _effectStyles; }
    set { this.RaiseAndSetIfChanged(ref _effectStyles, value); }
  }

  // See below for more on this
  private EffectStyle _selectedEffectStyle;
  public EffectStyle SelectedEffectStyle
  {
    get { return _selectedEffectStyle; }
    set { this.RaiseAndSetIfChanged(ref _selectedEffectStyle, value); }
  }

  public ViewModel()
  {
    // Convert a list of enums into a ReactiveList
    var list = (IList<EffectStyle>)Enum.GetValues(typeof(EffectStyle))
      .Select( x => new EffectStyleLookup() {
        Item = x,
        Display = x.ToString()
      });

    EffectStyles = new ReactiveList<EffectStyle>( list );
  }
}

In the ComboBox, utilise the SelectedValuePath property, to bind to the original enum value:
<ComboBox Name="EffectStyle" DisplayMemberPath="Display" SelectedValuePath="Item" />

In the View, this allows us to bind the original enum to the SelectedEffectStyle in the ViewModel, but display the ToString() value in the ComboBox:
this.WhenActivated( d =>
{
  d( this.OneWayBind(ViewModel, vm => vm.EffectStyles, v => v.EffectStyle.ItemsSource) );
  d( this.Bind(ViewModel, vm => vm.SelectedEffectStyle, v => v.EffectStyle.SelectedValue) );
});

A: Nick's solution can be simplified more, with nothing fancy, you would only need a single converter:
[ValueConversion(typeof(Enum), typeof(IEnumerable<Enum>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var r = Enum.GetValues(value.GetType());
        return r;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

You then use this wherever you want your combo box to appear:
<ComboBox ItemsSource="{Binding PagePosition, Converter={converter:EnumToCollectionConverter}, Mode=OneTime}"  SelectedItem="{Binding PagePosition}" />

A: I wouldn't recommend implementing this as it is but hopefully this can inspire a good solution.
Let's say your enum is Foo. Then you can do something like this.
public class FooViewModel : ViewModel
{
    private int _fooValue;

    public int FooValue
    {
        get => _fooValue;
        set
        {
            _fooValue = value;
            OnPropertyChange();
            OnPropertyChange(nameof(Foo));
            OnPropertyChange(nameof(FooName));
        }
    }
    public Foo Foo
    {
        get => (Foo)FooValue;
        set
        {
            _fooValue = (int)value;
            OnPropertyChange();
            OnPropertyChange(nameof(FooValue));
            OnPropertyChange(nameof(FooName));
        }
    }
    public string FooName { get => Enum.GetName(typeof(Foo), Foo); }

    public FooViewModel(Foo foo)
    {
        Foo = foo;
    }
}

Then on Window.Load method you can load all enums to an ObservableCollection<FooViewModel> which you can set as the DataContext of the combobox.

A: I just kept it simple. I created a list of items with the enum values in my ViewModel:
public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>()
{
    InputsOutputsBoth.Both,
    InputsOutputsBoth.Inputs,
    InputsOutputsBoth.Outputs
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:
<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

A: <Window.Resources>
        <ObjectDataProvider x:Key="DiaryTypeEnum"
       MethodName="GetValues" ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="z:Enums+DiaryType"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
</Window.Resources>
...
<ComboBox ItemsSource="{Binding Source={StaticResource DiaryTypeEnum}}" SelectedItem="{x:Static z:Enums+DiaryType.Defect}" />

Where z its xmlns:z="clr-namespace:ProjName.Helpers"
My Enum into static class
  public static class Enums
    {
        public enum DiaryType
        {
            State,
            Defect,
            Service,
            Other
        }
        public enum OtherEnumOrMethods
        {
           //TODO
        }
    }

A: here is my short answer.
public enum Direction { Left, Right, Up, Down };
public class Program
{
    public Direction ScrollingDirection { get; set; }
    public List<string> Directions { get; } = new List<string>();

    public Program()
    {
        loadListDirection();
    }

    private void loadListDirection()
    {
        Directions.AddRange(Enum.GetNames(typeof(Direction)));
    }
}

And Xaml:
<ComboBox SelectedIndex="0" ItemsSource="{Binding Path=Directions, Mode=OneWay}" SelectedItem="{Binding Path=ScrollingDirection, Mode=TwoWay}"/>

Good Luck!


text:
Q: Explanation on Tasks I'd like some clarification on code I didn't do and have to modify in a service.
Here's some parts of the code of the service
private Thread _thread;
private ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
private Task _runningTask = null;

protected override void OnStart(string[] args)
{
    _thread = new Thread(WorkerThreadFunc);
    _thread.IsBackground = true;
    _thread.Start();
}

private void WorkerThreadFunc()
{
    InitDb();

    while (!_shutdownEvent.WaitOne(1000))
    {
        if (_runningTask == null || _runningTask.IsCompleted)
        {
            Task task;
            if (_tasks.TryDequeue(out task))
            {
                _runningTask = task;
                _runningTask.Start();
            }
        }
    }
}

private void RunReport(int reportID)
{
    var task = new Task(id =>
    {
        //Task code
    }, reportID);

    _tasks.Enqueue(task);
}

And so, this all works well
The thing is, I want to add other tasks to the task queue, but I don't have any ID to give them (the task in the code runs a report and uses the reportID, but the other tasks aren't linked to one report in particular).
Is there a way to create a Task without giving it an ID (which I doubt), or is there something i'm completely missing ?

A:
Is there a way to create a Task without giving it an ID (which I doubt), or is there something i'm completely missing ?

Yes, just use:
_tasks.Enqueue(new Task(() => {
       // Your code here
   });

That being said, this is not an idiomatic usage of the Task class.  In general, the Task and Task<T> classes are meant to always be running - not created and started later.

A: I know it's not your code to begin with but, like Reed said, you shouldn't queue Tasks. You should queue work items instead.
Take a look at TPL DataFlow. There's even an introductory document.


text:
Q: Promise.all is run concurrently or in parallel As far as I know, NodeJS doesn't run promises in parallel, it runs them concurrently as it is a single threaded event loop architecture. Ability to run things in parallel by creating a new child process to take advantage of multi-core CPUs. but when i run this test it shows the result of running in parallel. please help me explain
const a = new Promise(resolve => setTimeout(() => resolve("a"), 2000))
const b = new Promise(resolve => setTimeout(() => resolve("b"), 2000))
const c = new Promise(resolve => setTimeout(() => resolve("c"), 2000))
const begin = Date.now();
async function test() {

  const promises = [a, b, c];
  const [output1, output2, output3] = await Promise.all(promises);
  return `parallel is done: ${output1} ${output2} ${output3}`;

}
test().then((arr)=>{
    console.log(arr);
    console.log( "time :", Date.now()- begin);
})
// parallel is done: a b c
//time : 2010

A: It doesn't run in parallel, but I believe your question is exactly the point of this video: https://www.youtube.com/watch?v=mvWSD-5G4Yw

A: just because its single thread it doesnt means it can do only one thing.
yes, you can spawn, but most things are done like:
"hey, ur done?"
"nope"
goes ask whatever needs to be done next while waiting

its basically a big while true that goes around checking stuff until things are done.


text:
Q: Overlapping table with line ssrs 208 I have to make a report with a fixed table size. It's pretty easy, just have to put a table and a line above it, but ssrs is moving the line and I think it's a problem of overlapping.
I set the textboxes inside the tablix to not grow.
Thats how I designed the report:

And that's what's rendering:

Any ideas of how I can achieve that?

A: At the end I put all the controls into a rectangle and rendered fine.


text:
Q: How to convert integer value of ip address to standard IP address Pls. can you help me how to convert integer value of ip address to standard ip address?
A got integer value from
tmpWifiServiceNative:= TAndroidHelper.Activity.getSystemService(TJContext.JavaClass.WIFI_SERVICE);

tmpWifiManager:= TJWifiManager.Wrap((tmpWifiServiceNative as ILocalObject).GetObjectID);

tmpWifiIPAddress:= tmpWifiManager.getDhcpInfo.ipAddress //This returns integer value

A: Simply use this function:
uses
  Androidapi.Helpers,
  Androidapi.JNIBridge,
  Androidapi.JNI.Java.Net,
  Androidapi.JNI.JavaTypes;

function ConvertIntegerIPAddressToString(AIntegerIPAddress: Integer): string;
var
  IPAddress: Integer;
  SystemByte: TJavaArray<Byte>;
  InetAddress: JInetAddress;
begin
  if (TJByteOrder.JavaClass.nativeOrder.equals(TJByteOrder.JavaClass._GetLITTLE_ENDIAN)) then
    IPAddress:= TJInteger.JavaClass.reverseBytes(AIntegerIPAddress)
  else
    IPAddress:= AIntegerIPAddress;

  SystemByte:= TJBigInteger.JavaClass.valueOf(IPAddress).toByteArray;

  try
    InetAddress:= TJInetAddress.JavaClass.getByAddress(SystemByte);

    Result:= JStringToString(InetAddress.getHostAddress);
  except
    Result:= 'Convert error';
  end;
end;


text:
Q: Facebook Graph API doesn't display birthday I am developing an Android app where I need access to all the birthdays of my facebooks friends. But somehow I only get the birthdays of very few people.
Could it be that the new Facebook Timeline causes this bug? Because if I go to Graph API Explorer I don't see them either although almost every friend of mine has set his birthday visible.
I also noticed that I was able to see the birthdays of my friends who still have the old facebook without the timeline.
Does anyone have an idea what could cause this problem?
Thanks in advance!

A: For birthday following are the two permissions
friends_birthday,user_birthday

The behavior is same for old wall and Timeline users. Double check you are taking the above permissions using following tool.
Accesstoken Debugger
and if permissions are there check friends birthday using following tool
Graph Api tool
PS: User can apply privacy on its year but not on its complete birthday. For some people birthday will not show up using graph api because they have opted out of Facebook applications using Facebook setting..


text:
Q: ScrollMagic element is being triggered on page load automatically I have a graphic element positioned at the bottom center of my page that is supposed to fade-in when you start scrolling down.
I am using ScrollMagic JS
The problem is that element is being displayed automatically whenever I reload the page and then fades out. And after I start scrolling down, it fades back in again and starts working normally.
I need to hide on initial page load.
How may I achieve that? Because adding display: none to the element simply hides it all together.
I would also like to use a different kind of animation, instead of ease-out in CSS, I would like to use something that makes the graphic element to look like as it is rising up and rising down.
Similar to this site here: http://lempens-design.com/
DEMO https://jsfiddle.net/jtLo27op/3/
HTML

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur distinctio facilis fugit quasi quisquam quos recusandae rerum sunt temporibus voluptates? A, ipsa labore laudantium non recusandae suscipit vel voluptas. Aut!

CSS
html, body {
    width: 100%;
    height: 100%;
}
body {
    background-color: #191617;
}
.height100 {
    height: 100%;
}
.logo {
    width: 220px;
    margin-top: 10em;
}
.skyline {
    display: block;
    max-width: 100%;
    position: absolute;
    bottom:0;
    left:50%;
    transform:translateX(-50%);
}
.city-vector {
    opacity: 1;
    transition: all 3s ease-out;
}
.city-vector.fade-in {
    opacity: 0;
}

.intro {
    height: 100%;
    position: relative;
    overflow: hidden;
}

.intro::before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url('../img/bg/bg5.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    height: 100%;
    -webkit-filter: blur(3px);
    -moz-filter: blur(3px);
    -o-filter: blur(3px);
    -ms-filter: blur(3px);
    filter: blur(3px);
    transform: scale(1.01);
}

Javascript
$(document).ready(function() {
    var controller = new ScrollMagic.Controller();

    var ourScene = new ScrollMagic.Scene({
        triggerElement: '#animate',
        duration: 361
    })
    .setClassToggle('#animate', 'fade-in')
    .addTo(controller);
});

A: You have to change your CSS code:
.city-vector {
    opacity: 0;
    transition: all 3s ease-out;
}
.city-vector.fade-in {
    opacity: 1;
}

Updated JSfiddle
UPDATE: Okay, for the function you want, you don't need any external libraries. I don't have any experience with ScrollMagic, so I just didn't use it. I've also added the animation that makes it "rise out of the page" through CSS.
JSfiddle
jQuery
$(document).ready(function() {
  $(window).scroll(function() { //run function every time window is scrolled
    var scroll = $(window).scrollTop(); //find how much is scrolled from top

    if (scroll > 0) { // if the scroll from top is greater than zero...
      $("#animate").addClass("fade-in"); //then add class
    } else { // if the scroll from top is not greater than zero...
      $("#animate").removeClass("fade-in"); //then remove class
    }
  });
});

CSS animation:
.skyline {
  display: block;
  max-width: 100%;
  position: absolute;
  bottom: 0;
  opacity: 0;  /* I removed this in update */
  transition: all 3s ease-out; /* Changed animation duration to 0.5s */
  left: 50%;
  transform: translate(-50%, 100%);
}

.city-vector.fade-in .skyline {
  transform: translate(-50%);
  opacity: 1; /* and this */
}

UPDATE: New JSfiddle with "snappish" effect.


text:
Q: How to use the factory boy class attribute value in another factory class in factory boy this is my companytaxratefactory
class CompanyTaxRateFactory(basefactory.BaseFactory):
    class Meta:
        model = companytaxrate.CompanyTaxRate

    tax_rate = 18
    igst_rate = 18
    cgst_rate = 9
    sgst_rate = 9
    eff_from = '2021-11-25'

and i want to to calculate taxable_amount in orderitemfactory and in which how i can use tax_rate value at the place of 18
class OrderItemFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = orderitem.OrderItem
        exclude = ('productrate',)

    qty = 1
    product = factory.LazyAttribute(lambda o: o.productrate.product)
    billingfrequency = factory.LazyAttribute(lambda o: o.productrate.billingfrequency)
    rate = factory.LazyAttribute(lambda o: o.productrate.rate)
    amount = factory.LazyAttribute(lambda o: o.qty*o.rate)
    # taxable_amount = amount * (100/100+())
    productrate = None


text:
Q: Is this a system resource? (or how do I know if I need to delete a pointer) - working with C in C++ Looking at this cplusplus.com time example, got me thinking more about pointers. The code has no delete (and no new).
Warning: I generally try to avoid pointers as much as possible, so I am definitely not proficient.
I've cut a lot of the code from the example below so as to focus on my question:
/* time example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t timer;
  time(&timer);  /* get current time; same as: timer = time(NULL)  */

  return 0;
}

Should I delete timer at the end of this, or is this just pointing to a system resource? My understanding is that whenever I use new, I should use delete. Is it right to think that as I am not using new, I don't need delete.
This stack question seems to be what I am looking for and explains I don't need delete (which matches the example code on the website) as I am not doing a new; however, I am not sure the functions I am using are not calling a new somewhere (as I find it very hard to read the source). How do I know? Do I need to know?
I really hate working with this old time code and can't wait for the upcoming C++20 chrono update, but this is too far away for my project.

A: Short answer:
No!

Long answer:
You don't have a pointer in your code that is pointing to memory allocated with new, so you are not required to delete anything. And, your reasoning is correct that whenever you allocate something in your code, you are responsible to de-allocate that as well. It is best to use RAII (Resource Acquisition Is Initialization) to manage resources that need to be de-allocated.
For your question regarding the internal allocations by an API, as a programmer you yourself are responsible to go through the API's documentation to figure that out. Some APIs require you to de-allocate the allocated memory in a particular way, which is (ideally) very well documented, and you should follow that.
In C, memory allocated with malloc() must be de-allocated with free().
In C++, memory allocated with new or new[] must be de-allocated with delete or delete[], respectively.
BTW, you ought to use C++11's smart pointers (std::unique_ptr and std::shared_ptr along with std::make_unique and std::make_shared respectively) to enforce RAII in your code whenever possible.

A: You just can delete timer if define it as a pointer like this with new keyword :
time_t *timer = new time_t(50);
// do something with *timer
delete timer;

In bellow case :
{
    time_t timer;
    time(&timer);
}

You just pass timer address with & (reference sign) and time_t timer and it stored in stack. At the end of block it will be delete automatically.


text:
Q: Trying to pull from github i get error remote: Repository not found My server was working fine until yesterday
it was pulling fine.
today I run the command
>> git pull origin <branch>

I get a response: remote: Repository not found.
I run command
>> ssh -T git@github.com

I get response: Hi! You've successfully authenticated, but GitHub does not provide shell access.
>> I added ssh to my use and it has read and write ability

I even added config file like in here
https://help.github.com/en/github/authenticating-to-github/using-ssh-over-the-https-port
still not working, and it'd be a mess if I create a new repo.
any ideas? is there something wrong with GitHub? why this might happen.

A: If your URL (git remote -v) is indeed git@github.com:/

*

*you should not need to use SSH over the HTTPS port

*a git ls-remote git@github.com:<you>/<yourRepo> should work.

If not, check the case of the URL (it is case sensitive).
And try an HTTPS URL just for testing:
git ls-remote https://github.com/<you>/<yourRepo>

That will ask for your credentials (GitHub username/password)


text:
Q: html  showing different size of some images I have some images and I am using this class for every  tag to set same height and width-

.imgsize{
              height:80px;
              width:80px
          }

The issue is some of the images are not rendering according to the size. here is the layout of those images

*

*
as you can see the right side image is showing according to the size in CSS class but the 1st and 2nd is a bit smaller. However, when I refresh the page I see first 2 images as the same size as third one( but just for a few seconds till the page is loading).
When I gave custom size to the 2 images the difference was 15 px in height and width.

height="95" width="95" style="margin-top:-6px"

but then it showed like its the same size as 3rd one. I don't understand the reason why is it behaving this way.

Is something wrong with images or with code.?
Any advice will be appreciated.
Edit:
This is the screenshot while the page was loading - this is how the image looks the exact same size as one another for just... maybe 2 seconds only -

A: Hi thanks for your help guys. The issue is resolved now and Its same as I started to think , it was not rendering the same size because those images were very small in size than other images on my page. those images were from 93-99 px in size and so they might not be showing according to the css Class(80px). I made those people to change the image size and make it bigger originally. Now its looking same..
But still I am in doubt as 80px was small from its original size then also it didnt show correct.

A: sorry to writing this on answer, because i don't have enough reputation to write a comment.
anyway,
from your question in the html tag you get height="95" width="95" style="margin-top:-6px" inside.
so, try type it in your css
.imgsize{ height:80px !important; width:80px !important; }

it ignores any post styles unless you reload or change class mapping the css.


text:
Q: Android Action bar custom dropdown view on item click I'm writing an Android app for tablets. I've gone with the action bar to create my icons. However, I need to open a custom view when one of the menu items is clicked.
I don't want a custom action bar - I need to inflate a custom view when the "Browse Subjects" action bar item is clicked. This view will need to appear like a dropdown but be using my own custom layout as it will not be used for navigation.

Here is my menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_browse"
        android:title="Browse Subjects"
        android:showAsAction="always"
        android:actionLayout="@layout/action_layout_browse"
        android:actionProviderClass="au.com.pearson.f12catalogue.action_providers.BrowseProvider"
            />
    <item android:id="@+id/menu_settings"
        android:title="Settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>

I assumed the ActionProviderClass would allow me to instantiate a custom view when the action bar item is clicked but I can't work out a way - perhaps I'm going down the wrong path.
Any help on this would be MUCH appreciated! Thanks!
UPDATE:
Thanks for links to action bar styling but I don't want to simply style a dropdown. I want to inflate a custom view. The view will perform DB queries etc aswell.

A: Ok I worked out a solution myself. Basically the actionProviderClass is used to instantiate an actionView in the actionBar. In this class you can attach an onClick listener to the view you inflate. I used this listener to inflate a dropdown view in the main frame when clicked.
For instance
public class BaseProvider extends ActionProvider {

    protected final Context context;
    protected final int layout;
    protected final BaseProvider self;
    protected View view;
    protected int positionLeft = 0;
    protected Dropdown dropdown;

    public BaseProvider(Context context, int layout, Dropdown dropdown) {
        super(context);
        this.layout = layout;
        this.context = context;
        this.self = this;
        this.dropdown = dropdown;
    }

    @Override
    public View onCreateActionView() {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

        View view = inflater.inflate(this.layout, null);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                self.onItemClick();
            }
        });
        this.view = view;
        return view;
    }

    public boolean onItemClick(){
        toggleDropdown();
        return true;
    }

    protected void toggleDropdown(){
        this.positionLeft = getRelativeLeft(view);
        DropdownInflater.getInstance().toggleDropdown(this.dropdown,this.positionLeft);
    }

    protected int getRelativeLeft(View view) {
        int[] loc = new int[2];
        view.getLocationOnScreen(loc);
        return loc[0];
    }
}


text:
Q: Jquery Exporting HTML5 table to Excel in IE without ActiveX object? I am trying to export HTML table's contents to an Excel in IE using jquery. I realize that they are many threads that discuss this. But all of them specify either this code:
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;

or this:
  window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('#dataTable').html()));

The first one works in IE, but I would prefer not to use ActiveX object as it goes against the default security settings of my IE. The second one doesn't work in IE. I want to do this client side using jQuery or JS.

A: Let's assume your html table has an id="exportTable"
you can export the table to an xls file using:
window.open('data:application/vnd.ms-excel,' + $('#exportTable').html());

you're trying to either open an application or write to the file system from within your browser. That means that if the default security settings won't allow that, there's really no way around that except either change the security settings (I assume that's not an option) or try this in e.g. Chrome (maybe not an option either) because this is working fine for me.
Writing to the File System from the browser isn't something that's allowed by default and, as you can imagine, with good reason.
One alternative might be to investigate the possibility to create a new Google Docs Spreadsheet using your table data.
I found an interesting article describing how you could approach this, but I haven't any experience with this.


text:
Q: Bootstrap responsive height I'm making a website and I'm making a register form, but I need to adjust div height's according to wiewport, something like this:
xs devices: 12
sm devices: 9
md devices: 7
Note: I'm using bootstrap 4

A: Something like this :
@media only screen and (max-width: 500px) {
   div{
       height: 12px;
   }
}

You can use this website to find the viewport sizes for multiple devices and you replace the max-width by the size you want.
The media query will check for your screen size and applies the directives inside the block if the condition is true.
More about media queries here  and here


text:
Q: Ionic Framework and AngularJS - How to read mobile contacts into application Below is the code I have tried. When I execute the code below it appears as when I click a button in my application and it is opening device phone book and displaying contacts. When I click on any contact it is picked by application but it should not open device address book but when clicked it should display the contacts of my device in my application. Can anyone suggest me how to do this?
HTML:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, r-scalable=no, width=device-width">
  <title></title>
  <link href="lib/ionic/css/ionic.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

  <ion-pane>
    <ion-header-bar class="bar-stable">
      <button class="button" ng-click="pickContact()">Contacts</button>

All Contacts

    </ion-header-bar>
    <ion-content>

                     0">

{{contact.displayName}}

 0">{{contact.emails[0].type}} : {{contact.emails[0].value}}

 0">{{contact.phones[0].type}} : {{contact.phones[0].value}}

    </ion-content>
  </ion-pane>

Javascript:
angular.module('starter', ['ionic'])
  .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {

      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })

.service("ContactsService", ['$q',
  function($q) {

    var formatContact = function(contact) {

      return {
        "displayName": contact.name.formatted || contact.name.givenName + " " + contact.name.familyName || "Unknown Person",
        "emails": contact.emails || [],
        "phones": contact.phoneNumbers || [],
        "photos": contact.photos || []
      };

    };

    var pickContact = function() {

      var deferred = $q.defer();

      if (navigator && navigator.contacts) {

        navigator.contacts.pickContact(function(contact) {

          deferred.resolve(formatContact(contact));
        });

      } else {
        deferred.reject("Hurray!!!!......  No contacts in desktop browser");
      }

      return deferred.promise;
    };

    return {
      pickContact: pickContact
    };
  }
])

.controller("AppCtrl", ['$scope', 'ContactsService',
  function($scope, ContactsService) {

    $scope.data = {
      selectedContacts: []
    };

    $scope.pickContact = function() {
      ContactsService.pickContact().then(
        function(contact) {
          $scope.data.selectedContacts.push(contact);
          console.log("Selected contacts=");
          console.log($scope.data.selectedContacts);

        },
        function(failure) {
          console.log("Hurray!!!!......  Failed to pick a contact");
        }
      );

    }
  }
])

A: You could try using $cordovaContacts which is a part of the ngCordova (ngCordova needs to be installed). You can install in your app with the command cordova plugin add cordova-plugin-contacts. Then there is a simple function to getting all contacts in your contacts list.
$scope.getAllContacts = function() {
  $cordovaContacts.find({filter: '',multiple:true}).then(function(allContacts) {
    $scope.contacts = allContacts;
  });
};

Note: It seems to be so that the find() function in $cordovaContacts can not be empty. Include ie. a filter in there for it to work.
EDIT:
This is a demonstration of the general structure and functions which you need to make the ngCordova contacts plugin to work.
Here's all my code you'll need in a JSFiddle: https://jsfiddle.net/thepio/osjppoqu/
And then I just call the getAllContacts function using a button click in my app.html file like this:
<button type="button" ng-click="getAllContacts()" class="button button-block button-positive">Get contacts</button>

REMEMBER it only works on a real device, probably not even emulator (haven't tested though). Include the ngCordova in your module. If you're calling the contacts plugin without a click or something remember that it is required that it's only called AFTER the device is ready. In Ionic you can do this with the following:
$ionicPlatform.ready(function() {
  // Call the plugin here
});


text:
Q: Deserializing arbitrary JSON with Jackson I have a JSON clob which I am deserializing into a bean, which is then sent as JSON as the response of an HTTP request.
I would like to add a JSONObject field to the bean which contains arbitrary JSON.
Here is my bean:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DTO implements Serializable {
    private String height;
    private String width;
    //I would like to add this field
    //private JSONObject settings;

And here is how I deserialize the CLOB:
DTO layout = null;
String json = "{\"height\": \"300px\", \"width\": \"100%\"}";
final ObjectMapper mapper = jackson.getContext(DTO.class);

try {
    layout = mapper.readValue(json, DTO.class);
}
catch(IOException ex) {
    logger.error("Unable to deserialize Dashboard layout CLOB", ex);
}

This works.  However, I need my clob to contain a settings object which contains arbitrary JSON.  Is this possible?  For example:
 {"height": "300px", "width": "100%", "settings": {"propA": 1, "propB": "red"}}

When I try this with JSONObject, I get the error:
org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.codehaus.jettison.json.JSONObject and no properties discovered to create BeanSerializer (to avoid  exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain:  api.jaxb.DTO["settings"])

A: JSONObject comes from the JSON library which is a separate package than Jackson. In your case you should use JsonNode from the Jackson library.:
public class DTO implements Serializable {
    ...
    private org.codehaus.jackson.JsonNode settings;


text:
Q: what is a first-chance-exception? I'm getting a First-chance exception at 0x75FA2EEC in x.exe: Microsoft C++ exception: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::ptree_bad_path> > at memory location 0x006AE774.
In my code, I thought I have handled them already:
const ptree& v;
std::string value;
try { value = v.get<std::string>("<xmlattr>.Value"); }
catch(ptree_bad_path&) { value = v.get_value<std::string>(); }

(According to the docs.)
So why do I get the error?
It seems to just ignore the error then and continues with execution.

A:
So why do I get the error?

It is not an error, it is just a debugger notification.  There are several, you for example also see notifications when a thread exits or a DLL gets loaded or the program terminates.  These are the kind of events in a program that usually have a lot of impact on the program, a C++ exception is an exceptional event so the debugger lets you know about that.
The "first chance" exception doesn't have to turn into an unhandled exception that aborts your program.  And it didn't, you wrote try/catch in your code and caught the exception.  Still good to know about this, maybe your catch handling is broken and your program misbehaves.  It very commonly is since exceptions should be exceptional so don't get tested very often.  You do that with Debug + Exceptions, tick the Thrown checkbox for C++ exceptions.  The debugger now automatically breaks the program on the first chance exception notification, giving you a shot at finding out exactly why the exception was thrown.  Very useful.
You don't have to look at these notifications, right-click the Output window and untick the "Exception messages" option.
Feature, not a bug.


text:
Q: Wikidata Query Service: how do I search by freebase I am using the Wikidata Query Service (https://query.wikidata.org) to get details about freebase ids.
I now have a list of freebase ids
/m/0gqpg /m/0h0vk /m/0h3vhfb /m/0h4xw_ /m/0h52w /m/0hfp /m/0hhbr
How should I modify the following code to achieve a bulk query?
\`SELECT  ?s ?sLabel ?p  ?o ?oLabel WHERE {
?s wdt:P646 "/m/0181lj"

SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
}

I would like to get the label corresponding to the freebase id

A: There are multiple options (FILTER with IN; FILTER with ||; UNION), but usually the best is VALUES:
SELECT ?s ?sLabel ?freebaseID
WHERE {

  VALUES ?freebaseID {
    "/m/0181lj"
    "/m/0gqpg"
    "/m/0h0vk"
    "/m/0h3vhfb"
    "/m/0h4xw_"
    "/m/0h52w"
    "/m/0hfp"
    "/m/0hhbr"
  }

  ?s wdt:P646 ?freebaseID .

  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }

}


text:
Q: Parsing xml with python, many similar attributes Good day, dear developers, I need to parse XML file like this:
(using  xml.etree.ElementTree python module)
<level1>
   <level2 id="1">
      <level3>
        <level4 id="1">name1</foobar>
        <level4 id="2">name2</foobar>
     </level3>
   </level2>
</level1>

I've got dozens of level4 items, how can i get specific ones? If i need to get just name2 or id=2 attribute what should i do?
I use this code to take the level4 item at the moment.
import xml.etree.ElementTree

root = source.findall('.//level4')
counter = 0

for elem in root:
    counter +=1
    if counter = 2:
        id = elem.get('Id')

But what if i need many level1-3 items and some of them don't have name1 item?
The loop won't work properly then. Thank you in advance


text:
Q: tensor flow defined precise mini batch I have a database, in which I cut with numpy my variable X and my variable to guess, or 'predict': Y
my question is about the definition of training data batches. Indeed,
I have a column in my database called "classes" which informs that this or that student is part of this or that class.
If I want to cause the tensorflow to make predictions class by class, I have to define as "training mini batch" the different values presented in this column?
(ex: class_1, class_2, class_3) But these classes are obviously never the same size: / so how to tell him to take just the line for one value of the column "classes" and cut by class so that he can finally receive a whole class of student and he can to make predictions on the scale of a class such as for example (which pupil progresses the fastest in chemistry, which is promised to a literary future etc etc).
I hope, are clearly formulated in my approximate English, and thanks to you if you have to take the time to decipher some things.
If clarification can help you to answer me effectively I am available do not hesitate.
There is the code, i put you my accuracy too, which is don't move :(  :
        #coding:utf-8
    # Import les librairies necessaires:
    import statsmodels as stat
    import seaborn as sbrn
    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    import sqlite3
    from sqlalchemy import create_engine
    from tensorflow import keras
    import tensorflow as tf

    # Connexion a la base de donnée:
    conn=sqlite3.connect("t15.db")

    engine = create_engine('sqlite:///t15.db')

    def init_variables():

        weights = np.random.normal(size=18)
        bias = 0
        return weights, bias

    def pre_activation(features,weights,bias):

        return np.dot(features, weights) + bias

    def activation(z):

        return 1 / (1 + np.exp(-z))

    def derivative_activation(z):

        return activation(z) * (1 - activation(z))

    def predict(features, weights, bias):

        z = pre_activation(features, weights, bias)
        y = activation(z)
        return np.round(y)

    def cost(predictions, targets):

        return np.mean((predictions - targets)**2)

    def train(features, targets, weights, bias):

        epochs = 100
        learning_rate = 0.1

        # Imprimer la precision:
        predictions = predict(features, weights, bias)
        print("Accuracy = ", np.mean(predictions == targets))

        for epoch in range(epochs):
            if epoch % 10 == 0:
                predictions = activation(pre_activation(features, weights, bias))
                print("Cost = {0}".format(cost(predictions, targets)))

            # Initialiser les gradients:
            weights_gradients = np.zeros(weights.shape)
            bias_gradients = 0

            # Traverser chaque itération, chaque ligne de la DB:
            for feature, target in zip(features, targets):

                # Calculer la predicton:
                z = pre_activation(feature, weights, bias)
                y = activation(z)
                # Mettre à jour le gradients:
                weights_gradients += (y - target) * derivative_activation(z) * feature
                bias_gradients += (y - target) * derivative_activation(z)
            # Mettre à jour les variables:
            weights = weights - learning_rate * weights_gradients
            bias = bias - learning_rate * bias_gradients
            # Imprimer la precision:
            predictions = predict(features, weights, bias)
            print("Accuracy = ", np.mean(predictions == targets))

    # Creation de notre DataSet:
df = pd.read_sql_table("performances",engine, index_col='id', columns=['nom_cours','name_student','date_cours','prof','frere_soeur','option','parent','age','heure_cours','nb_de_cours','moyenne','meilleur_note','temps_controle','nb_controle','sexe','place'])
    df.loc[:, 'date_cours'] = pd.to_datetime(df.date_cours)

    X = df.iloc[:,-16:-1].values
    Y = df.iloc[:,-1].values

    # Codage de la variable indépendante:
    from sklearn.preprocessing import LabelEncoder, OneHotEncoder
    labEncr_X = LabelEncoder()

    # Passer les variable en Dummy
    X[:,0] = labEncr_X.fit_transform(X[:,0])
    X[:,1] = labEncr_X.fit_transform(X[:,1])
    X[:,2] = labEncr_X.fit_transform(X[:,2])
    X[:,3] = labEncr_X.fit_transform(X[:,3])
    X[:,4] = labEncr_X.fit_transform(X[:,4])
    X[:,12] = labEncr_X.fit_transform(X[:,12])
    X[:,13] = labEncr_X.fit_transform(X[:,13])

    # Passer les variable en Dummy de trap
    onehotEncr = OneHotEncoder(categorical_features=[0])
    onehotEncr = OneHotEncoder(categorical_features=[1])
    onehotEncr = OneHotEncoder(categorical_features=[2])
    onehotEncr = OneHotEncoder(categorical_features=[3])
    onehotEncr = OneHotEncoder(categorical_features=[4])
    onehotEncr = OneHotEncoder(categorical_features=[12])
    onehotEncr = OneHotEncoder(categorical_features=[13])

    X = onehotEncr.fit_transform(X).toarray()

    # Variable dépendante:
    labEncr_Y = LabelEncoder()
    Y = labEncr_Y.fit_transform(Y)

    features = X
    targets = Y.reshape(-1, 1)

    # Construction des echantillons de test et de training:
    from sklearn.model_selection import train_test_split
    X_train,X_test,Y_train,Y_test = train_test_split(X,Y, test_size= 0.2, random_state = 0)

    if __name__ == '__main__':
        # dataset

        weights, bias = init_variables()

        print(features[0])
        print(features[1])
        train(features,targets,weights,bias)

Accuracy :
[0.0000e+00 0.0000e+00 1.0000e+00 0.0000e+00 5.1000e+01 3.1000e+01
 0.0000e+00 1.8900e+02 2.2100e+02 2.1000e+03 7.4100e+01 7.0000e+00
 1.3470e+01 1.0000e+00 4.8000e+04 1.7024e+05 1.0000e+00 1.8000e+01]
[0.0000e+00 0.0000e+00 0.0000e+00 1.0000e+00 5.1000e+01 6.0000e+01
 0.0000e+00 1.6700e+02 6.8000e+01 2.1000e+03 7.3600e+01 7.0000e+00
 1.3470e+01 2.0000e+00 4.8000e+04 1.7436e+05 1.0000e+00 1.8000e+01]
Accuracy =  0.20898258478460127
Cost = 0.7910174152153987
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Cost = 0.7910174152153987
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Accuracy =  0.20898258478460127
Cost = 0.7910174152153987

Thank you a lot for your interest people ! :)


text:
Q: How to disable the triggers in SQL Server 2012 across session Am running a SQL job in which am disabling the trigger on all the tables in a particular DB. But few triggers are getting enabled again thru' different script which runs from the application/web service. How can I ensure that triggers are not get enabled until the SQL job completes?

A: It sounds like you want one session to be immune from the trigger activity, rather than to disable the triggers (which will disable them for all sessions) whilst that session is running. If that's the case, and if re-writes are possible, I'd suggest using context info.
What you do is, within the session that should be immune, you set a particular context value, e.g.:
SET CONTEXT_INFO 0x53494C4C59

Then, within your triggers, before doing anything else, check and exit:
IF CONTEXT_INFO() = 0x53494C4C59
BEGIN
    RETURN
END

Note that this is not suitable as a security measure - it relies on nobody, potentially maliciously, setting up their context info with the "magic, disable triggers" value in any other sessions where it's not appropriate.


text:
Q: Neo4J Cypher conditional where statement depending on parameter I'm trying to write a query that takes four parameters which are all lists of ids and which should filter the results.
I have nodes called KnowledgeEntry which have multiple KnowledgeRecords attached to them
(:KnowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)

KnowledgeRecords each have four types of relations to nodes of type Location, Community, Function or OrganizationalUnit which all have an id attribute.
I want to retrieve all KnowledgeEntries if they have one or more KnowledgeRecords that have a relation to Location, Community, Function or OU where id matches one of the items in the given list (parameter)
This is what I came up with so far:
MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $filters.locationIds
}

RETURN relationship, knowledgeEntry;

This only works if all parameters used are set. If for example $filters.locationIds has no entries or is null the where statement should be ignored. I tried this with CASE statement and apoc.when but had no success.
When adding an OR EXISTS for e.g OrganizationalUnit I get an error "There should be at least one pattern expression"
MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT]->(loc:Location)
    WHERE loc.id IN $locationIds
}

OR EXISTS {
    MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:RELEVANT_FOR_EMPLOYEES_WITH]->(ou:OrganizationalUnit)
    WHERE ou.id IN $organizationalUnitIds
}

RETURN relationship, knowledgeEntry;

A: It seems you are encountering a possible neo4j bug when there are multiple existential subqueries in a boolean expression.
This query combines your two subqueries, and may work better for you:
MATCH (knowledgeEntry:KnowledgeEntry)-[relationship]-(:KnowledgeEntry)
WHERE EXISTS {
  MATCH (knowledgeEntry)-[:CONTAINS]->(:KnowledgeRecord)-[:BASED_AT|RELEVANT_FOR_EMPLOYEES_WITH]->(x)
  WHERE
    (x:OrganizationalUnit AND x.id IN $organizationalUnitIds) OR
    (x:Location AND x.id IN $locationIds)
}
RETURN relationship, knowledgeEntry;


text:
Q: Different use of this operator in android I want to know different use of this operator in android. I have seen some example, but I get confused like:
Intent intent=new intent(Main Activity.this, Second Activity.class)

here what "this" refer to?
Handler handler= new handler();

Thread t1;

t1=new thread(new runnable)){
    void run(){
        handler.postdelayed(this,2000);
    }
}

here, what "this" refer to?
I know that "this" refer to the current instance of the class, but here whose instance is passing thread class or any other and any more example anybody know regarding this keyword.

A: The intent function you using has take Context and Class as its parameters,
Intent(Context packageContext, Class<?> cls)

hence the this here is the Context. So in general, it you want to use the current class you working on as the Context as the parameter for some function, use this.
Read more about the Intent constructor here
In the second block of code, this refers to the Runnable class you want the function to run on.
I suggest you google about function or constructor to traceback what are the parameters.


text:
Q: How can I avoid repeating messages in vr_ad? In my environment I see too many messages coming from the vr_ad.  typical "disturbing" example:
Three consecutive messages, all informing of one access – reading from address 0x5
[14] C_BUS: (info - Fetch) Fetch EX_CBUS_MAP vr_ad_map-@1, address: 0x00000005
[14] C_BUS: (info - Fetch) Fetch XCORE vr_ad_reg_file-@2, address: 0x00000005
[14] C_BUS: (info - Fetch) Fetch EX_PROXY_REG vr_ad_reg-@7 in XCORE vr_ad_reg_file-@2, addr 0x00000005, data 0x00000008
Why are there so many messages?
And how can I remove these messages?

A: Seems that you work with verbosity MEDIUM or even higher. To reduce amount of messages, you can change verbosity to LOW (and then you will see only the last message - the one from the vr_ad_reg, and not from its containers), or even to NONE - and then you will get only critical messages.
To change verbosity - you can use either the set message command, or message_manager api. (the messages configuration is per instance - so you can have different vr_ad messages verbosity for each sub-environment)
For example -
specman>set message sys.env.sub_env1 -tag=VR_AD_MSG HIGH

or
extend my_env {
    post_generate() is also {
        message_manager.set_screen_messages(me,
                                            VR_AD_MSG,
                                            FULL);
    };
};

Another thing you might want to do is filtering message based on "direction" - different setting for update, fetch, and compare_and_update.
For example - to avoid getting messages that come after write (vr_ad update() ), but see messages coming from compare_and_update() -
vr_ad remove update messages
vr_ad add compare messages


text:
Q: Setting Up multiple domain in LDAP server I am trying to setup an LDAP server from scratch on a CENTOS 7 server. I was able to install it properly, but when it came to configuring it I am a bit stuck on the initial part.
The thing is the company I am setting this up for has 3 domains like:

*

*example.com

*example.in

*example-new.com

I am following this tutorial.
How is can I setup 3 different dc for a single LDAP server

A: The answer to that is dependent on how you want to use the LDAP server.

*

*If you want to have three complete separate LDAP trees, you would configure multiple databases in the cn=config configuration with the olcDatabase object type. Note that if you do it this way, you would need to setup a separate LDAP connection for each LDAP tree and you can't search for objects in other domains at all.

*If you just want a logical separation, e.g. having separate mail accounts for each domain, you would just add a junction point at appropriate branches in the tree. Something like ou=example.com,cn=users,dc=example,dc=com and ou=example.in,cn=users,dc=example,dc=com where each cn would hold the users for a subdomain. Depending on your needs, you would have multiple such junction points, other options might be cn=groups,dc=example,dc=com or cn=sites,dc=example,dc=com.
This way, you can either search for users in ou=example.com,cn=users,dc=example,dc=com and find only users for that domain or you can search more globally in cn=users,dc=example,dc=com and find all users.

*A third approach is to have multiple subtrees,e.g. ou=example.com,dc=example,dc=com and ou=example.in,dc=example,dc=com and then have sub containers for actual objects like cn=users,ou=example.com,dc=example,dc=com. Note that while this approach offers better separation, it often turns out to be quite inefficient, as you now have to search the whole tree if you want to find an object in any of the domains.

An illustration:

*

*Variant 1:
dc=example,dc=com
    cn=users
    cn=groups
------------------  Complete separation
dc=example,dc=in
    cn=users
    cn=groups

*Variant 2
dc=example,dc=com
    cn=users                <---- Junction point
        ou=example.com
            uid=alice
            uid=bob
        ou=example.in
            uid=claire
    cn=groups               <---- Junction point
         ou=example.com
            cn=accounting
         ou=example.in
            cn=hr

*Variant 3
dc=example,dc=com
    ou=example.com
        cn=users
        cn=groups
    ou=example.in
        cn=users
        cn=groups


text:
Q: What are the benefits of using an online pass? I bought a used copy of "Medal of Honor" for my PS3 the last days. As I opened the case there was a paper with a used online pass on it. Because I never owned a game which needed an online pass I started the multiplayer directly to check if I can play without buying a new one. After skipping the purchase of a new online pass (10€ btw) I could play online just like a normal game without such mechanics.
Due to this EA-article I assumed that the online pass is no longer needed, but I can't find much more information.

Do I still need an Online Pass to play multiplayer games online?
For new EA titles, Online Pass will no longer be needed or included.  Additionally, we are in the process of eliminating Online Pass requirements from existing EA games.  This process will take several weeks.  For some games, the prompt to enter an Online Pass code will no longer appear; for others, you will still need to download and install an Online Pass, but they will be available free of charge from the Xbox LIVE Marketplace or PlayStation Store.

So my question is: Does Medal of Honor still need an online pass - the prompt to enter one is still there - and if so, what are the benefits of it? I could play without entering an online pass perfectly.

A: They changed it. Before you had to have an Online Pass to actually play online (there might be additional maps or classes playable with it, but I don't think so). As the pass should be free by now, just grab one to get rid of the prompt, in case it returns. Otherwise you could probably just ignore it.


text:
Q: converting a string into parameter for GET request in python I am calling a GET API to retrieve some data. For get call I need to covert my keyword as
keyword = "mahinder singh dhoni"

into
caption%3Amahinder%2Ccaption%3Asingh%2Ccaption%3Adhoni

I am new to python and dont know the pythonic way. I am doing like this
caption_heading = "caption%3A"
caption_tail = "%2Ccaption%3A"

keyword = "mahinder singh dhoni"
x = keyword.split(" ")
new_caption_keyword = []
new_caption_keyword.append(caption_heading)
for data in x:
    new_caption_keyword.append(data)
    new_caption_keyword.append(caption_tail)

search_query = ''.join(new_caption_keyword)
search_query = search_query[:-13]

print("new transformed keyword", search_query)

Is there a better way to do this.I means this is kind of hard coding.
Thanks

A: Best to turn our original string into a list:
>>> keyword = "mahinder singh dhoni"
>>> keyword.split()
['mahinder', 'singh', 'dhoni']

Then your actual string looks like caption:...,caption:...,caption:..., that can be done with a join and a format:
>>> # if you're < python3.6, use 'caption:{}'.format(part)`
>>> [f'caption:{part}' for part in keyword.split()]
['caption:mahinder', 'caption:singh', 'caption:dhoni']
>>> ','.join([f'caption:{part}' for part in keyword.split()])
'caption:mahinder,caption:singh,caption:dhoni'

And finally you'll urlencode using urllib.parse:
>>> import urllib.parse
>>> urllib.parse.quote(','.join([f'caption:{part}' for part in keyword.split()]))
'caption%3Amahinder%2Ccaption%3Asingh%2Ccaption%3Adhoni'

A: so try this way,
instead of split you can replace " " empty space with "%2Ccaption%3A" and start your string with "caption%3A"
for 2.x:
>>> from urllib import quote
>>> keyword = "mahinder singh dhoni"
>>> quote(','.join(['caption:%s'%i for i in keyword.split()]))

for 3.x:
>>> from urllib.parse import quote
>>> keyword = "mahinder singh dhoni"
>>> quote(','.join(['caption:%s'%i for i in keyword.split()]))