答:
You need to combine control is-expanded with select is-fullwidth.

Here is an example:

@import url('https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field is-horizontal">
  <div class="field-body">
     <div class="field">
        <p class="control is-expanded has-icons-left">
           <input class="input" type="text" placeholder="Search" name="id" id="id">
           <span class="icon is-small is-left"><i class="fa fa-search"></i></span>
        </p>
     </div>
     <div class="field">
        <p class="control is-expanded">
           <span class="select is-fullwidth">
              <select name="status" id="status">
                 <option value="">Status:</option>
                 <option value="active">active</option>
                 <option value="pause">pause</option>
              </select>
           </span>
        </p>
     </div>
     <div class="field">
        <p class="control is-expanded">
           <span class="select is-fullwidth">
              <select name="limit" id="limit">
                 <option value="">Limits:</option>
                 <option value="10">10</option>
                 <option value="20">20</option>
              </select>
           </span>
        </p>
     </div>
  </div></code>```

Title: bulma: horizontal form controls not expanded correctly

Body:
You need to combine control is-expanded with select is-fullwidth.

Here is an example:

@import url('https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css');

<div class="field is-horizontal">
  <div class="field-body">
     <div class="field">
        <p class="control is-expanded has-icons-left">
           <input class="input" type="text" placeholder="Search" name="id" id="id">
           <span class="icon is-small is-left"><i class="fa fa-search"></i></span>
        </p>
     </div>
     <div class="field">
        <p class="control is-expanded">
           <span class="select is-fullwidth">
              <select name="status" id="status">
                 <option value="">Status:</option>
                 <option value="active">active</option>
                 <option value="pause">pause</option>
              </select>
           </span>
        </p>
     </div>
     <div class="field">
        <p class="control is-expanded">
           <span class="select is-fullwidth">
              <select name="limit" id="limit">
                 <option value="">Limits:</option>
                 <option value="10">10</option>
                 <option value="20">20</option>
              </select>
           </span>
        </p>
     </div>
  </div>


来源: stackexchange

问:
How to correctly pass a SQL query as parameter in Jasper Reports?
I've looked into all other questions regarding this topic and I followed all steps mentioned there, however I'm still getting an error when trying to pass an entire SQL statement as Parameter.

This is my SQLQuery Parameter:

```<code><parameter name="SQLTag" class="java.lang.String">
    <defaultValueExpression><![CDATA["SELECT * FROM REPORT_VER WHERE TAG BETWEEN  $P{Von}  AND $P{Bis}"]]></defaultValueExpression>
</parameter>
</code>```

I've checked it and the SQL works perfectly fine when passed directly into the Report SQL field.
However because I want to have conditional SQL queries I need them passed through a parameter. Anyone knows what I'm missing?

I tried to use $P{SQLTag} and $P!{SQLTag} expressions at queryString/

Stack trace:

```<code>net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRException: Error executing SQL statement for: Abnahme.
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:548)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$20(ReportControler.java:523)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$5.run(ReportControler.java:404)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
Caused by: net.sf.jasperreports.engine.JRException: Error executing SQL statement for: Abnahme.
    at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:344)
    at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:1245)
    at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:723)
    at net.sf.jasperreports.engine.fill.BaseReportFiller.setParameters(BaseReportFiller.java:438)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:550)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFill.run(BaseFillHandle.java:123)
</code>```

答:
In case using parameters at defaultValueExpression you should operate with them as a common Java variable.

For example:

```<code><parameter name="fieldFilter" class="java.lang.String">
    <defaultValueExpression><![CDATA["someValue"]]></defaultValueExpression>
</parameter>
<parameter name="query" class="java.lang.String">
    <defaultValueExpression><![CDATA["SELECT * FROM some_table WHERE some_field = '" + $P{fieldFilter} + "'"]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[$P!{query}]]>
</queryString>
</code>```

or like this:

```<code><parameter name="intFieldFilter" class="java.lang.Integer">
    <defaultValueExpression><![CDATA[2017]]></defaultValueExpression>
</parameter>
<parameter name="strFieldFilter" class="java.lang.String">
    <defaultValueExpression><![CDATA["someValue"]]></defaultValueExpression>
</parameter>
<parameter name="query" class="java.lang.String">
    <defaultValueExpression><![CDATA[String.format("SELECT * FROM some_table WHERE some_field = '%1$s' AND trunc(date_field, 'yyyy') = trunc(to_date(%2$d, 'yyyy'), 'yyyy')", $P{strFieldFilter}, $P{intFieldFilter})]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[$P!{query}]]>
</queryString>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've looked into all other questions regarding this topic and I followed all steps mentioned there, however I'm still getting an error when trying to pass an entire SQL statement as Parameter.

This is my SQLQuery Parameter:

<parameter name="SQLTag" class="java.lang.String">
    <defaultValueExpression><![CDATA["SELECT * FROM REPORT_VER WHERE TAG BETWEEN  $P{Von}  AND $P{Bis}"]]></defaultValueExpression>
</parameter>

I've checked it and the SQL works perfectly fine when passed directly into the Report SQL field.
However because I want to have conditional SQL queries I need them passed through a parameter. Anyone knows what I'm missing?

I tried to use $P{SQLTag} and $P!{SQLTag} expressions at queryString/

Stack trace:

net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRException: Error executing SQL statement for: Abnahme.
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:548)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$20(ReportControler.java:523)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$5.run(ReportControler.java:404)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
Caused by: net.sf.jasperreports.engine.JRException: Error executing SQL statement for: Abnahme.
    at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:344)
    at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:1245)
    at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:723)
    at net.sf.jasperreports.engine.fill.BaseReportFiller.setParameters(BaseReportFiller.java:438)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:550)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFill.run(BaseFillHandle.java:123)

Body:
In case using parameters at defaultValueExpression you should operate with them as a common Java variable.

For example:

<parameter name="fieldFilter" class="java.lang.String">
    <defaultValueExpression><![CDATA["someValue"]]></defaultValueExpression>
</parameter>
<parameter name="query" class="java.lang.String">
    <defaultValueExpression><![CDATA["SELECT * FROM some_table WHERE some_field = '" + $P{fieldFilter} + "'"]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[$P!{query}]]>
</queryString>

or like this:

<parameter name="intFieldFilter" class="java.lang.Integer">
    <defaultValueExpression><![CDATA[2017]]></defaultValueExpression>
</parameter>
<parameter name="strFieldFilter" class="java.lang.String">
    <defaultValueExpression><![CDATA["someValue"]]></defaultValueExpression>
</parameter>
<parameter name="query" class="java.lang.String">
    <defaultValueExpression><![CDATA[String.format("SELECT * FROM some_table WHERE some_field = '%1$s' AND trunc(date_field, 'yyyy') = trunc(to_date(%2$d, 'yyyy'), 'yyyy')", $P{strFieldFilter}, $P{intFieldFilter})]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[$P!{query}]]>
</queryString>


问:
How can I use the access token to get a list of projects from a website in c#?
I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:</p>

```<code>public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";

public async Task GetProjectsAsync()
{
    try
    {
        HttpClient client = new HttpClient();
        var projects = "https://app.rakenapp.com/api/v2/projects?" + token;

        client.CancelPendingRequests();
        HttpResponseMessage output = await client.GetAsync(projects);

        if (output.IsSuccessStatusCode)
        {
            string response = await output.Content.ReadAsStringAsync();
            project proj = JsonConvert.DeserializeObject<project>(response);

            if (proj != null)
            {
                Console.WriteLine(proj.name); // You will get the projects here.
            }
        }
    }
    catch (Exception ex)
    {
        //catching the exception
    }

}
</code>```

答:
you need to add a header to your request:</p>

```<code> string url = "https://app.rakenapp.com/api/v2/projects";
 using (var httpClient = new HttpClient())
       {
           httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
           HttpResponseMessage response = await httpClient.GetAsync(url);
           var contents = await response.Content.ReadAsStringAsync();
           var model = JsonConvert.DeserializeObject<project>.contents);
           return model;
        }
</code>```

Body:
I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:

public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";

public async Task GetProjectsAsync()
{
    try
    {
        HttpClient client = new HttpClient();
        var projects = "https://app.rakenapp.com/api/v2/projects?" + token;

        client.CancelPendingRequests();
        HttpResponseMessage output = await client.GetAsync(projects);

        if (output.IsSuccessStatusCode)
        {
            string response = await output.Content.ReadAsStringAsync();
            project proj = JsonConvert.DeserializeObject<project>(response);

            if (proj != null)
            {
                Console.WriteLine(proj.name); // You will get the projects here.
            }
        }
    }
    catch (Exception ex)
    {
        //catching the exception
    }

}

Body:
you need to add a header to your request:

 string url = "https://app.rakenapp.com/api/v2/projects";
 using (var httpClient = new HttpClient())
       {
           httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
           HttpResponseMessage response = await httpClient.GetAsync(url);
           var contents = await response.Content.ReadAsStringAsync();
           var model = JsonConvert.DeserializeObject<project>.contents);
           return model;
        }


问:
IEnumerable parser class design
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        /// <summary>
        /// Creates a new DDocument from a file.
        /// </summary>
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        /// <summary>
        /// Creates a new XDocument instance by using the specified stream.
        /// </summary>
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        /// <summary>
        /// Gets or sets a list with MetaInformation containing DDataElements
        /// </summary>
        public List<DDataElement> Data
        {
            get;
            set;
        }

        /// <summary>
        /// Returns an enumerator that can be used to iterate through the DDocument
        /// </summary>
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}
</code>```

I wanted to know what you think of it. Are there any changes you would make in this class?

答: In terms of recommendations, I would make your class names more meaningful. DicomDocument and DicomElement are just more descriptive and anyone else working with your code will immediately know what they are (especially if they are familiar with the DICOM structure).</p>

ContentLicense: CC BY-SA 2.5

Title: IEnumerable parser class design

Body:
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        ///
        /// Creates a new DDocument from a file.
        ///
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        ///
        /// Creates a new XDocument instance by using the specified stream.
        ///
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        ///
        /// Gets or sets a list with MetaInformation containing DDataElements
        ///
        public List<DDataElement> Data
        {
            get;
            set;
        }

        ///
        /// Returns an enumerator that can be used to iterate through the DDocument
        ///
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}

I wanted to know what you think of it. Are there any changes you would make in this class?


问:
I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported
Currently I'm using HttpClient, HttpPost to send data to my PHP server from an Android app but all those methods were deprecated in API 22 and removed in API 23, so what are the alternative options to it?

I searched everywhere but I didn't find anything.

答:
if targeted for API 22 and older, then should add the following line into build.gradle

```<code>dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}
</code>```

if targeted for API 23 and later, then should add the following line into build.gradle

```<code>dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
</code>```

If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:

```<code>useLibrary 'org.apache.http.legacy'
</code>```

to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!

Body:
if targeted for API 22 and older, then should add the following line into build.gradle

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

if targeted for API 23 and later, then should add the following line into build.gradle

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:

useLibrary 'org.apache.http.legacy'

to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!


问:
WPF BitmapSource Alpha Channel Offset
I have a BitmapSource image that I would like to efficiently offset the alpha channel by a fixed amount i.e. Alpha=Floor(Alpha-x).  What is the most efficient way to do this.  I was trying using DrawingContext.PushOpacity() then DrawImage() but this multiplies the opacity and I am really looking to do a additive offset

Update

I am trying to achieve an effect when text changes on my display. The idea is to fade the previous text value away when a new value is set.  I have a rough implementation but I would like input on this implementation or if there is a better strategy.  An example of how the effect should look (hard with a still image)

And the code

```<code>    public class TransitionalText : FrameworkElement
    {
        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TransitionalText), new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.None, OnTextPropertyChanged));
        public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register("Transition", typeof(Int16), typeof(TransitionalText), new UIPropertyMetadata((Int16)255,OnTransitionPropertyChanged));

        private RenderTargetBitmap textCache, renderBitmap;
        private byte[] transitionCache;

        private void DrawText()
        {
            int stride = renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3);

            // Copy Current Render Scene To Cache
            renderBitmap.CopyPixels(transitionCache, stride, 0);

            // Clear Cached Text Bitmap
            textCache.Clear();

            // Render New Text Value
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            FormattedText formattedText = new FormattedText(Text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(new FontFamily("lucidia"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal), 32, Brushes.Black);

            drawingContext.DrawText(formattedText, new Point(0, 0));
            drawingContext.Close();
            textCache.Render(drawingVisual);

            // Create Opacity Mask
            byte[] opacityMask = new byte[renderBitmap.PixelHeight * stride];

            // Remove Overlapping Pixels
            for (int i=3; i<opacityMask.Length; i+=4)
            {
                transitionCache[i] -= (transitionCache[i] > opacityMask[i]) ? opacityMask[i] : transitionCache[i];
            }

        }

        private void FadeTransition(int fadeValue)
        {
            for (int i = 3; i < transitionCache.Length; i += 4)
            {
                transitionCache[i] -= (byte)((transitionCache[i] > fadeValue) ? fadeValue : transitionCache[i]);
            }
        }

        private void Render()
        {
            renderBitmap.Clear();
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            // Draw Transition
            drawingContext.DrawImage(BitmapSource.Create(renderBitmap.PixelWidth, renderBitmap.PixelHeight, renderBitmap.DpiX, renderBitmap.DpiY, renderBitmap.Format, renderBitmap.Palette, transitionCache, renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3)), new Rect(RenderSize));
            drawingContext.DrawImage(textCache, new Rect(RenderSize));
            drawingContext.Close();

            renderBitmap.Render(drawingVisual);

        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            renderBitmap = new RenderTargetBitmap((int)RenderSize.Width, (int)RenderSize.Height, 96, 96, PixelFormats.Pbgra32);
            textCache = (RenderTargetBitmap)renderBitmap.Clone();

            int stride = renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3);
        transitionCache = new byte[renderBitmap.PixelHeight * stride];

            DrawText();
            Render();

            drawingContext.DrawImage(renderBitmap, new Rect(RenderSize));

        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((TransitionalText)d).OnTextPropertyChanged((string)e.NewValue);
        }
        private void OnTextPropertyChanged(string newText)
        {
            if (renderBitmap!=null)
            {
                DrawText();
                Int16Animation intAnimation = new Int16Animation(255, 0, TimeSpan.FromMilliseconds(150));
                BeginAnimation(TransitionProperty, intAnimation);
            }

        }

        private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((TransitionalText)d).OnTransitionPropertyChanged((Int16)e.OldValue, (Int16)e.NewValue);
        }

        private void OnTransitionPropertyChanged(int oldValue, int newValue)
        {
            if (newValue < oldValue)
            {
                FadeTransition(oldValue - newValue);
                Render();
            }
        }
    }
</code>```

I know I can do better with parameterizing for fonts etc. but I want to know that I am not wasting my time first.  This works reasonable well as long as the change rate of the change is not too fast (looks good at 100ms not so good at 10ms however that test was just with DispatcherTimer so I think that the rendering was conflicting for execution time with the timer event)

I would be interested if there are better ways to achieve this result like CustomShader etc.

Thanks

答:
How you plan to use the resulting pixel data is important here.

Custom Effect

If you only need to offset the alpha for the purpose of rendering (it sounds like you do), you can create a custom shader effect to accomplish this and not have to deal with modifying pixel data. This approach is especially useful if the value is changing over time, and you want to avoid rewriting a bitmap frequently.

If you have never created custom shader effects in WPF, there are some articles on the topic you can read up on. It basically involves writing and compiling a HLSL pixel shader, including the compiled shader as an application resource, creating a C# class that extends ShaderEffect, and connecting the effect to the shader.

Here is a quick untested mock up of a shader that theoretically has the effect you are looking for.

Shader

sampler2D inputSampler : register(S0);
float alpha : register(C0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 color = tex2D(inputSampler, uv);
    return float4(color.rgb, clamp(color.a + alpha, 0, 1));
}
```

<p><strong>Effect</strong></p>

<pre class="lang-cs prettyprint-override"><code>class AddAlphaEffect : ShaderEffect
{
    // The Input property is special and will automatically receive the content of the element being rendered
    public Brush Input
    {
        get { return (Brush)GetValue(InputProperty); }
        set { SetValue(InputProperty, value); }
    }
    public static readonly DependencyProperty InputProperty = RegisterPixelShaderSamplerProperty("Input", typeof(AddAlphaEffect), 0);

    public float Alpha
    {
        get { return (Point)GetValue(CenterProperty); }
        set { SetValue(CenterProperty, value); }
    }
    public static readonly DependencyProperty AlphaProperty = DependencyProperty.Register("Alpha", typeof(float), typeof(AddAlphaEffect),
        new PropertyMetadata(0.0f, PixelShaderConstantCallback(0)));

    public AddAlphaEffect()
    {
        // Reference the compiled shader here, which should be included as a resource in your applciation.
        // ResourceHelper is my own utility that formats URIs for me. The returned URI
        // string will be something like /AssemblyName;component/Effects/AddAlpha.ps
        PixelShader = new PixelShader() { UriSource = ResourceHelper.GetResourceUri("Effects/AddAlpha.ps", relative: true)};

        UpdateShaderValue(AlphaProperty);
    }
}
</code>```

Usage

```<code><Image
    Source="some image">
    <Image.Effect>
        <effects:AddAlphaEffect
            Alpha="0.2" />
    </Image.Effect>
</Image>
</code>```

Writable Bitmap

If you want to modify the data and hold on to it for a while because it is not changing frequently (or you want to save it out), then you will probably want to use a WritableBitmap and update the pixel data directly.

From MSDN documentation:

Call one of the WritePixels overloads to update and display content in the back buffer automatically.

For greater control over updates, and for multi-threaded access to the back buffer, use the following workflow.

Call the Lock method to reserve the back buffer for updates.

Obtain a pointer to the back buffer by accessing the BackBuffer property.

Write changes to the back buffer. Other threads may write changes to
  the back buffer when the WriteableBitmap is locked.

Call the AddDirtyRect method to indicate areas that have changed.

Call the Unlock method to release the back buffer and allow presentation to
  the screen.

Note that the WritableBitmap method may perform better than a custom shader due to the poor performance of custom shader effects in WPF. It may be worth trying both if you are using this effect enough to raise performance concerns.

Title: WPF BitmapSource Alpha Channel Offset

Body:
I have a BitmapSource image that I would like to efficiently offset the alpha channel by a fixed amount i.e. Alpha=Floor(Alpha-x).  What is the most efficient way to do this.  I was trying using DrawingContext.PushOpacity() then DrawImage() but this multiplies the opacity and I am really looking to do a additive offset

Update

I am trying to achieve an effect when text changes on my display. The idea is to fade the previous text value away when a new value is set.  I have a rough implementation but I would like input on this implementation or if there is a better strategy.  An example of how the effect should look (hard with a still image)

And the code

    public class TransitionalText : FrameworkElement
    {
        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TransitionalText), new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.None, OnTextPropertyChanged));
        public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register("Transition", typeof(Int16), typeof(TransitionalText), new UIPropertyMetadata((Int16)255,OnTransitionPropertyChanged));

        private RenderTargetBitmap textCache, renderBitmap;
        private byte[] transitionCache;

        private void DrawText()
        {
            int stride = renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3);

            // Copy Current Render Scene To Cache
            renderBitmap.CopyPixels(transitionCache, stride, 0);

            // Clear Cached Text Bitmap
            textCache.Clear();

            // Render New Text Value
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();
            FormattedText formattedText = new FormattedText(Text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(new FontFamily("lucidia"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal), 32, Brushes.Black);

            drawingContext.DrawText(formattedText, new Point(0, 0));
            drawingContext.Close();
            textCache.Render(drawingVisual);

            // Create Opacity Mask
            byte[] opacityMask = new byte[renderBitmap.PixelHeight * stride];

            // Remove Overlapping Pixels
            for (int i=3; i<opacityMask.Length; i+=4)
            {
                transitionCache[i] -= (transitionCache[i] > opacityMask[i]) ? opacityMask[i] : transitionCache[i];
            }

        }

        private void FadeTransition(int fadeValue)
        {
            for (int i = 3; i < transitionCache.Length; i += 4)
            {
                transitionCache[i] -= (byte)((transitionCache[i] > fadeValue) ? fadeValue : transitionCache[i]);
            }
        }

        private void Render()
        {
            renderBitmap.Clear();
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            // Draw Transition
            drawingContext.DrawImage(BitmapSource.Create(renderBitmap.PixelWidth, renderBitmap.PixelHeight, renderBitmap.DpiX, renderBitmap.DpiY, renderBitmap.Format, renderBitmap.Palette, transitionCache, renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3)), new Rect(RenderSize));
            drawingContext.DrawImage(textCache, new Rect(RenderSize));
            drawingContext.Close();

            renderBitmap.Render(drawingVisual);

        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            renderBitmap = new RenderTargetBitmap((int)RenderSize.Width, (int)RenderSize.Height, 96, 96, PixelFormats.Pbgra32);
            textCache = (RenderTargetBitmap)renderBitmap.Clone();

            int stride = renderBitmap.PixelWidth * ((renderBitmap.Format.BitsPerPixel + 7) >> 3);
        transitionCache = new byte[renderBitmap.PixelHeight * stride];

            DrawText();
            Render();

            drawingContext.DrawImage(renderBitmap, new Rect(RenderSize));

        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((TransitionalText)d).OnTextPropertyChanged((string)e.NewValue);
        }
        private void OnTextPropertyChanged(string newText)
        {
            if (renderBitmap!=null)
            {
                DrawText();
                Int16Animation intAnimation = new Int16Animation(255, 0, TimeSpan.FromMilliseconds(150));
                BeginAnimation(TransitionProperty, intAnimation);
            }

        }

        private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((TransitionalText)d).OnTransitionPropertyChanged((Int16)e.OldValue, (Int16)e.NewValue);
        }

        private void OnTransitionPropertyChanged(int oldValue, int newValue)
        {
            if (newValue < oldValue)
            {
                FadeTransition(oldValue - newValue);
                Render();
            }
        }
    }

I know I can do better with parameterizing for fonts etc. but I want to know that I am not wasting my time first.  This works reasonable well as long as the change rate of the change is not too fast (looks good at 100ms not so good at 10ms however that test was just with DispatcherTimer so I think that the rendering was conflicting for execution time with the timer event)

I would be interested if there are better ways to achieve this result like CustomShader etc.

Thanks

Body:
How you plan to use the resulting pixel data is important here.

Custom Effect

If you only need to offset the alpha for the purpose of rendering (it sounds like you do), you can create a custom shader effect to accomplish this and not have to deal with modifying pixel data. This approach is especially useful if the value is changing over time, and you want to avoid rewriting a bitmap frequently.

If you have never created custom shader effects in WPF, there are some articles on the topic you can read up on. It basically involves writing and compiling a HLSL pixel shader, including the compiled shader as an application resource, creating a C# class that extends ShaderEffect, and connecting the effect to the shader.

Here is a quick untested mock up of a shader that theoretically has the effect you are looking for.

Shader

sampler2D inputSampler : register(S0);
float alpha : register(C0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 color = tex2D(inputSampler, uv);
    return float4(color.rgb, clamp(color.a + alpha, 0, 1));
}

Effect

class AddAlphaEffect : ShaderEffect
{
    // The Input property is special and will automatically receive the content of the element being rendered
    public Brush Input
    {
        get { return (Brush)GetValue(InputProperty); }
        set { SetValue(InputProperty, value); }
    }
    public static readonly DependencyProperty InputProperty = RegisterPixelShaderSamplerProperty("Input", typeof(AddAlphaEffect), 0);

    public float Alpha
    {
        get { return (Point)GetValue(CenterProperty); }
        set { SetValue(CenterProperty, value); }
    }
    public static readonly DependencyProperty AlphaProperty = DependencyProperty.Register("Alpha", typeof(float), typeof(AddAlphaEffect),
        new PropertyMetadata(0.0f, PixelShaderConstantCallback(0)));

    public AddAlphaEffect()
    {
        // Reference the compiled shader here, which should be included as a resource in your applciation.
        // ResourceHelper is my own utility that formats URIs for me. The returned URI
        // string will be something like /AssemblyName;component/Effects/AddAlpha.ps
        PixelShader = new PixelShader() { UriSource = ResourceHelper.GetResourceUri("Effects/AddAlpha.ps", relative: true)};

        UpdateShaderValue(AlphaProperty);
    }
}

Usage

<Image
    Source="some image">
    <Image.Effect>
        <effects:AddAlphaEffect
            Alpha="0.2" />
    </Image.Effect>
</Image>

Writable Bitmap

If you want to modify the data and hold on to it for a while because it is not changing frequently (or you want to save it out), then you will probably want to use a WritableBitmap and update the pixel data directly.

From MSDN documentation:

Call one of the WritePixels overloads to update and display content in the back buffer automatically.

For greater control over updates, and for multi-threaded access to the back buffer, use the following workflow.

Call the Lock method to reserve the back buffer for updates.

Obtain a pointer to the back buffer by accessing the BackBuffer property.

Write changes to the back buffer. Other threads may write changes to
  the back buffer when the WriteableBitmap is locked.

Call the AddDirtyRect method to indicate areas that have changed.

Call the Unlock method to release the back buffer and allow presentation to
  the screen.

Note that the WritableBitmap method may perform better than a custom shader due to the poor performance of custom shader effects in WPF. It may be worth trying both if you are using this effect enough to raise performance concerns.


问:
File not Found Codeigniter in production
So I've put my website online and only my landing page (Home_controller) is working fine but any other page is not working.

http://www.my-websiteabc.net/ works fine but not http://www.my-websiteabc.net/About_cookies

http://www.my-websiteabc.net/Home_controller and http://www.my-websiteabc.net/home_controller don't work either.

I've spent all day reading different suggestions and workarounds but can't get it to work.

What I've tried so far:

1.My Controllers filenames and Classes have a first Uppercase character. For instance:

About_cookies.php

class About_cookies extends CI_Controller

View: cookies.php

2.My folder structure is:

```<code>/.
   /my-websiteabc
   /my-websiteabc/application
   /my-websiteabc/js
   /my-websiteabc/css
   /my-websiteabc/system
</code>```

3.I have .htaccess in the root folder contains:

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>
</code>```

4.I also tried with/without this .htaccess in the application folder:

```<code><IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
</code>```

5.My routes.php :

```<code>$route['default_controller'] = 'Home_controller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

6.And config.php:

```<code>$config['base_url'] = 'http://www.my-websiteabc.net/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
</code>```

I get File not found. when trying anything else than http://www.my-websiteabc.net/ but on this page all the images and CSS are correct so I guess my path is correct.

Using CI 3.1.5 and PHP 7.1.6

Update 05/07:

Controller definition (About_cookies.php):

```<code><?php
class About_cookies extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $ci =& get_instance();
        if ($ci->session->userdata('site_lang')) {
            $siteLang = $ci->session->userdata('site_lang');
        } else {
            $siteLang = 'english';
            $this->session->set_userdata('site_lang', $siteLang);
        }
        $ci->lang->load('home',$siteLang);
    }

    public function index(){
        $data['main_content'] = 'cookies';
        $this->load->view('templates/default',$data);
    }
}
</code>```

The URL my browser is trying to access:
http://www.my-websiteabc.net/About_cookies

My view: cookies.php

答:
After reading through many many posts, I finally found the solution here.

The following .htaccess works for me:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code>```

The thing that makes the difference is the question mark ? after the index.php

I'm not able to say if this slows down the performance yet but I really would like to know what this ? changes. I didn't find any documentation on this topic.

Body:
So I've put my website online and only my landing page (Home_controller) is working fine but any other page is not working.

http://www.my-websiteabc.net/ works fine but not http://www.my-websiteabc.net/About_cookies

http://www.my-websiteabc.net/Home_controller and http://www.my-websiteabc.net/home_controller don't work either.

I've spent all day reading different suggestions and workarounds but can't get it to work.

What I've tried so far:

1.My Controllers filenames and Classes have a first Uppercase character. For instance:

About_cookies.php

class About_cookies extends CI_Controller

View: cookies.php

2.My folder structure is:

/.
   /my-websiteabc
   /my-websiteabc/application
   /my-websiteabc/js
   /my-websiteabc/css
   /my-websiteabc/system

3.I have .htaccess in the root folder contains:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>

4.I also tried with/without this .htaccess in the application folder:

<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

5.My routes.php :

$route['default_controller'] = 'Home_controller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

6.And config.php:

$config['base_url'] = 'http://www.my-websiteabc.net/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

I get File not found. when trying anything else than http://www.my-websiteabc.net/ but on this page all the images and CSS are correct so I guess my path is correct.

Using CI 3.1.5 and PHP 7.1.6

Update 05/07:

Controller definition (About_cookies.php):

<?php
class About_cookies extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $ci =& get_instance();
        if ($ci->session->userdata('site_lang')) {
            $siteLang = $ci->session->userdata('site_lang');
        } else {
            $siteLang = 'english';
            $this->session->set_userdata('site_lang', $siteLang);
        }
        $ci->lang->load('home',$siteLang);
    }

    public function index(){
        $data['main_content'] = 'cookies';
        $this->load->view('templates/default',$data);
    }
}

The URL my browser is trying to access:
http://www.my-websiteabc.net/About_cookies

My view: cookies.php

Body:
After reading through many many posts, I finally found the solution here.

The following .htaccess works for me:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

The thing that makes the difference is the question mark ? after the index.php

I'm not able to say if this slows down the performance yet but I really would like to know what this ? changes. I didn't find any documentation on this topic.


问:
Woocommerce rest api - Create product via ajax in wordpress
Well, the problem is here. I created a local project to create a product in Woocommerce mounted in wordpress on a remote server. My local project code is this one

```<code>    <?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
function creaProd(){
$precio = $_POST['Total'];
$imagen = $_POST['Imagen'];
$descrip = $_POST['Descripcion'];
$tipo = $_POST['Tipo'];

$woocommerce = new Client(
    'http://example.com',
    'ck_sdfsdfsdfsfdxxx',
    'cs_sdfsdfsfsdfaxxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]
);

$data = [
    'name' => $tipo,
    'type' => 'simple',
    'regular_price' => $precio,
    'description' => $descrip,
    'short_description' => $descrip,
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => [
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 0
        ],
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 1
        ]
    ]
];

print_r($woocommerce->post('products', $data));
}
creaProd();
</code>```

And evertything works fine, the problem is, that I have tried a bunch of things, but I just don't get to create the product working in the wordpress project.

I put it in the wp-includes folder and the wp-content, but didn't work.

I tried to call an ajax to example.com/wp-includes/myFile.php but I can't reach it, I can reach files like example.com/wp-includes/option.php and all the files already there, but if I upload that one, I just can't, and I don't know where to put the vendor folder either.

Which is the right way to integrate this project to my real site in Wordpress?

Hope someone knows how to do this. Thanks.

答:
I think the best way to integrate third party libraries into Wordpress is creating your own plugins (This for me is the best option, cause you can use other API Wordpress even security stuff like if a user is login or have the right permissions). they are simple to create and they can be enabled through the Wordpress dashboard admin.

Here is some post about it:

How to create plugin - Wordpress Documentation

in this article you can find how to write a plugin in Wordpress from the official documentation

Body:
Well, the problem is here. I created a local project to create a product in Woocommerce mounted in wordpress on a remote server. My local project code is this one

    <?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
function creaProd(){
$precio = $_POST['Total'];
$imagen = $_POST['Imagen'];
$descrip = $_POST['Descripcion'];
$tipo = $_POST['Tipo'];

$woocommerce = new Client(
    'http://example.com',
    'ck_sdfsdfsdfsfdxxx',
    'cs_sdfsdfsfsdfaxxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]
);

$data = [
    'name' => $tipo,
    'type' => 'simple',
    'regular_price' => $precio,
    'description' => $descrip,
    'short_description' => $descrip,
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => [
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 0
        ],
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 1
        ]
    ]
];

print_r($woocommerce->post('products', $data));
}
creaProd();

And evertything works fine, the problem is, that I have tried a bunch of things, but I just don't get to create the product working in the wordpress project.

I put it in the wp-includes folder and the wp-content, but didn't work.

I tried to call an ajax to example.com/wp-includes/myFile.php but I can't reach it, I can reach files like example.com/wp-includes/option.php and all the files already there, but if I upload that one, I just can't, and I don't know where to put the vendor folder either.

Which is the right way to integrate this project to my real site in Wordpress?

Hope someone knows how to do this. Thanks.


问:
How to pull specific object from Json String
I am new to Json Parsing issue I have the below Json object and I need to get the User object from the below Json

```<code>{
  "aud": "RoomyClinetApps",
  "sub": "AAAA",
  "User": {
    "firtsName": "Godavarthi",
    "LastName": "chaitanya"
  },
  "iss": "Roomy",
  "iat": 1499279510
}
</code>```

The below is the code I am trying to pull the User object where the the above json is in jsonInString variable when i trying t print I am getting null

```<code>ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            User user= mapper.readValue(jsonInString.toString(), User.class);

 System.out.println(user.getFirtsName()); --> Null

public class User {
    @JsonProperty
    private String firtsName;
    @JsonProperty
    private String LastName;
}
</code>```

Could some one please Provide me a working code which is more appreciable.

Thanks
Chaitanya

答:
Tested the below code. It worked for me. Try this once.

```<code>public class Test {

    public static void main(String[] args) throws IOException {
        String jsonInString = "{\n"
                + "  \"aud\": \"RoomyClinetApps\",\n"
                + "  \"sub\": \"AAAA\",\n"
                + "  \"user\": {\n"
                + "    \"firtsName\": \"Godavarthi\",\n"
                + "    \"LastName\": \"chaitanya\"\n"
                + "  },\n"
                + "  \"iss\": \"Roomy\",\n"
                + "  \"iat\": 1499279510\n"
                + "}";
        ObjectMapper mapper = new ObjectMapper().configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonObject jobj = mapper.readValue(jsonInString.toString(), JsonObject.class);

        System.out.println(jobj.getUser().getFirtsName());
    }

}

class User {

    private String firtsName;
    private String LastName;

    public String getFirtsName() {
        return firtsName;
    }

    public void setFirtsName(String firtsName) {
        this.firtsName = firtsName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String LastName) {
        this.LastName = LastName;
    }

}

class JsonObject {

    private String aud;
    private String sub;
    private User user;
    private String iss;
    private long iat;

    public String getAud() {
        return aud;
    }

    public void setAud(String aud) {
        this.aud = aud;
    }

    public String getSub() {
        return sub;
    }

    public void setSub(String sub) {
        this.sub = sub;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getIss() {
        return iss;
    }

    public void setIss(String iss) {
        this.iss = iss;
    }

    public long getIat() {
        return iat;
    }

    public void setIat(long iat) {
        this.iat = iat;
    }

}
</code>```

Hope this is helpful.

Body:
I am new to Json Parsing issue I have the below Json object and I need to get the User object from the below Json

{
  "aud": "RoomyClinetApps",
  "sub": "AAAA",
  "User": {
    "firtsName": "Godavarthi",
    "LastName": "chaitanya"
  },
  "iss": "Roomy",
  "iat": 1499279510
}

The below is the code I am trying to pull the User object where the the above json is in jsonInString variable when i trying t print I am getting null

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            User user= mapper.readValue(jsonInString.toString(), User.class);

 System.out.println(user.getFirtsName()); --> Null

public class User {
    @JsonProperty
    private String firtsName;
    @JsonProperty
    private String LastName;
}

Could some one please Provide me a working code which is more appreciable.

Thanks
Chaitanya

Body:
Tested the below code. It worked for me. Try this once.

public class Test {

    public static void main(String[] args) throws IOException {
        String jsonInString = "{\n"
                + "  \"aud\": \"RoomyClinetApps\",\n"
                + "  \"sub\": \"AAAA\",\n"
                + "  \"user\": {\n"
                + "    \"firtsName\": \"Godavarthi\",\n"
                + "    \"LastName\": \"chaitanya\"\n"
                + "  },\n"
                + "  \"iss\": \"Roomy\",\n"
                + "  \"iat\": 1499279510\n"
                + "}";
        ObjectMapper mapper = new ObjectMapper().configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonObject jobj = mapper.readValue(jsonInString.toString(), JsonObject.class);

        System.out.println(jobj.getUser().getFirtsName());
    }

}

class User {

    private String firtsName;
    private String LastName;

    public String getFirtsName() {
        return firtsName;
    }

    public void setFirtsName(String firtsName) {
        this.firtsName = firtsName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String LastName) {
        this.LastName = LastName;
    }

}

class JsonObject {

    private String aud;
    private String sub;
    private User user;
    private String iss;
    private long iat;

    public String getAud() {
        return aud;
    }

    public void setAud(String aud) {
        this.aud = aud;
    }

    public String getSub() {
        return sub;
    }

    public void setSub(String sub) {
        this.sub = sub;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getIss() {
        return iss;
    }

    public void setIss(String iss) {
        this.iss = iss;
    }

    public long getIat() {
        return iat;
    }

    public void setIat(long iat) {
        this.iat = iat;
    }

}

Hope this is helpful.


问:
Activation functions - Neural Network
I am working with neural network in my freetime.
I developed already an easy XOR-Operation with a neural network.
But I dont know when I should use the correct activations function.

Is there an trick or is it just math logic?

答:
You can solve you problem with a sigmoid neurons in this case the activation function is:

https://chart.googleapis.com/chart?cht=tx&chl=%5Csigma%20%5Cleft%20(%20z%20%5Cright%20)%20%3D%20%5Cfrac%7B1%7D%7B1%2Be%5E%7B-z%7D%7D

Where:

https://chart.googleapis.com/chart?cht=tx&chl=z%20%3D%20%5Csum_%7Bj%7D%20(w_%7Bj%7Dx_%7Bj%7D%2Bb)

In this formula w there are the weights for each input, b is the bias and x there are the inputs, finally you can use back-propagation for calculate the cost function.

ContentLicense: CC BY-SA 4.0

Title: Activation functions - Neural Network


问:
Oracle Enterprise Manager Error - NMO setuid (root)
I've been trying for days to fix the "Connection to host as user SYSDBA failed.ERROR: NMO not setuid-root (Unix-only)".

All, without exception, of the blogs I visited, say that in order to fix the issue, it's only needed to run the root.sh script as root, where script path is $ORACLE_HOME. I did that during Oracle Grid and Database install as requested, but re-run to make sure.

If i list the permissions of nmo and nmb binary files after running the root.sh, i get:

ls -la ./nm?
-rws--x--- 1 root oinstall 34166 Apr 16 02:10 ./nmb
-rws--x--- 1 root oinstall 44437 Apr 16 02:05 ./nmo

After following tutorials, i did:
chown root nmo
chmod 6750 nmo
chown root nmb
chmmod 6750 nmb

permissions went like so:

ls -la ./nm?
-rwsr-s--- 1 root oinstall 34166 Apr 16 02:10 ./nmb
-rwsr-s--- 1 root oinstall 44437 Apr 16 02:05 ./nmo

Above permissions are according to what most blogs said they should be like. SO I relaunched EM:

emctl stop dbconsole
emctl start dbconsole

and Still got the error. I am almost performing a fresh install of Grid and Database, because I repeated the procedures multiple times, backed up /etc/oratab, deleted it and re run root.sh (so it could recreate oratab and fix possible mistakes).

I installed everything following the documentation, opened root.sh and referenced scripts so I could read them, but found nothing suspect.

My EM version is 11.2.0.3.0

I am running Oracle Linux under VirtualBox.

AGAIN: I've executed the root.sh as suggested in 99% of the websites regarding the setuid nmo error... Any clues or different procedures?

Thanks.

答:
Beside root.sh. You might run into my case.

Got the similar problem and found out the error came from inadequate swap space.  My swap is low and run down to 300MB, this problem "Failed to launch process: Cannot run program "/opt/OEMAgent/sbin/nmo" (in directory   /opt/OEMAgent/agent_inst/bin"): error=12, Not enough space" suddenly shows up.

It goes away immediately after adding additional swap space.


问:
How can I create a database from a database model using Entity Framework
I'm working on a ASP.Net application and I  have a database which so far i have been using as a prod database and dev database. I have decided now to create a new database which will be the dev database and also will take the prod-database model. Using Entity Framework I did created the database model. Now don't knew hot actually to create that dev database into another data server which is also going to be dev. Btw i'm working on Azure </p>

答:
You can use Entity Framework Code First Migrations. This also plays nicely with CD scenarios.

You could also use a Visual Studio database project. Note that this type of project is completely independent from Entity Framework. You'll have to manually right click and choose to deploy from Visual Studio. For CD scenarios, you can use VSTS to automatically deploy a DACPAC.

The benefits of both of these is that your database schema (and even reference data) is now part of source control right along with your project.


问:
fill option on html with java array list
i want to use multiple drop down select in JSF. here is the code that i found for this solution:

```<code><select id="dates-field2" class="multiselect-ui form-control"
                                        multiple="multiple">
         <option value="item1" >item1</option>
         <option value="item2" >item2</option>

</select>
</code>```

how can i use this in JSF page and fill options by array list in java instead of item1 and item2?
I'd used f:selectItems in JSF but it doesn't work!

答:
Maybe are you looking for h:selectManyMenu component? Is pretty similar to Ipper`s explanation:

```<code><h:selectManyMenu value="#{yourBean.selectedValues}">
    <f:selectItems value="#{yourBean.yourCollection}" var="item"
        itemLabel="#{item.label}" itemValue="#{item.value}"/>
</h:selectManyMenu>
</code>```

Body:
i want to use multiple drop down select in JSF. here is the code that i found for this solution:

<select id="dates-field2" class="multiselect-ui form-control"
                                        multiple="multiple">
         <option value="item1" >item1</option>
         <option value="item2" >item2</option>

</select>

how can i use this in JSF page and fill options by array list in java instead of item1 and item2?
I'd used f:selectItems in JSF but it doesn't work!

Body:
Maybe are you looking for h:selectManyMenu component? Is pretty similar to Ipper`s explanation:

<h:selectManyMenu value="#{yourBean.selectedValues}">
    <f:selectItems value="#{yourBean.yourCollection}" var="item"
        itemLabel="#{item.label}" itemValue="#{item.value}"/>
</h:selectManyMenu>


问:
PhalconPHP - getRouter in \Phalcon\Di
I've created new project using PhalconPHP 3.1.2. Everything works fine, but I have problem with IDE. In PhpStorm I've added ide/stubs/Phalcon from phalcon-devtools 3.1.2 as external libraries to dispose of warnings and errors.

But there is still one problem: in app/config/router.php (standard catalog structure created by devtools) I got line $router = $di->getRouter(); (also created by devtools) with warning: Method getRouter not found in Phalcon\Di\FactoryDefault.

There is no method in this class indeed: https://github.com/phalcon/phalcon-devtools/blob/3.1.x/ide/stubs/Phalcon/di/FactoryDefault.php -> https://github.com/phalcon/phalcon-devtools/blob/3.1.x/ide/stubs/Phalcon/Di.php

Now I don't have autocomplete of router's methods and this is problem for me. Did I do something wrong?

答:
First of all -- I'm not familiar with Phalcon. These are my comments based on general PHP/PhpStorm experience.

So .. if you look at that PHPDoc in the last link you gave (stubs for Di.php) you will notice the code example there that has $request = $di->getRequest();.

If you just copy-paste that whole sample you will get the same "method not found" error ... as getRquest() is transformed at run time via magic __get() method.

The possible solution here is to create your own stub for your $di:

Create new class that will extend original Di, e.g.

```<code>class MyDi extends \Phalcon\Di
</code>```

Add all those getRoute() / getRequest() etc methods there (could be real methods with empty bodies as in Phalcon's stub files .. or via @method PHPDoc tag)

Place such file anywhere in the project -- it will be used by IDE only.

When you are using your $di -- typehint it with your class, e.g.

```<code>/** @var \MyDi $di */
$di = new Di();
</code>```

In the above code during runtime $di will be an instance of Di but for PhpStorm during development it will be MyDi so all type hints are in place.

As possible alternative -- instead of using magic via $di->getRoute() .. try $di->getShared('route') or similar.

If you use PhpStorm's Advanced Metadata functionality it will allow to get correct type based on parameter value.

Title: PhalconPHP - getRouter in \Phalcon\Di

Body:
First of all -- I'm not familiar with Phalcon. These are my comments based on general PHP/PhpStorm experience.

So .. if you look at that PHPDoc in the last link you gave (stubs for Di.php) you will notice the code example there that has $request = $di->getRequest();.

If you just copy-paste that whole sample you will get the same "method not found" error ... as getRquest() is transformed at run time via magic __get() method.

The possible solution here is to create your own stub for your $di:

Create new class that will extend original Di, e.g.

class MyDi extends \Phalcon\Di

Add all those getRoute() / getRequest() etc methods there (could be real methods with empty bodies as in Phalcon's stub files .. or via @method PHPDoc tag)

Place such file anywhere in the project -- it will be used by IDE only.

When you are using your $di -- typehint it with your class, e.g.

/** @var \MyDi $di */
$di = new Di();

In the above code during runtime $di will be an instance of Di but for PhpStorm during development it will be MyDi so all type hints are in place.

As possible alternative -- instead of using magic via $di->getRoute() .. try $di->getShared('route') or similar.

If you use PhpStorm's Advanced Metadata functionality it will allow to get correct type based on parameter value.


问:
AspectJ - exclude inner classes from within clause
I have a marker interface which has several implementations. My intention is to add an aspect for all public methods defined in any class implementing that marker interface.
I defined my aspect as follows:

```<code>@Around("within(x.y.z.MyInterface+) && execution(public * *(..))")
</code>```

The problem is that this also catches inner classes, for example consider this method in one of the classes implementing that interface:

```<code>public void foo() {
  doSomething(new Request() {
    @Override
    public void do() {
      System.out.println("Hi");
    }
  });
}
</code>```

For some reason, the aspect also catches that "do()" method, even though it is does not inherit from MyInterface.

How should I fix my aspect definition?

答:
Instead of "within" use the "this" pointcut:

```<code>@Around("this(x.y.z.MyInterface+) && execution(public * *(..))")
</code>```

Basically "this" matches joinpoints where this, the current object reference at the time, is an instance of MyInterface. Anonymous classes not implementing your interface will no longer match.

JavaWorld has a nice article on it:
http://www.javaworld.com/article/2074048/core-java/i-want-my-aop---part-2.html?page=2

Body:
I have a marker interface which has several implementations. My intention is to add an aspect for all public methods defined in any class implementing that marker interface.
I defined my aspect as follows:

@Around("within(x.y.z.MyInterface+) && execution(public * *(..))")

The problem is that this also catches inner classes, for example consider this method in one of the classes implementing that interface:

public void foo() {
  doSomething(new Request() {
    @Override
    public void do() {
      System.out.println("Hi");
    }
  });
}

For some reason, the aspect also catches that "do()" method, even though it is does not inherit from MyInterface.

How should I fix my aspect definition?

Body:
Instead of "within" use the "this" pointcut:

@Around("this(x.y.z.MyInterface+) && execution(public * *(..))")

Basically "this" matches joinpoints where this, the current object reference at the time, is an instance of MyInterface. Anonymous classes not implementing your interface will no longer match.

JavaWorld has a nice article on it:
http://www.javaworld.com/article/2074048/core-java/i-want-my-aop---part-2.html?page=2


问:
How to get GoogleApiClient in Xamarin?
I want to implement something like this in my Android application that I'm developing in Xamarin but can not find a namespace in which the GoogleApiClient is. Can anybody help?

答: It should be noted that the command "Install-Package Xamarin.GooglePlayServices.Location" also works for updating the Xamarin.GooglePlayServices. It will always fail if you try to use the UI to update the components.</p>

Title: How to get GoogleApiClient in Xamarin?


问:
Nulleable parameter using route Data Annotations
I send parameters from JS as:

```<code>apiService.post("../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo + "/" + $scope.selected.ID
</code>```

and I receive into controller like:

```<code>[Route("UpdateCatalogoRegistro/{Codigo}/{Nombre}/{ID}/{Padre}/{scopeSelected?}")]
public HttpResponseMessage UpdateCatalogoRegistro(HttpRequestMessage request, string Codigo, string Nombre, int ID, string Padre, int? scopeSelected)
</code>```

As you can see I want to get nulleable scopeSelected. If I send all parameters into with postman as:

http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/2

it returns a value but If I delete last parameter as:

http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/

it throw me:

"Message": "No HTTP resource was found that matches the request URI
  'http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/'.",
          "MessageDetail": "No action was found on the controller 'CatalogoRegistro' that matches the request."

It doesn´t found route. Why it dont detect nullable parameter? can anyone help me?

答:
It is because of the slash / at the end of the URL. The routing table does not know how to handle that segment.

Construct the URL accordingly when sending the request

```<code>var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
if ($scope.selected.ID) { // or how ever you check for null
    url = url + "/" + $scope.selected.ID
}
apiService.post(url);
</code>```

It is either that our check that the URL does not end with a trailing / before making the request and remove it.

```<code>var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo + "/" + $scope.selected.ID;
apiService.post(url.trimRight("/"));
</code>```

in the above case trimRight("/") is used to trim any trailing slashes on the end of the URL.

Body:
I send parameters from JS as:

apiService.post("../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo + "/" + $scope.selected.ID

and I receive into controller like:

[Route("UpdateCatalogoRegistro/{Codigo}/{Nombre}/{ID}/{Padre}/{scopeSelected?}")]
public HttpResponseMessage UpdateCatalogoRegistro(HttpRequestMessage request, string Codigo, string Nombre, int ID, string Padre, int? scopeSelected)

As you can see I want to get nulleable scopeSelected. If I send all parameters into with postman as:

http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/2

it returns a value but If I delete last parameter as:

http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/

it throw me:

"Message": "No HTTP resource was found that matches the request URI
  'http://localhost:55720/api/Catalogo/UpdateCatalogoRegistro/T60/T6000/4/MOD/'.",
          "MessageDetail": "No action was found on the controller 'CatalogoRegistro' that matches the request."

It doesn´t found route. Why it dont detect nullable parameter? can anyone help me?

Body:
It is because of the slash / at the end of the URL. The routing table does not know how to handle that segment.

Construct the URL accordingly when sending the request

var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
if ($scope.selected.ID) { // or how ever you check for null
    url = url + "/" + $scope.selected.ID
}
apiService.post(url);

It is either that our check that the URL does not end with a trailing / before making the request and remove it.

var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo + "/" + $scope.selected.ID;
apiService.post(url.trimRight("/"));

in the above case trimRight("/") is used to trim any trailing slashes on the end of the URL.


问:
Getting all open files for process results in errno 12 = Out of Memory
With the help of SO, I wrote an app that displays all open TCP/UDP connections in Swift.
In the next step, I would like to get the process that opened the connection (pretty much as lsof does).

Since lsof is open source, I could write the following code to get all the open files for a process:

Bridging-Header:

```<code>#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <mach/host_info.h>
#include <mach/task_info.h>
#include <mach/thread_info.h>
#include <mach/vm_region.h>
#include <libproc.h>

#include <sys/proc_info.h>
#include <sys/kdebug.h>
#include <sys/msgbuf.h>
</code>```

(I don't think every include is needed, but at least it compiles for now).

```<code>for app in NSWorkspace.shared().runningApplications
    {
        let pid = app.processIdentifier

        var tai = proc_taskallinfo()
        let size = MemoryLayout<proc_bsdinfo>.size
        var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
        let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

        if result <= 0
        {
            if errno == ENOMEM
            {
                Swift.print("Out of memory.")
            }
            Swift.print(errno)
            continue
        }

        var fid = proc_fdinfo()
        let fdInfoSize = MemoryLayout<proc_fdinfo>.size
        result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

        if result <= 0
        {
            Swift.print("Error. No Files?")
        }
        else
        {
            Swift.print("Files found.")
        }
    }
</code>```

The code was ported from C to Swift 3. The original C code looks like this:

```<code>int nb;
struct proc_taskallinfo tai;
...
nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai));
</code>```

When I run my code, I get the errno 12 (Out of memory). Why?

P.S. I know that the second proc_pidinfo will also fail because a pointer to an array of proc_fdinfo is returned and not a pointer to a single struct, but one step at a time. It's all about the errno 12.

答:
Here is the final code to get the TCP sockets. Unfortunately it is not possible to use the code in sandboxed apps:</p>

```<code>for app in NSWorkspace.shared().runningApplications {
    let pid = app.processIdentifier

    var tai = proc_taskallinfo()
    let size = MemoryLayout<proc_taskallinfo>.size
    var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
    let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

    if result <= 0 {
        continue
    }

    var fid = Array(repeating: proc_fdinfo(), count: Int(fileCount))
    let fdInfoSize = MemoryLayout<proc_fdinfo>.stride
    result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

    if result <= 0 {
        Swift.print("Error PROC_PIDLISTFDS.")
    }
    else {
        for i in 0.. < Int(result) / fdInfoSize {
            let fdp = fid[i]

            if fdp.proc_fdtype == UInt32(PROX_FDTYPE_SOCKET) {
                var si = socket_fdinfo()
                let sizeSi = MemoryLayout<socket_fdinfo>.size
                result = proc_pidfdinfo(pid, fdp.proc_fd, PROC_PIDFDSOCKETINFO, &si, Int32(sizeSi))

                if result <= 0 {
                    Swift.print("Error PROC_PIDFDSOCKETINFO: " + errno.description)
                }
                else {
                    if si.psi.soi_kind == Int32(SOCKINFO_TCP) {
                        Swift.print("TCP Socket")
                    }
                }
            }
        }
    }
}
</code>```

Body:
With the help of SO, I wrote an app that displays all open TCP/UDP connections in Swift.
In the next step, I would like to get the process that opened the connection (pretty much as lsof does).

Since lsof is open source, I could write the following code to get all the open files for a process:

Bridging-Header:

#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <mach/host_info.h>
#include <mach/task_info.h>
#include <mach/thread_info.h>
#include <mach/vm_region.h>
#include <libproc.h>

#include <sys/proc_info.h>
#include <sys/kdebug.h>
#include <sys/msgbuf.h>

(I don't think every include is needed, but at least it compiles for now).

for app in NSWorkspace.shared().runningApplications
    {
        let pid = app.processIdentifier

        var tai = proc_taskallinfo()
        let size = MemoryLayout<proc_bsdinfo>.size
        var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
        let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

        if result <= 0
        {
            if errno == ENOMEM
            {
                Swift.print("Out of memory.")
            }
            Swift.print(errno)
            continue
        }

        var fid = proc_fdinfo()
        let fdInfoSize = MemoryLayout<proc_fdinfo>.size
        result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

        if result <= 0
        {
            Swift.print("Error. No Files?")
        }
        else
        {
            Swift.print("Files found.")
        }
    }

The code was ported from C to Swift 3. The original C code looks like this:

int nb;
struct proc_taskallinfo tai;
...
nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai));

When I run my code, I get the errno 12 (Out of memory). Why?

P.S. I know that the second proc_pidinfo will also fail because a pointer to an array of proc_fdinfo is returned and not a pointer to a single struct, but one step at a time. It's all about the errno 12.

Body:
Here is the final code to get the TCP sockets. Unfortunately it is not possible to use the code in sandboxed apps:

for app in NSWorkspace.shared().runningApplications {
    let pid = app.processIdentifier

    var tai = proc_taskallinfo()
    let size = MemoryLayout<proc_taskallinfo>.size
    var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
    let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

    if result <= 0 {
        continue
    }

    var fid = Array(repeating: proc_fdinfo(), count: Int(fileCount))
    let fdInfoSize = MemoryLayout<proc_fdinfo>.stride
    result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

    if result <= 0 {
        Swift.print("Error PROC_PIDLISTFDS.")
    }
    else {
        for i in 0.. < Int(result) / fdInfoSize {
            let fdp = fid[i]

            if fdp.proc_fdtype == UInt32(PROX_FDTYPE_SOCKET) {
                var si = socket_fdinfo()
                let sizeSi = MemoryLayout<socket_fdinfo>.size
                result = proc_pidfdinfo(pid, fdp.proc_fd, PROC_PIDFDSOCKETINFO, &si, Int32(sizeSi))

                if result <= 0 {
                    Swift.print("Error PROC_PIDFDSOCKETINFO: " + errno.description)
                }
                else {
                    if si.psi.soi_kind == Int32(SOCKINFO_TCP) {
                        Swift.print("TCP Socket")
                    }
                }
            }
        }
    }
}


问:
fetchedResultsController returns nil
Trying to create simple application to display data from Core Data to Table View. The code builds successfully - every time it loads it adds new entry, currently more than 20 - but then it crashes when trying to build the table.

Here I have ViewController:

```<code>import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate  {

     @IBOutlet weak var habitTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let habitClassName:String = String(describing: Habits.self)

        let habit:Habits = NSEntityDescription.insertNewObject(forEntityName: habitClassName, into: DatabaseController.getContext()) as! Habits

        habit.habitsPic = ":("
        habit.positive = false
        habit.theHabit = "do bad"

        DatabaseController.saveContext()

        let fetchRequest:NSFetchRequest<Habits> = Habits.fetchRequest()

        do{
            let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
            print("number of results: \(searchResults.count)")

        }
        catch{
            print("Error \(error)")
        }

    }

    //CONSTRUCT TABLE VIEW
    func numberOfSectionsInTableView(tableView: UITableView)-> Int {
        return fetchedResultsController.sections!.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let sections = fetchedResultsController.sections else {
            fatalError("No sections in fetchedResultsController")
        }
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)-> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "positiveCell", for: indexPath as IndexPath)
        let habit = fetchedResultsController.object(at: indexPath as IndexPath) as! Habits

        cell.textLabel?.text = habit.theHabit
        cell.detailTextLabel?.text = habit.habitsPic

        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //FOR DISPLAYING DATA IN TABLE
    var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!

    func initializeFetchedResultsController() {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Habits")
        let departmentSort = NSSortDescriptor(key: "theHabit", ascending: true)
        let lastNameSort = NSSortDescriptor(key: "positive", ascending: true)
        request.sortDescriptors = [departmentSort, lastNameSort]

        let moc = DatabaseController.getContext()
        fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController.delegate = (self as! NSFetchedResultsControllerDelegate)

        do {
            try fetchedResultsController.performFetch()
        } catch {
            fatalError("Failed to initialize FetchedResultsController: \(error)")
        }
    }

}
</code>```

And DatabaseController:

```<code>import Foundation
import CoreData

class DatabaseController {
    private init(){

    }

    class func getContext() -> NSManagedObjectContext{
        return DatabaseController.persistentContainer.viewContext
    }

    let container = NSPersistentContainer(name: "ada")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

class func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
}
</code>```

It will not build the table view, because the fetchedResultsController returns nil. I assume it is problem with "moc" variable, but what?

EDIT

error:
fatal error: unexpectedly found nil while unwrapping an Optional value

line:
guard let sections = fetchedResultsController.sections else {

答:
You declare your fetched results controller as an implicitly unwrapped optional:

```<code>var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!
</code>```

Its initial value is nil.

You also have a method called initializeFetchedResultsController that assigns a value to this property, but you never call that method.  In a comment you said that you're calling it in this code:

```<code>guard let sections = fetchedResultsController.sections else {
    fatalError("No sections in fetchedResultsController")
}
</code>```

But that code never mentions the initializeFetchedResultsController method, and so it never calls that method.

You have an optional variable but you never assign it a value. So it never gets a value. So it's nil. This isn't a Core Data question, it's basic Swift. Properties don't get values unless you give them values, and you are not doing that.

Title: fetchedResultsController returns nil

Body:
Trying to create simple application to display data from Core Data to Table View. The code builds successfully - every time it loads it adds new entry, currently more than 20 - but then it crashes when trying to build the table.

Here I have ViewController:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate  {

     @IBOutlet weak var habitTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let habitClassName:String = String(describing: Habits.self)

        let habit:Habits = NSEntityDescription.insertNewObject(forEntityName: habitClassName, into: DatabaseController.getContext()) as! Habits

        habit.habitsPic = ":("
        habit.positive = false
        habit.theHabit = "do bad"

        DatabaseController.saveContext()

        let fetchRequest:NSFetchRequest<Habits> = Habits.fetchRequest()

        do{
            let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
            print("number of results: \(searchResults.count)")

        }
        catch{
            print("Error \(error)")
        }

    }

    //CONSTRUCT TABLE VIEW
    func numberOfSectionsInTableView(tableView: UITableView)-> Int {
        return fetchedResultsController.sections!.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let sections = fetchedResultsController.sections else {
            fatalError("No sections in fetchedResultsController")
        }
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)-> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "positiveCell", for: indexPath as IndexPath)
        let habit = fetchedResultsController.object(at: indexPath as IndexPath) as! Habits

        cell.textLabel?.text = habit.theHabit
        cell.detailTextLabel?.text = habit.habitsPic

        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //FOR DISPLAYING DATA IN TABLE
    var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!

    func initializeFetchedResultsController() {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Habits")
        let departmentSort = NSSortDescriptor(key: "theHabit", ascending: true)
        let lastNameSort = NSSortDescriptor(key: "positive", ascending: true)
        request.sortDescriptors = [departmentSort, lastNameSort]

        let moc = DatabaseController.getContext()
        fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController.delegate = (self as! NSFetchedResultsControllerDelegate)

        do {
            try fetchedResultsController.performFetch()
        } catch {
            fatalError("Failed to initialize FetchedResultsController: \(error)")
        }
    }

}

And DatabaseController:

import Foundation
import CoreData

class DatabaseController {
    private init(){

    }

    class func getContext() -> NSManagedObjectContext{
        return DatabaseController.persistentContainer.viewContext
    }

    let container = NSPersistentContainer(name: "ada")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

class func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
}

It will not build the table view, because the fetchedResultsController returns nil. I assume it is problem with "moc" variable, but what?

EDIT

error:
fatal error: unexpectedly found nil while unwrapping an Optional value

line:
guard let sections = fetchedResultsController.sections else {

Body:
You declare your fetched results controller as an implicitly unwrapped optional:

var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!

Its initial value is nil.

You also have a method called initializeFetchedResultsController that assigns a value to this property, but you never call that method.  In a comment you said that you're calling it in this code:

guard let sections = fetchedResultsController.sections else {
    fatalError("No sections in fetchedResultsController")
}

But that code never mentions the initializeFetchedResultsController method, and so it never calls that method.

You have an optional variable but you never assign it a value. So it never gets a value. So it's nil. This isn't a Core Data question, it's basic Swift. Properties don't get values unless you give them values, and you are not doing that.


问:
Tawk.to widget issue on mobile (AngularJS)
So basically, I'm using tawk.to as the free chat service for my client's application built on AngularJS
The issue is that whenever I open the chat widget on mobile device and reopen it after closing it once, it closes automatically, thereby making it impossible for users to chat.

As per the official site's instruction, all we had to do was paste a script at the bottom, like so:

var $_Tawk_API={},$_Tawk_LoadStart=new Date(); (function(){ var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0]; s1.async=true; s1.src='https://embed.tawk.to/57e650264a427d157423018b/default'; s1.charset='UTF-8'; s1.setAttribute('crossorigin','*'); s0.parentNode.insertBefore(s1,s0); })();

Upon further digging, I found that the issue was due to the hash prefixing which adds a # on the address bar, and whenever we click on the "Start Chat" button, it adds another # to the address, so in order to escape that it converts it into %23 and therefore the chat widget closes.

I've tried looking for the solution everywhere to no avail.

Can anyone help me out with this bugger ?

答:
Place this after the widget loads :

Tawk_API = Tawk_API || {};
Tawk_API.disableMobileBackHistory = true;

Here is a working example :

http://rd.tawk.to/mobile-maximize/

Cheers,

Robert


问:
Maintaining environment state between subprocess.Popen commands?
I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.

The nodes are running on EC2.

One of the projects depends on a from source version of a 3rd party application.

Specifically:

```<code>cd /tmp
wget s3://.../tools/x264_20_12_2010.zip
unzip x264_20_12_2010.zip
cd x264_20_12_2010
./configure
make
checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default
</code>```

Currently I'm doing this with boto's ShellCommand (which uses subprocess.Popen internally), this looks something like this:

```<code>def deploy():
        ShellCommand("apt-get remove ffmpeg x264 libx264-dev")
        ShellCommand("apt-get update")
        ShellCommand("apt-get install -y build-essential checkinstall yasm texi2html libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support libfaac-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev zlib1g-dev")

        ShellCommand("cd /tmp")
        s3cmd_sync("s3://.../tools/x264_20_12_2010.zip", "/tmp/x264_20_12_2010.zip")
        ShellCommand("unzip x264_20_12_2010.zip")
        ShellCommand("cd x264_20_12_2010")
        ShellCommand("./configure")
        ShellCommand("make")
        ShellCommand(r'checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default')
</code>```

Sadly this fails, because cd /tmp applies to the subprocess, meaning that once I return the the father process and issue the second ShellCommand the exeenv is inherited from the father, which leans me to think that I need some execution framework for shell commands which will apply all commands in the same sub process without loosing context.

What is the recommend solution to this problem? Please note that loggings of the command line executed app is very important (how can you debug without it?), which is why I like ShellCommand... (see boto logging if interested).

Thank you,

Maxim.

答:
Think of os.chdir("DIRECTORY") instead of Popen("cd DIRECTORY")

Maybe it's best here not to execute a new shell for each command: Just write one multi-line shell skript

deploy_commands = """apt-get foo
apt-get bar
cd baz ; boo bat"""

end execute via Popen(deploy_commands, shell=True).

But please read the security warning in the Popen documentation about not escaping untrusted parameters.

Body:
I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.

The nodes are running on EC2.

One of the projects depends on a from source version of a 3rd party application.

Specifically:

cd /tmp
wget s3://.../tools/x264_20_12_2010.zip
unzip x264_20_12_2010.zip
cd x264_20_12_2010
./configure
make
checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default

Currently I'm doing this with boto's ShellCommand (which uses subprocess.Popen internally), this looks something like this:

def deploy():
        ShellCommand("apt-get remove ffmpeg x264 libx264-dev")
        ShellCommand("apt-get update")
        ShellCommand("apt-get install -y build-essential checkinstall yasm texi2html libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support libfaac-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev zlib1g-dev")

        ShellCommand("cd /tmp")
        s3cmd_sync("s3://.../tools/x264_20_12_2010.zip", "/tmp/x264_20_12_2010.zip")
        ShellCommand("unzip x264_20_12_2010.zip")
        ShellCommand("cd x264_20_12_2010")
        ShellCommand("./configure")
        ShellCommand("make")
        ShellCommand(r'checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default')

Sadly this fails, because cd /tmp applies to the subprocess, meaning that once I return the the father process and issue the second ShellCommand the exeenv is inherited from the father, which leans me to think that I need some execution framework for shell commands which will apply all commands in the same sub process without loosing context.

What is the recommend solution to this problem? Please note that loggings of the command line executed app is very important (how can you debug without it?), which is why I like ShellCommand... (see boto logging if interested).

Thank you,

Maxim.


问:
How do I get all third party cookies with Scrapy or other easier methods?
I wish to use Python Scrapy to get all cookies on a domain, including third party cookies such as embedded videos or Google Calender.

I first used Scrapy to check "Set-Cookie" Field in HTTP headers, but I was only able to get first party cookies.

Then I tried Scrapy+Selenium+Chromedriver to load all js to get all cookies. However, this is very slow. I found this post and tried PhantomJS: How to get 3rd party cookies? I did the same thing, but I got an empty cookie.txt file.

I am wondering whether there is any easy way to get all cookies from a website, or how I should fix this?

Thanks in advance.

答:
Most python scraping tools are never going to do a complete job of getting cookies as it is unable to execute javascript and many (perhaps most) third-party cookies are set directly or indirectly by scripts.

You therefore need to use some sort of browser automation which you seem to be doing.  In regards to phantomjs, it most certainly does return all cookies via its API, if you are having trouble keep trying.  As far as selenium+chromedriver goes, it will only return first-party cookies.  PhantomJS is actually the best option strictly for gathering cookies.  Another option is to create fresh profiles for chrome/firefox in selenium, find the temporary files path, and opening the cookie database directly with sqlite.

You can also try a tool like webxray which is designed to capture third-party requests and cookies: https://github.com/timlib/webXray (disclosure: I wrote it).