text:
Q: One or more errors occurred while processing template 'Entity.tt' Am using Microsoft Visual Studio Tools for Applications 2015, I have installed EF Power Tools as in Installing EF Power Tools into VS2015
After that I was trying to run EF Reverse engineering code first approach, but I was getting the issue and resolved from Visual Studio 2015 Update 2 breaks EF reverse code engineer vsix
When I have done this I am getting an issues now as One or more errors occurred while processing template 'Entity.tt'.
For this I have followed One or more errors occurred while processing template 'Entity.tt'.
And I have even added
Trusted_Connection=False;Persist Security Info=True

In web.config and changed Persist Security Info=True in advanced tab, but still the issues isn't resolved am getting the same issue as in title.
Need help/suggestions.
Detiled error from visual studio output window.
One or more errors occurred while processing template 'Entity.tt'.
error : An exception was thrown while trying to compile the transformation code. The following Exception was thrown:
System.ArgumentException: Empty path name is not legal.
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at Roslyn.Utilities.FileUtilities.OpenFileStream(String path)
   at Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(String path, MetadataReferenceProperties properties, DocumentationProvider documentation)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.<>c.<.ctor>b__15_0(String x)
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__66`1.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__66`1.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.ImmutableArrayExtensions.AsImmutableOrEmpty[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.Compilation.ValidateReferences[T](IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.WithReferences(IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CommonWithReferences(IEnumerable`1 newReferences)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.PrepareNewCompilation()
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.Compile()
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.Compile(String source, String inputFile, IEnumerable`1 references, Boolean debug, SupportedLanguage language, String compilerOptions)

Need help/suggestions

A: My workaround for this is the following:

*

*Right click on the project, open Properties.

*Change the Target Framework to .NET Framework 4

*Rerun the Reverse Engineer Code First script.

*Reopen project properties, change Target Framework back to what you want it to be


text:
Q: Error:Execution failed for task ':app:kaptDemoTestingDebugKotlin' I am using kotlin for the very first time and trying to run databinding in it.
I keep getting this error:

Error:Execution failed for task ':app:kaptDebugKotlin'.

Internal compiler error. See log for more details

I have my build.gradle (Module: app)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-kapt'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "in.pmock.practicemock"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    flavorDimensions "default"

    productFlavors {

        finalProduction {
            dimension "default"
            applicationId "in.pmock.practicemock"
            resValue "string", "app_name", "Practice Mock"
        }

        demoProduction {
            dimension "default"
            applicationId "in.pmock.practicemock.demoproduction"
            resValue "string", "app_name", "Practice Mock Demo P"
        }

        demoTesting {
            dimension "default"
            applicationId "in.pmock.practicemock.demotesting"
            resValue "string", "app_name", "Practice Mock Demo T"
        }

        mock {
            dimension "default"
            applicationId "in.pmock.practicemock.mock"
            resValue "string", "app_name", "Practice Mock Mock"
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    kapt "com.android.databinding:compiler:3.0.0"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

I have my build.gradle (Module: Project)
buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle Stack Trace-
* What went wrong:
Execution failed for task ':app:kaptDemoTestingDebugKotlin'.
> Internal compiler error. See log for more details

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDemoTestingDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.GradleException: Internal compiler error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:9)
    at org.jetbrains.kotlin.gradle.internal.KaptTask.compile(KaptTask.kt:78)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:731)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 27 more

* Get more help at https://help.gradle.org

BUILD FAILED in 6s

Thanks in advance for helping.

A: In your project,

*

*Delete {root}/.gradle, {root}/app/build & {root}/build folders from your project's root directory

*Run Invalidate Caches / Restart

*Sync your project again after Android Studio restarts

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with adobe-reader I cannot open the preferences dialog in adobe-reader. I want to uninstall it and get rid of all the configurations. How can I do that? I installed from the binary that was provided in adobe's website. I looked for UNINSTALL file, but I could not find it. I also tried apt-get remove adobe-reader, but that did not help either.

A: the correct file should be
sudo apt-get remove adobereader-enu

otherwise use synaptic and search for adobe
ref

A: This is what worked for me:
Open the terminal
cd /opt/Adobe/Reader9/bin
sudo ./UNINSTALL


text:
Q: How to iterate Data from two columns into single select box in ASP.Net MVC Currently I am doing it in old fashioned way like without using any model.
I want to get price and Name columns from same table and show the Name in Selectbox options and whenever user selects an option its price should come into a label on the side. It is loading Names but dont know how to get the price.
Any help is highly appreciated.
Controller Code:
        string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
        SqlConnection conn = new SqlConnection(ConnectionString);

        List<string> listId = new List<string>();
        List<string> listName = new List<string>();
        List<string> listPrice = new List<string>();

        conn.Open();
        string query = "select id,pkgName,price from packages";
        SqlCommand cmdss = new SqlCommand(query, conn);
        SqlDataReader dr = cmdss.ExecuteReader();
        while (dr.Read())
        {
            listId.Add(dr[0].ToString());
            listName.Add(dr[1].ToString());
            listPrice.Add(dr[2].ToString());

        }

        conn.Close();

        var ListNameArray = listName.ToArray();
        ViewBag.ListNameArray = ListNameArray;

        var ListPriceArray= listPrice.ToArray();
        ViewBag.ListPriceArray = ListPriceArray;

        return View();

View Code:
<select>

         @foreach (string item in ViewBag.ListNameArray)
         {
           <option>@item</option>
         }

</select>

A: You should create a class to represent each package record.
public class Package
{
    public int Id { set; get; }
    public string Name { set; get; }
    public decimal Price { set; get; }
}

Now when you read the table, create a list of this class and add an object to this list for each record.
var list=new List<Package>();
using(SqlDataReader dr = cmdss.ExecuteReader())
{
   while (dr.Read())
   {
        var p = new Package();
        p.Id=reader.GetInt32(reader.GetOrdinal("Id"));
        p.Name=reader.GetString(reader.GetOrdinal("pkgName"));
        p.Price=reader.GetDecimal(reader.GetOrdinal("Price"));
        list.Add(p);
   }
}

Assuming Id is of type Int an Price is of decimal type.
So now create a view model for your view
public class PackageVm
{
  public List<Package> Packages { set;get;}
  public int SelectedPackage { set;get;}
}

Now in the GET action, create an object of this, Load the Packages property to the list and send it to the view.
public ActionResult Create()
{
  var vm=new PackageVm();
  vm.Packages = GetPackages();
  return View(vm);
}

Assuming GetPackages method returns the list of Package ( the prev method).
Now in your view, which is strongly typed to your PackageVm class, Use the Html.DropDownListFor helper method to render the dropdown. Also We will store this list of Packages to a javascript array which we will use later. When user changes the dropdown, read the selected item value ( Id) and loop through the packages array and compare the Id's. If it is matching, get the Price property of that item and show it in the label.
@model PackageVm
@using(Html.BeginForm())
{
  @Html.DropDownListFor(s=>s.SelectedPackage,new SelectList(Model.Packages,"Id","Name"))
  <label id="price">Test</label>
  <input type="submit" />
}
@section Scripts
{
   $(function() {

     var packages = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Packages));
     $("#SelectedState").change(function() {
            var val = $(this).val();
            $.each(packages, function(a, b) {
                if (b.Id == val) {
                    $("#price").html(b.Price);
                }
            });
     });
   });
 }


text:
Q: ContextMenu based on object binding wpf So I have a list view that displays post items (Delivery date, type, tracking number etc) and I have a context menu set up that either opens up the tracking website or copies the tracking number to the clipboard.
What I want is for the contextmenu only to appear for listitems that have a tracking number. I've got the idea of changing the visibility of the contextmenu but it's the binding to the tracking number I'm having the trouble with.
<ContextMenu x:Key="MyElementMenu">
    <MenuItem Header="Track Item" Click="MenuItem_Click"></MenuItem>
    <MenuItem Header="Copy to Clipboard" Click="MenuItem_CopyToClipboard"></MenuItem>
</ContextMenu>

<!--Sets a context menu for each ListBoxItem in the current ListBox-->
<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
</Style>

This is what I have currently.

A: That seems like a case for a trigger:
<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
    <Style.Triggers>
        <!--
        Maybe the tracking number property is called something else, maybe it's 0
        instead of null when absent. You didn't say.
        -->
        <DataTrigger Binding="{Binding TrackingNumber}" Value="{x:Null}">
            <Setter Property="ContextMenu" Value="{x:Null}"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

A: <MyControl.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</MyControl.Resources>

<!--Sets a context menu for each ListBoxItem in the current ListBox-->
<Style TargetType="{x:Type ListViewItem}">
  <Setter Property="ContextMenu">
    <Setter.Value>
      <ContextMenu IsEnabled="{Binding HasTrackingNumber}" Visibility="{Binding HasTrackingNumber, Converter={StaticResource BoolToVis}">
        <MenuItem Header="Track Item" Click="MenuItem_Click"></MenuItem>
        <MenuItem Header="Copy to Clipboard" Click="MenuItem_CopyToClipboard"></MenuItem>
      </ContextMenu>
    </Setter.Value>
  </Setter>
</Style>

This should give you what you need. Not sure if you use the ContextMenu elsewhere, but if you dont you can always just set it in the style of the ListViewItem Style. Then you dont need to have it referenced from elsewhere. Either way its more about adding the Binding from the item. In your ListItem Viewmodel you could add something like:
public bool HasTrackingNumber => TrackingNumber == 0 || TrackingNumber == null;
(I dont know what type your tracking number is so you can do your own logic checks to know if it "has" a valid tracking number)


text:
Q: is it possible to use scrollable (jQuery tools) with just one item? I am trying to work out if it is possible to use scrollable, part of jQuery tools, to scroll through 1 item/div vertically.  At the moment I can only get it working with at least two DIVS.  It seems to be set up as an image gallery scroller, but I would like to use it to scroll a playlist vertically and there would be one DIV for the playlist.
If it does have to have at least two DIVs I was wondering if I could set the second DIV to have a height of 1px, or to be hidden?  At the moment it seems like all the DIVs have to have the same height.
Thanks,
Nick.

A: It really depends on which plugin you are using. For example jcarousel ( http://sorgalla.com/jcarousel/ ) you can do it via customizing the options. The options are available here: http://sorgalla.com/projects/jcarousel/

A: Nick, I think what you are asking is how to get the scroll animation to play automatically for one item? If so, I believe you need to set the circular (i.e. loop) parameter to true.
e.g. circular: true

Something like this:
$(document).ready(function() {
    $.easing.custom = function (x, t, b, c, d) {
        var s = 1.10158;
        if ((t/=d/2) < 1)
            return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        return c/2*((t-=2)*t*(((s*=(1.925))+1)*t + s) + 2) + b;
    }

    var root =
        $(".scrollable").scrollable({
            easing: 'custom',
            speed: 800,
            circular: true
        }).autoscroll(5400, {
            autoplay: true
        });

    window.api = root.data("scrollable");
});


text:
Q: plotting two yaxis with different markers and colors If I have two y vectors and one x vector:
y1 = [0.1,0.2,0.5,0.6];
y2 = [0.3,0.4,0.7,0.8];
x = 1:length(y1);

How can I plot all of the information on the same plot using different markers and different colors. I have tried the following:
cols = {'k','r','b',[0,0.5,0]};
markers = {'s','o','d','v'};

for i = 1:4;
    plot(x(i),y1(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor','w');
    hold on
end
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'),...
       'YAxisLocation','right','XColor','k','YColor','k');
linkaxes([ax1,ax2],'x');
for i = 1:4;
    plot(x(i),y2(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor',cols{i},'Parent',ax2);
    hold on;
end

But this seems to overwrite the first plot. My aim here it to draw the first four points (y1) with the markers and colors defined, but with the maker faces in white. I then hope to include on the same figure, a second yaxis (on the right) with the values from y2, but this time with the marker faces colored according to 'cols'. How can I do this?
Addition:
When I use plotyy
for i = 1:4;
    [ax,h1,h2] = plotyy(x(i),y1(i),x(i),y2(i));
    hold on
    set(h1,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor',cols{i});
    set(h2,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor','w');
    set(ax,{'ycolor'},{'k';'k'},{'xcolor'},{'k';'k'});
end

The xaxis values do not show up correctly, where although they are identical, they do not line up on the plot.

A: You can use the embedded function of Matlab , plotyy
plotyy(X1,Y1,X2,Y2) plots X1 versus Y1 with y-axis labeling on the left and plots X2 versus Y2 with y-axis labeling on the right.
check more options here.
This example graphs two mathematical functions using plot as the plotting function. The two y-axes enable you to display both sets of data on one graph even though relative values of the data are quite different.
figure
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');

If you are trying with 'hold on' this solves the a-synchronized axes:
set(ax, 'XLim', [min(xaxis) max(xaxis)]);
set(ax(2),'XTick',[]);

A: The problem is that the background color on the overlayed plot is set to white (and opaqueness to max) so that everything underneath is invisible. Substituting the ax2 = ... statement with
ax2 = axes('Position',get(ax1,'Position'),...
'YAxisLocation','right','XColor','k','YColor','k','color','none');

should fix things.


text:
Q: MS Lists links displayed in the Comments Within MS Lists (Office 365), is there a way to display a link within the Comments? Currently When I add a URL, it is displayed as text only and not as link.

I know I can create a Comments column within the List itself, and apply the to Rich Text formatting on it, however, I wanted to try make use of the inbuilt comments function itself to able to add links to it.


text:
Q: calculate statistics for every column and add it to empty Dataframe my idea is to get statistics like mean,median,var,min,max from every column of a dataframe and save it to a new empty dataframe. My dataframe looks like this:
    A   B   C   D
0   3   4   2   1
1   4   3   3   1
2   4   2   3   0

and my new dataframe should look like this:
A_mean | A_median | A_var | A_max | A_min | B_mean | B_median | B_var | B_max  |B_min | ...
 1          2         1       1       0      1           1        1       2       1     ...

i can't use df.describe() because it doesn't have var or median.
My idea of implementing this:
row=pd.DataFrame()
for column in df:
        row = row.append({column + '_mean':df_test[column].mean()}, ignore_index=True)
        row = row.append({column + '_median':df_test[column].median()}, ignore_index=True)
        row = row.append({column + '_var':df_test[column].var()}, ignore_index=True)
        row = row.append({column + '_max':df_test[column].max()}, ignore_index=True)
        row = row.append({column + '_min':df_test[column].min()}, ignore_index=True)

but then i get

my goal is to have this in one row not in 10 different rows. How could I change my code?

A: If possible change format use agg with functions in list:
df = df.agg(['mean','median', 'var','max','min'])
print (df)
               A    B         C         D
mean    3.666667  3.0  2.666667  0.666667
median  4.000000  3.0  3.000000  1.000000
var     0.333333  1.0  0.333333  0.333333
max     4.000000  4.0  3.000000  1.000000
min     3.000000  2.0  2.000000  0.000000

Or add unstack with to_frame and transpose, last flatten columns names for one row DataFrame:
df = df.agg(['mean','median', 'var','max','min']).unstack().to_frame().T
df.columns = df.columns.map('_'.join)
print (df)
     A_mean  A_median     A_var  A_max  A_min  B_mean  B_median  B_var  B_max  \
0  3.666667       4.0  0.333333    4.0    3.0     3.0       3.0    1.0    4.0

   B_min    C_mean  C_median     C_var  C_max  C_min    D_mean  D_median  \
0    2.0  2.666667       3.0  0.333333    3.0    2.0  0.666667       1.0

      D_var  D_max  D_min
0  0.333333    1.0    0.0


text:
Q: Atiyah-Hirzebruch spectral sequence for twisted K-theory for infinite-dimensional CW-complexes I'm writing a thesis that runs an AHSS for twisted K-theory over an Eilenberg-MacLane space, namely an infinite-dimensional CW-complex.
In Atiyahs works Twisted K-Theory and Twisted K-Theory and cohomology, I could not find any reference on how the twisted AHSS would behave for infinite-dimensional CW-complexes. Neither could I find any reference in his foundational work Vector bundles and homogeneous spaces, where Atiyah introduces the untwisted version of the AHSS.
Is there any published material defining a twisted AHSS infinite-dimensional CW-complex? I do not need convergence of the sequence (that might be affected), only that the calculations of the successive pages work.
I've also tried theorem 15.7. of Switzers Algebraic Topology, but this theorem gives the sequence for generalized homology theories, not generalized cohomology theories, such as twisted K-Theory. At the moment, I'm trying to extract the information from Whitehead's Elements of Homotopy Theory, Theorem 3.6 of chapter XIII, but not with too much success.


text:
Q: Print double pointer to array - keeps crashing i have this small piece of code which i cant get to work.
I am kinda new and i just cant find a mistake i did. Thanks
int main (void)
{
    int **array;
    int i,j, m;

    scanf("%d", &m);

    array = malloc(sizeof(int) * (m*m));

    for (i = 0; i < m; i++)
    {
        for (j = 0; j < m; j++)
        {
            scanf("%d", &array[i][j]);
        }
    }

        for (i = 0; i < m; i++)
        {
            for (j = 0; j < m; j++)
            {
                printf("%d", array[i][j]);
            }
        }

    return 0;
}

A: What you are allocating is an one dimensional array of size m*m but you are using it as if you have allocated a jagged array where each row contains m elements.
You can allocate a bit different way than what you did
array = malloc(sizeof *array * m);
if( array == NULL)
{
   // error in malloc
}
for(size_t i =0; i<m; i++)
{
   array[i]=  malloc(sizeof *array[i] * m);
   if( array[i] == NULL)
   {
      // error

   }
}
...
for(size_t i = 0; i<m ; i++)
   free(array[i]);
free(array);

Alternatively you can put all the elements in a linear manner using i and j.
int *array;
...
for (i = 0; i < m; i++)
{
    for (j = 0; j < m; j++)
    {
        if( scanf("%d", &array[i*m+j]) != 1){
           // error in getting input.
        }
    }
}
...
free(array);

Same goes with printf also.
Also don't forget to free the memory you have allocated dynamically after you are done working with it.


text:
Q: extract specific rows of .tbl files in excel I have an excel file with the following links:

These links are connected to files with the following data:

I want the yellow part of the notepad file to be read into the .xlsx file yellow parts (the notepad is an opened version of the .tbl file). The dotted parts differ for each Version number. (This code is used as a check that the right discount curve is used). However, the discount_curve.tbl format is the only format the next programme used is able to handle. Therefore, it has the same name just in a different folder.
Is there a way excel/vba can read in every third line whilst the file read in depends on the folder link? I strongly prefer to have the whole process automated since there are many many version numbers. Furthermore, I do not want to change the file formatting, since I want the process to be as clean as possible.
Could someone help me out?
Kind regards.

A: Please, try the next function, if the necessary data to be extracted exists in a single file, at every three rows.. It will return a 2D array able to be dropped at once in the range you need:
Function extractThirdLine(filePath As String) As Variant
     Dim arrTxt, i As Long, arrFin, k As Long
     'read the file content in an array:
     arrTxt = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(filePath, 1).ReadAll, vbCrLf)
     ReDim arrFin(1 To Int(UBound(arrTxt) / 3) + 1, 1 To 1)
     For i = 2 To UBound(arrTxt) Step 3 'start from 2, because  arrTxt is 1D array
        k = k + 1
        arrFin(k, 1) = arrTxt(i) 'build the filal array containing the necessary rows
     Next i
     extractThirdLine = arrFin
End Function

Your picture does not show the rows and columns headers. So, supposing that the range you show us exists in columns "A:C" and you need to place the extracted data in column "D:D", please use the next way:
Sub testExtractThirdLine()
   Dim filePath As String, arrVal, el
   filePath = "your text file full name" 'please write here the correct file  name
   arrVal = extractThirdLine(filePath)
   Range("D1").Resize(UBound(arrVal), 1).value = arrVal
End Sub

If the range you show is not the one I supposed, you cam easily adapt Range("D1") to the immediately after the columns range and its row to be the first row of the range in discussion.
If something not clear enough, please do not hesitate to ask for clarifications.
Edited:
But if each third line can be found in a file, for each row, and the path to the respective file is obtained by concatenation of the three columns, the next function will do the job:
Function extractLine(filePath As String) As String
   extractLine = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(filePath, 1).ReadAll, vbCrLf)(2)
End Function

It can be called as:
Sub extractStrings()
 Dim i As Long, arr, arrFin, lastRow As Long

 lastRow = Range("A" & rows.count).End(xlUp).Row 'supposing that 'C:\' exists in A:A column
 arr = Range("A2:C" & lastRow).value
 ReDim arrFin(1 To UBound(arr), 1 To 1)

 For i = 1 To UBound(arr)
    arrFin(i, 1) = extractLine(arr(i, 1) & arr(i, 2) & arr(i, 3))
 Next i
 'drop the processed array content at once:
 Range("D2").Resize(UBound(arrFin), 1).value = arrFin
End Sub

A: Seems like you're looking for common I/O opearations i.e. reading file line by line.
Pretty good example was shown [here][1]
To reach your goal we need to add some if-conditions to extract every third line of your text files.
Modulo division will be a good helper.
For example we have 'i' as row number
then we just need to make an if condition looks smth like that:
If (i mod 3) = 0 Then ...

It means that we're looking for every 'i' which divided by 3 gives us a remainder of 0
This way our code will look something like this
Sub ReadFileLineByLine()
Dim my_file As Integer
Dim text_line As String
Dim file_name As String
Dim i As Integer

file_name = "C:\text_file.txt"

my_file = FreeFile()
Open file_name For Input As my_file

i = 1

While Not EOF(my_file)
    Line Input #my_file, text_line
    If (i mod 3) = 0 Then
        Cells(i, "A").Value = text_line
    End If
    i = i + 1
Wend

End Sub
[1]: https://excel.officetuts.net/vba/read-a-text-file/#:~:text=Reading%20a%20file%20line%20by%20line,-Let's%20read%20text&text=Open%20VBA%20Edit%20(Alt%20%2B%20F11,and%20insert%20the%20following%20code.&text=First%2C%20a%20new%20file%20is,places%20it%20inside%20a%20worksheet.

A: You can create a User function that will read the lines from the given file and return the third one.
Here is such a function (Disclaimer: there is no error management in this code it can probably be improved a lot)
Function Get3rdLine(filename As String)
    Dim f As Long
    f = FreeFile
    Open filename For Input As f
    Line Input #f, Get3rdLine ' just ignore this line
    Line Input #f, Get3rdLine ' and this one too
    Line Input #f, Get3rdLine ' and return this one
    Close #f
End Function

You can call it with the path of the file you want to read from:
=Get3rdLine(CONCATENATE(A1,B1,C1)) for example if your path is defined by cells A1, B1 and C1.


text:
Q: Native replication from Percona XtraDB Cluster to a standard stand-alone slave I'm replicating from one node of a three-member Percona XtraDB cluster to a separate slave, using regular MySQL replication.  The node is set to write binlog in ROW mode, with log_slave_updates=true specifically for this.  Replication seems to work fine.  Still I wonder, given that XtraDB is an extension of InnoDB which the slave is using, is there a risk of some updates not replicating?  Is it worth it to replicate into an XtraDB slave, and how would that need to be configured?  I want the native async replication to the slave as it is an analytics DB and the goal is to offload the production Percona cluster from analytics queries, so it should not be just a regular cluster member.

A: The binlog doesn't contain different structures when the storage engine is XtraDB vs InnoDB.
In the sense of interoperability, XtraDB is not an "extension" of InnoDB -- it's a fully-compatible replacement, that handles some internal operations differently but is still very much "InnoDB" wherever it is exposed outside the server core.
For what it's worth,  I've taken "datadir" -- including ibdata1 and the ibd files from a stopped MySQL server, put them on a MariaDB server (which also uses XtraDB instead if InnoDB) and had zero compatibility issues.
The only caveat that comes to mind is the same as any MySQL async replication setup: the slave must be running the same or newer version of MySQL as its master (which, by the way, can be any one of thr PXC machines).
The reason for this "slave version the same or newer" rule is that the binlog format is forward-extensible only: when new capabilities are added to the binlog format, a newer master cam break an older slave, since the slave may not always understand what it is reading from the binlog, and replication will hit a hard stop (not a soft fail).  A newer slave should never fail to understand what an older master writes to its binlog, since, officially, replication is supported across major releases (e.g., 5.1 to 5.5) but in practice, 5.1 to 5.6 also seems completely compatible.
The parallel minor version or newer, of MySQL Server, MariaDB, or -- seemingly the most foolproof -- Percona Server... should work fine as an async slave.
If you start out the slave with Identical data, and you replicate every table and schema, missing transactions should never happen. Don't even try to filter what replicates and try to replicate a subserlt of your schemata/tables unless and until you really understand the issues this can encounter.  Replicating everything is the default behavior.
Yes... it is very much worth it to set up async slaves for reporting.  The cluster members should already have the config they need for this to work (othet than the user account the slave will use to connect).


text:
Q: Moving entire folder and all its contents to another folder Just need a batch script that will move one folder and all its contents into another folder.
Essentially this
C:\Folder1 to C:\Folder2\Folder 1

A: You can use windows native command:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2

You can use move /?
call for more details.
So, in you case , the command would be:
move C:\Folder1 C:\Folder2\

If Folder2 doesn't exist, Folder1 will be renamed Folder2.


text: Q: ASP.NET manage Message Box position with multiple display screens I have built a web application for users who normally use 2 display monitors. When the application browser is moved to the secondary screen, all message boxes continue to be displayed on the primary screen. Is there a way in ASP.NET to "tie" the message box to the display screen where the browser is currently open? I am using ASP.NET 4.5.1 with VB


text:
Q: tuple generics in array vs rest I'm trying to build a function that can accept an array of functions that are reduced. It does a lot of other stuff, but in essence it's a pipe. I want to use generics to infer the output of the function. For some reason it's not working unless I have the array be a rest parameter.
Extremely simplified example:
const pipe = <A, B, C, D>(items: [
  (a: A) => B,
  (b: B) => C,
  (c: C) => D
]): D => {
  return items.reduce((acc, fn) => fn(acc), {} as A & B & C) as D;
};

if I call this like so:
const result = pipe([
  (a: {}) => ({
    ...a,
    age: 4,
  }),
  (b) => ({
    ...b,
    color: 'blue',
  }),
  (c) => ({
    ...c,
    height: 100,
  }),
]);

I get the type { height: number }.
It seems to just lose its train of thought. Although parameter b is of type { age: number }, the parameter c is of type {}.
If I do exactly the same thing but with a rest parameter:
const pipe = <A, B, C, D>(...items: [
  (a: A) => B,
  (b: B) => C,
  (c: C) => D
]): D => {
  return items.reduce((acc, fn) => fn(acc), {} as A & B & C) as D;
};

I get the type { age: number, color: string, height: number } as expected.
Could anyone shed some light on this?


text:
Q: Tradingview Webhook got Triggered Multiple Times Issue The tradingview webhook will send multiple alert for the same alert to my webhook api, it results in sometimes my api have to process the same alert multiple times simultaneously as well. May I know is it the issue from TradingView? How can I solve it.
@app.route("/tradingview-to-webhook-order", methods=['POST'])
def tradingview_webhook():

    stop2sec = False
    if stop2sec:
        time.sleep(2)
        stop2sec = False

    stop2sec = True

This is what I have tried so far to try to add some gap between the alerts it recieve, at least they are not processing simultaneously which make it harder to debug...but it still failed.


text:
Q: How to enter whitespace only once after 4 characters in a string? Hey I have a input where the user enters his social security number. To make the input more readable I want to insert a whitespace after the first 4 characters of the string. The social security number itself is 10 numbers long. So the result should looke like: 1234 567890. I only found solutions where a whitespace every 4 characters is inserted but no example which is similar to this. Has someone an idea how to solve this?
<input type="text" maxlength="10" @keyup="insertWhitespace()"/>

A: You can do this with the use of Regular Expression + HTML DOM Element addEventListener().
Reference Website For "Regular Expression":  https://regexr.com/
With the help of a regular expression is a sequence of characters that specifies a search pattern in text or strings.

document.getElementById('example').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim();
});
<input id="example" maxlength="11" name="example" />

A: Here is the solution (Javascript) to your problem:
The code below reads the input value and remove alphabets and then replaces the digit value with the appropriate space character only once as expected after 4 digits.

function insertWhitespace() {
 document.getElementById('myElement').value = document.getElementById('myElement').value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim()
}
<input id="myElement" maxlength="11" onkeyup="insertWhitespace()" />

A: I think you should make your max length to 11 because white space also counts and try it with the following code
const ssn =  document.querySelector("selector");
ssn.addEventListener("keyup",(e) => {
  if(e.target.value.length === 4){
    ssn.value += " "
  }
})


text:
Q: Difference between buffer overflow attack on 64 vs 32 bit system I have both scripts in both c and Perl. The c code is:
#pragma check_stack(off)

#include <string.h>
#include <stdio.h>

void good_fn(){
    printf("GOOD CODE \n");
}

void mlc_fn(){
    printf("What is this I don understand what has happened !Probably buffer overflow attack and m hacked \n");
    system("shutdown -P now");
}

int main(int argc, char* argv[]){

    printf("Address of GOOD_CODE  = %p\n", good_fn);
    printf("Address of MLIC_CODE  = %p\n", mlc_fn);

    char data[10];

    //Callig function by pointer
    void (*dsrd_fn)();
    dsrd_fn = &good_fn;

    printf("SIZE : %d\n",sizeof(dsrd_fn));

    //try to overflow dsrd_fn here
    strcpy(data, argv[1]);
    //load content from file

    printf("Address of dsrd_fn    = %p\n", dsrd_fn);

    //call fn based on address pntr_fn
    dsrd_fn();

    printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n");
}

While the perl code is:
$arg = "AAAAAAAAAA"."\xC1\x84\x04\x08";
$cmd = "./bo_test ".$arg;

system($cmd);

after compiling and testing the bo_test, the output is:
student@EECS-337-VM:~/EECS 397/Part 2$ ./bo_test abcde
Address of GOOD_CODE  = 0x40060d
Address of MLIC_CODE  = 0x40061d
SIZE : 8
Address of dsrd_fn    = 0x40060d
GOOD CODE
My stack looks like:
0x7f00b3974000
0x7f00b37509e0
0xffffffffffffffff
0x7f00b37509e0
(nil)
0x7fff66218a68

When inserting the MLIC_ADDR into the perl script, the shell code buffer over-flow exploit with the perl script is not running on a 64 bit linux system, but it is running on a 32 bit linux system. Why would this be?


text:
Q: Can't use swagger ui in chrome and intellij idea due to CORS I can't send requests with swagger ui. Here's the error:
Access to fetch at 'http://localhost:8080/events' from origin 'https://editor.swagger.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The same in Intellij idea.
I've tried everything from here. In intellij I've checked "Allow unsigned requests" box in File | Settings | Build, Execution, Deployment | Debugger, but that also didn't work.
Does anybody know how to fix this CORS thing?


text:
Q: $.ajaxFileUpload used with canvas How can I use the $.ajaxFileUpload to upload the image rendered in a canvas so that it will be part of the HttpContext.Current.Request.Files?
Works fine with normal file upload:
$.ajaxFileUpload({
    url: "<%=AppRoot %>" + "upload",
    secureuri: false,
    fileElementId: "fld_image",
    dataType: "json",
    success: function (data, status) {
        if (typeof (data.error) != "undefined") {
            if (data.error) {
                //print error
                alert(data.error);
            }
        }
        else {
            $("#fld_image_hidden").remove();
            $(".heading").css("background-image", "url(<%= AppRoot %>" + data.Url + ")");
            var imagehidden = $("<input type=\"hidden\" id=\"fld_image_hidden\" name=\"fld_image_hidden\" value=\"" + data.Url + "|" + data.Name + "\" />");
            $("#Template_ID").after(imagehidden);
        }
        $("#fld_image").remove();
    },
    error: function (data, status, e) {
        alert(e);
    }});

But cannot get it to work using canvas:
var upload = $("<input type=\"file\" id=\"fld_image\" name=\"fld_image\" />");
upload.on("change", function () {
if ($(this)[0].files[0].size > 5000000) {
    alert("The file size may not exceed 5 MB.");
    return;
}

var filesToUpload = $(this)[0].files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function (e) {
    console.log(e);
    img.src = e.target.result;

    var canvas = $("#canvasImage")[0];

    var MAX_WIDTH = 500;
    var MAX_HEIGHT = 500;
    var width = img.width;
    var height = img.height;

    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);

    var dataurl = canvas.toDataURL();
    console.log(dataurl);
    //Do ajaxFileUpload here
    $.ajaxFileUpload({
        url: "<%=AppRoot %>" + "upload",
        secureuri: false,
        fileElementId: "canvasImage",
        dataType: "json",
        success: function (data, status) {
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
 });

The canvas is used to make the image smaller before uploading it to the server.

A: In the end I went this way, with guidance from this post, Canvas Upload:
var dataurl = canvas.toDataURL("image/png");
dataurl = dataurl.replace('data:image/png;base64,', '');

var ajax = new XMLHttpRequest();
ajax.open("POST", "<%=AppRoot %>" + "upload", false);
ajax.setRequestHeader("Content-Type", 'application/upload');
ajax.send(dataurl);

And on the server:
File.WriteAllBytes


text:
Q: CSS line-height attribute differences between mobile and desktop I'm having this weird situation when trying to create a text logo for my site, http://geekket.co/.
In desktop browsers (Firefox 51, Chrome 56, IE 11.576, Edge 38) the logo works perfectly, it looks pixel perfect as our design document specifies it.
But in mobile, the line-height property seems to work wrongly. Opera renders it fine, but Firefox and Chrome don't work as expected.
Mobile screenshots imgur album because I still have not enough reputation: http://imgur.com/a/Ij3cF
This is the CSS code dedicated to that particular section of the logo:
#LogoGeek {
  display: inline-block;
  background-color: rgb(90, 186, 71);
  font-family: "ForcedSquare";
  font-size: 90px;
  line-height: .72;
  height: .74em;
  padding: 0 .05em 0 .12em;
  vertical-align: middle;
}

"ForcedSquare" is a web font we added to the site.
I fiddled with the Remote Dev Tools ability in Mobile Chrome and found that if I changed line-height to .87, it works as expected, however, I feel that it is a ridiculous fix.
As far as I have read, it seems to be some sort of issue with the particular font. But then why there's no deal with all the different browsers of desktop and/or Opera Mobile, I have to idea.
Is there a better way to adjust it, or make it work properly in all browsers?
Thank you every one!

A: I know 2 solutions for this situation . First is that you can use paddings instead of line-height . Second is that you are using only one format of font . You must use all formats like TTF , OTF , WOFF . You can read more on w3school page . Link for W3schools.com


text:
Q: dependent select in react js i have 2 select elements
first one is:

<select>
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

Second one is:
<select>
   <option>1.1</option>
   <option>1.2</option>
   <option>1.3</option>
   <option>1.4</option>
   <option>2.1</option>
   <option>2.2</option>
   <option>2.3</option>
   <option>2.4</option>
   <option>2.5</option>
</select>

Second one will be hidden by default. when I select an option from first one and if that option got any sub item in second one then second one will show and only the options that are related to the first one selected option will be visible in second select element.
More details:
I selected 1 from first select element. then second select element will show and second select element will show only options that are related to 1, like, only 1.1, 1.2, 1.3, 1.4 options will be visible for second select option.
And if I select 3 from first select option then second select element will be hidden coz second select element got no items that are related to 3.
that's all. How can I achieve this using react hooks.

A: You can use useState in order to create a component variable.
[firstSelectAnswer, setFirstSelectAnswer] = useState('1');

This variable will hold the selected value from the first select box, for example by default 1; We will bind on change event on select or on click event on option in order to receive newly selected value.
firstSelectOptions = ["1", "2", "3"]
...
<select onChange={(e) => {setFirstSelectAnswer(e.target.value)}} value={firstSelectAnswer}>
   {
      firstSelectOptions.map((option) => <option key={option} value={option}>{option}</option>)
   }
</select>

We can use secondSelectAnswer variable in order to hold the answer from the second select box.
[secondSelectAnswer, setSecondSelectAnswer] = useState();
secondSelectOptions = [
   {key: "1", value: "1.1"},
   {key: "1", value: "1.2"},
   {key: "1", value: "1.3"},
   {key: "1", value: "1.4"},
   {key: "2", value: "2.1"},
   {key: "2", value: "2.2"},
   {key: "2", value: "2.3"},
   {key: "2", value: "2.4"},
   {key: "2", value: "2.5"}
]
...

We can use conditional rendering in order to show only required options:
{
   (firstSelectAnswer == '1' || firstSelectAnswer == '2') &&
      <select onChange={(e) => {setSecondSelectAnswer(e.target.value)}} value={secondSelectAnswer}>
        {
           secondSelectOptions
             .filter(option => {return option.required == firstSelectAnswer})
             .map((option) =>
                <option
                   key={option.value}
                   value={option.value}>
                 {option.value}
                </option>)
        }
      </select>
}

Variables firsSelectAnswer and secondSelectAnswer will hold appropriate values.


text:
Q: Use SSL only on one file in iis 7.5? I have a website hosted on an IIS 7.5/Server 2008 R2 Server. I want to use SSL and Basic Authentication on one file in the site. This used to be easy on sub-7 IIS versions, how can I do it on 7.5?

A: To enable, File Level Authentication in IIS 7 / 7.5

*

*Go the Web Site

*Click Content View

*Right click on the file e.g. iisstart.htm -> Switch to Features View

*Double click Authentication

*Now, select the Authentication Type you want to configure

Follow the same procedure for SSL Settings as well to enable SSL for just a single file.
Source: http://www.dotnetscraps.com/dotnetscraps/post/Did-you-know-Enable-File-Level-Authentication-in-IIS-7-75.aspx


text:
Q: Can we force Javascript/jQuery to load fresh (unmodified) version of page from anchor link in modified page? I have a jQuery function that clones certain elements on a page and then appends them as a list, replacing the prior content.
For background, the items are Wordpress comments of a certain type - posted since datetime "n" - that have been isolated within a nested comment structure. The nested comment thread is completely hidden, and a list of the selected comments take their place.
If this seems... peculiar... note that since the comments cannot be shown/hidden as siblings, getting them all meant cloning, re-formatting, and appending them in a list to a page element. The prior nested structure is hidden, and the new list of the selected comments appears in the former space.
So far, so good. Toggling back to the prior version also works fine. Everything works fine except for a last problem: When clicked, links of a certain type (those linking to elements within the same page, identified by id/hash) behave in a less than fully desirable manner.
These internal links, when clicked, appear in the browser address bar - .e.g.: ourhome/page/#itemID. If the linked item happens to be displayed in the cloned list, they function as normal anchors: We jump to their location within the list. (That's OK, if not necessarily ideal for all possible applications.)
But: If the element they link to is hidden, nothing happens except that the address in the browser bar changes.
Ideally, we would automatically force all links when clicked either, if external links, simply to load the linked page as usual, or, if internal, to load a fresh version of the page as displayed in the browser bar - that is, at the correct linked hash.
Unfortunately for this purpose, location.reload(), window.history.go(0) and, assuming I was using them correctly, other simple methods for refreshing the page DO NOT reload with the address in the browser bar, but with the prior address of the page. So the actual internal link is lost.
Preventing default action on anchor links would seem to serve no purpose here: It merely would prevent the new link from ever making it to the browser in the first place.
Is there a simple or even a complicated way to force clicked links to load fresh versions of the page with the new anchor/hash?
ADDITIONAL NOTE: This almost works, but doesn't actually go to the anchor on the refreshed page: We see the correct link in the browser bar, but instead go to some other spot on the page, possibly determined by offset(?). (Sub-note: Am using in this example familiar jQuery dollar signs instead of "jQuery" which Wordpress requires for "no-conflict"):
    $('a').click(function() {

    var url = $(this).attr('href');
    location.assign(url);
    history.go(0);

});

Same results so far with location.reload(), window.location.href and other minor variations...
NEW NEAR-SOLUTION:
    $('a').click(function(e) {

        e.preventDefault();
        var url = $(this).attr('href');
        window.open(url);

    });

In this version we open a fresh new page in another window that at least goes right to the item originally linked - no scroll problems except in a certain complicated secondary case (involving WordPress comment reply links, which present unique handling problems).
Unfortunately, window.open(url,"_self") encounters the same problems as with other methods. So, window.open(url) still the best solution so far, though still less than ideal.
IN LIEU OF SCREENSHOTS REQUESTED
Function in use and under testing here: http://ordinary-gentlemen.com/developing/2015/08/comments-since-last-visit-reloaded-reloaded-testing-post/
You'll have to leave a comment, or visit and then return later, to access the functions (since they deal with comments left "new since last visit").
I'm leaning toward preferring the "near-solution" over the alternative originally envisioned, but will leave this question unanswered at least for now in case someone has an enlightening answer.

A: It seems like you are wanting a cachebuster.
 var url = $(this).attr('href')+'?cb'+Date.now();

Also note that you can push pages to the browsers history with javascript: https://developer.mozilla.org/en-US/docs/Web/API/History_API


text:
Q: Problems with Subfigures? As a newbie to LaTeX, I am currently preparing my very first paper. Since the conference to which I am going to submit my paper to requires the authors to use the IEEE conference paper template.
I encounter problems with the subfigures. The following is my code.
\documentclass[conference]{IEEEtran}
\usepackage{natbib} % for the bibliography
\usepackage[pdftex]{graphicx}
\usepackage[cmex10]{amsmath} % http://www.ctan.org/tex-archive/macros/latex/required/amslatex/math/
\usepackage{algorithm} % http://ctan.org/pkg/algorithms
\usepackage{algpseudocode} % http://ctan.org/pkg/algorithmicx
\usepackage{array} % http://www.ctan.org/tex-archive/macros/latex/required/tools/
\usepackage{mdwmath}
\usepackage{mdwtab} % http://www.ctan.org/tex-archive/macros/latex/contrib/mdwtools/
\usepackage{eqparbox} % http://www.ctan.org/tex-archive/macros/latex/contrib/eqparbox/
\usepackage[tight,footnotesize]{subfigure} % http://www.ctan.org/tex-archive/obsolete/macros/latex/contrib/subfigure/
\usepackage{fixltx2e} % http://www.ctan.org/tex-archive/macros/latex/base/
\usepackage{stfloats} % http://www.ctan.org/tex-archive/macros/latex/contrib/sttools/
\usepackage{url} % http://www.ctan.org/tex-archive/macros/latex/contrib/misc/

\begin{document}

\title{Title}

\author{
\IEEEauthorblockN{
    Name1\IEEEauthorrefmark{1},
    Name2\IEEEauthorrefmark{2},
    Name3\IEEEauthorrefmark{3} and
    Name4\IEEEauthorrefmark{4}}
\IEEEauthorblockA{\IEEEauthorrefmark{1}institute1\\ Email1}
\IEEEauthorblockA{\IEEEauthorrefmark{2}institute2\\ Email2}}

% make the title area
\maketitle

\begin{abstract}
%\boldmath
The abstract goes here.
\end{abstract}

\section{Conclusion}
% An example of a double column floating figure using two subfigures.
% (The subfig.sty package must be loaded for this to work.)
% The subfigure \label commands are set within each subfloat command, the
% \label for the overall figure must come after \caption.
% \hfil must be used as a separator to get equal spacing.
% The subfigure.sty package works much the same way, except \subfigure is
% used instead of \subfloat.
%
\begin{figure*}[!t]
\centerline{\subfloat[Case I]\includegraphics[width=2.5in]{subfigcase1}%
\label{fig_first_case}}
\hfil
\subfloat[Case II]{\includegraphics[width=2.5in]{subfigcase2}%
\label{fig_second_case}}}
\caption{Simulation results}
\label{fig_sim}
\end{figure*}

\end{document}

Error Messages:
! Undefined control sequence.<argument> \subfloat[Case I]\includegraphics [width=2.5in]{subfigcase1}\lab... \label{fig_first_case}}
! Undefined control sequence. \subfloat
! Extra }, or forgotten \endgroup.\@endfloatbox ...pagefalse \outer@nobreak \egroup\color@endbox \end{figure}
! Extra }, or forgotten \endgroup.\@endfloatbox ...pagefalse \outer@nobreak \egroup\color@endbox \end{figure}
Label `fig_sim' multiply defined.
There were multiply-defined labels.

Where did I do wrong?

A: You have done some minor mistakes in the syntax for the sub-figures. Replacing »subfigure« by »subfig« works in the below approach.
\documentclass[conference]{IEEEtran}
\usepackage[T1]{fontenc}
\usepackage[demo]{graphicx}  % drop `demo` option in actual document!
\usepackage[caption=false]{subfig}

\title{Title}
\author{
  \IEEEauthorblockN{
    Name1\IEEEauthorrefmark{1},
    Name2\IEEEauthorrefmark{2},
    Name3\IEEEauthorrefmark{3} and
    Name4\IEEEauthorrefmark{4}
  }
  \IEEEauthorblockA{\IEEEauthorrefmark{1}institute1\\ Email1}
  \IEEEauthorblockA{\IEEEauthorrefmark{2}institute2\\ Email2}
}

\begin{document}
  \maketitle

  \begin{abstract}
    The abstract goes here.
  \end{abstract}

  \section{Conclusion}
    \begin{figure*}[!tb]
      \centering
      \subfloat[Case I\label{fig:first-case}]{%
        \includegraphics[width=2.5in]{subfigcase1}%
      }
      \hfill
      \subfloat[Case II\label{fig:second-case}]{%
        \includegraphics[width=2.5in]{subfigcase2}%
      }
      \caption{Simulation results}
      \label{fig:sim}
    \end{figure*}
\end{document}

Note that the figure will be shifted to the next page.


text:
Q: Using get_member in Cogs I have two applications one main.py which is my main file and the other one is Loops.py in which I use Cogs and tasks inside them so there is a problem.I have a function to change the nickname of my bot every second to another name like this :
botsnick = cycle(['','','','','','','',' ',' ',' ',' '])
@tasks.loop(seconds=1)
async def change_nick():
    server = client.get_guild(771043820157534228)
    bots = server.get_member(848887911884521502)
    await bots.edit(nick=next(botsnick))

It is working properly in main.py but as soon as I implement this code into Loops.py and inside Cog like this :
class Loops(commands.Cog):
    def __init__(self,client):
        self.client = client
        self.change_nick.start()

    botsnick = cycle(['','','','','','','',' ',' ',' ',' '])
    @tasks.loop(seconds=1)
    async def change_nick(self):
        server = self.client.get_guild(771043820157534228)
        bots = server.get_member(848887911884521502)
        await bots.edit(nick=next(self.botsnick))

def setup(client):
    client.add_cog(Loops(client))

I get this error :
bots = server.get_member(848887911884521502)
AttributeError: 'NoneType' object has no attribute 'get_member'

but there is no error in main.py if I use this fucntion there what is wrong?

A: get_member gets the Member from cache, since the loop starts immediately, your bot's internal cache isn't ready, as a result it doesn't find anything and returns None
Simple fix is to use await self.client.wait_until_ready() in a @yourtaskname.before_loop

*

*client.wait_until_ready()


text:
Q: how do I exit from xfce4-screenshooter -r without taking a picture? so I'm been trying to simulate Xubuntu to work similarly to the stuff I often do on my MacBookPro. One of the things I often do is to create a screenshot of a region and on xUbuntu, this is done via:
xfce4-screenshooter -r

My question is: if I pressed the shortcut combination by mistake, how do I exit without taking a pic? On the Mac, this can be done via the escape key or perhaps right-clicking using the mouse (not sure now. but can confirm in a bit).
I've searched the net before asking but nothing useful comes up.
Thanks a lot.
edit:  Pressing the "escape" key works the first time. but if I press the shortcut again, "escape" key doesn't work anymore.

A: Use timeout command to run the screenshot tool with a time limit.
Add a new application shortcut with the following command.
timeout 15 bash -c 'xfce4-screenshooter -r -s $HOME'

Then, press any keyboard keys of choice for the command shortcut. I had used Shift+Print keys in my testing. Now press again the keys to invoke the command.
Why those options
-s PATH is to specify directory at PATH where the screenshot will be saved. This option will skip the dialog to select action i.e. save, copy to clipboard that is shown before "Save As" dialog. This will reduce user interaction by several seconds.
bash -c '... $HOME' is to specify the environmental variable of Home directory of current user, using bash shell. This is convenient, rather than using direct path as /home/USERNAME.
Wait or kill
When timeout has reached the duration, the specified command i.e. Screenshooter will be terminated, regardless of screenshot has been taken and saved or otherwise. The command doesn't require a separate shortcut to exit the application. Wait for specified duration to exit on its own.
If the specified duration is quite long to wait, user can either:

*

*Change the timeout duration from 15 to smaller value in seconds

*Exit immediately by using the shortcut keys for killall xfce4-screenshooter as suggested by @linuxode
The latter seems to be an easier workaround, rather than changing the timeout duration that depends on time taken by user to select a region and saving the screenshot with different name, if any. This is why I had suggested 15 seconds and not lesser than that.
Even better, set optimal duration (neither too short nor too long for user to wait) and use both of the workarounds that will allow user to either "wait or kill", to exit Screenshooter in Xfce.
Disclaimer: This answer suggests a workaround, not a definite solution. The best answer would be to use Esc key that is supposed to work properly with Screenshooter in Xfce. I'm unsure if the said issue is still occurring in Xfce newer than 4.10 or else.

A: The command to do this (or for any unresponsive app) is killall <application name> So, in your case it will be killall xfce4-screenshooter How do you do this?  Set up a keyboard shortcut for this command. Whenever you accidentally press the keyboard combination for xfce4-screenshooter -r, simply press Escape or the shortcut you created for killall xfce4-screenshooter.  Found this here (Look at the second comment).


text:
Q: angular-fullstack heroku deployment Warning: fatal: 'heroku' does not appear to be a git repository Im new to angular-fullstack and I was trying to deploy my app to heroku, but I'm getting this Warning: Build directory "dist" doesn't exist. Nothing to version. Use --force to continue. error every time I do this command which is grunt buildcontrol:heroku
I already have a heroku app setup on herokuapp.com of course and a git remote for it as well.
UPDATE
As @maurycy pointed out I did grunt build but with --force grunt build --force I got the /dist and then grunt buildcontrol:heroku but now I got this Warning: fatal: 'heroku' does not appear to be a git repository


text:
Q: mysql error: Lock wait timeout exceeded I'm using mysql together with asp.net on my webserver. I also use a sqlite database to be able to use the database on another device. I need to send data between the two databases. This is something that needs to be done many times a day. This is an example of how I do it:
    using (MySqlTransaction mysqltransaction = mysqlconn.BeginTransaction())
            {
                using (mysqlcmd)
                {
                    //Creates parameters
                    MySqlParameter parmitemid = new MySqlParameter("?itemid", MySqlDbType.Int32);
                    mysqlcmd.Parameters.Add(parmitemid);
     //Creates more parameters, can't show them all...

                    //For each row in the sqlite table, do the insert
                    while (reader.Read())
                    {
                        //Sets the parameters, can't show them all
                        parmitemid.Value = reader.GetInt(1);
   mysqlcmd.CommandText = "INSERT INTO tblitem (itemid,......,customerid) VALUES (?itemid,......,(SELECT customerid FROM tblcustomer WHERE fid=?fid ORDER BY customerid DESC LIMIT 1))";
                        mysqlcmd.ExecuteNonQuery();
                    }
                }
                mysqltransaction.Commit();
            }

This is how I do it, as I wrote in the comments, there are many more parameters but they are all the same as the first one. When sending data between the databases I have like 20 different sets of this code doing almost the same thing as the code here. But as you understand I can't show them all..
Sometimes there can be 3000-4000 rows that needs to insert, but often small like 1-50.
The problem is that I run into this error from time to time "Lock wait timeout exceeded; try restarting transaction" and wonder what I can do to avoid it?
Also the whole solution seems slow. Can it be that I need to do a subselect for each insert query?
Thanks!

A: You can insert multiple rows at once using this syntax:
INSERT INTO table (col1, col2) VALUES ('a', 1), ('b', 2), ('c', 3)

This will insert three rows at once and is much faster.


text:
Q: How to create Multiple Selection in a List View with visibility of checkbox? I am having a Gridview which consists of list of customers, what i want is whenever send message option from toolbar is clicked , a checkbox should appear infront of each customer name in Gridview , means checkbox visibility should be visible only when send message is clicked , else checkbox visibility should be gone.
     gv=(GridView)findViewById(R.id.gridview);
     gv.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
     gv.setMultiChoiceModeListener(new GridView.MultiChoiceModeListener() {

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.setTitle("Select Items");
            mode.setSubtitle("One item selected");
            return true;
            }

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return true;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return true;
            }

            public void onDestroyActionMode(ActionMode mode) {
            //UN SELECT ALL IF PRESSED BACK
            tv_select_all.setText("Select all");
            selectedAll=false;
            for (int i = 0; i < gv.getAdapter().getCount(); i++)
            {
                gv.setItemChecked(i, false);
            }

            }

           public void onItemCheckedStateChanged(ActionMode mode, int position, long id,boolean checked)

            {
            View v = getViewByPosition(position,gv);

            int selectCount = gv.getCheckedItemCount();
            switch (selectCount) {
                case 1:
                    mode.setSubtitle("1 item selected");
                    break;
                default:
                    mode.setSubtitle("" + selectCount + " items selected");
                    break;
            }

             //CHANEG COLOR TO CYAN IF SELECTED BLUE IF NOT
            if(checked){
                ((CheckBox)v.findViewById(R.id.checkBox)).setChecked(true);
            }else{
                ((CheckBox)v.findViewById(R.id.checkBox)).setChecked(false);
            }
        }

    });

       tv_select_all.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!selectedAll) {
                tv_select_all.setText("Unselect all");
                for (int i = 0; i < listView.getAdapter().getCount(); i++) {
                    gv.setItemChecked(i, true);
                }
                selectedAll=true;
            }
            else {
                tv_select_all.setText("Select all");
                selectedAll=false;
                for (int i = 0; i < listView.getAdapter().getCount(); i++) {
                    gv.setItemChecked(i, false);
                }
            }
        }
    });

    public void checkItem(int i){
    gv.setItemChecked(i, true);
}

    public void uncheckItem(int i){
    gv.setItemChecked(i, false);
}

    //TO GET VIEW FROM ID
    public View getViewByPosition(int pos, GridView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return gv.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return gv.getChildAt(childIndex);
    }
}

A: If you have GridView, you should have a custom adapter like this:
public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(
                        R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkbox.setId(position);
            holder.imageview.setId(position);
            holder.checkbox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]){
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            holder.imageview.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    int id = v.getId();
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
                    startActivity(intent);
                }
            });
            holder.imageview.setImageBitmap(thumbnails[position]);
            holder.checkbox.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }
    class ViewHolder {
        ImageView imageview;
        CheckBox checkbox;
        int id;
    }
}

Please have a look here .


text:
Q: Bootstrap justified navbar not evenly spacing menu items on Internet explorer I'm using twitter bootstrap 3.1.1 and using the nav-justified class for my main navigation. It works well on all the major browsers except IE11 and below. Firefox, Chrome and Safari are able to evenly space out the li items based on the content but in IE it doesn't. Does anyone know of any quick fixes or point me in the right direction? I'm trying to avoid JS to set the widths and am trying to work out a CSS solution. Has anyone had this issue with the navbar in bootstrap?
Navigation displaying correctly on firefox, chrome, safari

Navigation not evenly spacing out menu items on IE11, IE10, IE9 or IE8

I've put an example of JSFiddle - http://jsfiddle.net/bGHL4/20/

Menus

Offers

Gallery

Benefit Cards

Reservations

Contact

Events

On IE the Benefit Cards item has different space between that and gallery and reservations. However on all the other major browsers the spacing between all navigation items is consistent.
thanks


text:
Q: VSTO 2015 generates pseudo code depending on office installed language On my workstation, I created, using VSTO 2015, a project with the template named 'Excel 2013 and 2016 VSTO Workbook'.
I used the Copy option from the project template to copy an existing Excel document.
I have Office 2016 in french installed on this computer, and VS generated a code with several classes inheriting from WorksheetBase with names 'Feuill1', Feuill2', etc. For the sheet n, the cookies and identifier parameters for the WorksheetBase constructor are generated in code as 'Feuilln',"Feuilln'.
I adapted my code and the project runs perfectly.
I then copied my VS project to another computer where Office 2016 was installed for english language. When I try to run my project I get errors, it appears that Feuilln is not found. I changed these names for 'Sheetn' and it worked.
I am very disapointed : isn't it a misconception to generate classes depending on the culture ???
Is there a way to create a project working independently of Office culture ?
I can't find any documentation on the process used by the Microsoft.Office.Tools.Excel.Factory and its usage of the xxxx.Designer.xml parameter file. Is adapting this file the way to go to be culture independant ?


text:
Q: Cannot access class varaible withing "findIndex" function - resolved I cannot access my class variable from findIndex method.
 My whole class:

    import { Component, Input, OnInit } from '@angular/core';
import { History } from '../model/history';
import { SharedService } from "../shared.service";

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss']
})
export class DetailsComponent implements OnInit {
  history: History[] = [
    {
      basic_text: { basic_text: 'text_1' },
      summary: { summary: 'summary_1' },
      tager: { tag_algorytm: true, tag_text: "tag_1" }
    },
    {
      basic_text: { basic_text: 'text_2' },
      summary: { summary: 'summary_2' },
      tager: { tag_algorytm: false, tag_text: "tag_2" }
    }
  ];
  basic_text: String = "Tekst podstawowy";
  summary: String = "Streszczenie";
  rating: String = "Ocenione zdania";
  chosedText: string;
  asd: string = 'asdad';

  constructor(private sharedService: SharedService) { }

  ngOnInit() {
    this.sharedService.sharedMessage.subscribe(chosedText => this.chosedText = chosedText)
  }

  textFilter(h: History[]) {
    let result: History[] = [];
    var param = this.chosedText;
    var foundIndex = h.findIndex(this.isEqualToSelectedText, param);

    result.push(h[foundIndex])
    return result;
  }

  // The function was moved out
  private isEqualToSelectedText(element: History) {
    return element.basic_text.basic_text === this.chosedText;
  }

}

I'm assigning thisArg with value of chosedText.
Error that I'm getting:
core.js:5967 ERROR TypeError: Cannot read property 'basic_text' of undefined
    at DetailsComponent_tr_12_Template (details.component.html:11)
    at executeTemplate (core.js:9274)
    at refreshView (core.js:9143)
    at refreshEmbeddedViews (core.js:10263)
    at refreshView (core.js:9167)
    at refreshComponent (core.js:10309)
    at refreshChildComponents (core.js:8940)
    at refreshView (core.js:9193)
    at refreshComponent (core.js:10309)
    at refreshChildComponents (core.js:8940)

But if I do
var x= h.findIndex(isEqualToSelectedText, 'text_1');

Everything works fine.
I tried to access my class varialb from isEqualToSelectedText function. But I always got this error.
The word "this" should during running of findIndex be equal 'text_1'.
Can you help me?

A: this will lose its reference because of the function scope. You could use an arrow function so it can preserve its scope or even move out the isEqualToSelectedText function to a private method in that class.
It could be like this:
// in the same place you're declaring the function
const isEqualToSelectedText = (element : History) => {
      return element.basic_text.basic_text === this.chosedText;
}

// or moving out to a private method in the class
export class DetailsComponent implements OnInit {
    history: History[] = [
        {
            basic_text: { basic_text : 'text_1' },
            summary: { summary : 'summary_1' },
            tager: { tag_algorytm : true, tag_text: 'tag_1' }
        },
        {
            basic_text: { basic_text : 'text_2' },
            summary: { summary : 'summary_2' },
            tager: { tag_algorytm : false, tag_text: 'tag_2' }
        }
    ];

    chosedText: string = 'text_1';

    textFilter(h: History[]) {
        let result: History[] = [];
        var param = this.chosedText;
        var foundIndex= h.findIndex(this.isEqualToSelectedText, param); // <-- changing here

        result.push(h[foundIndex])
        return result;
    }

    // The function was moved out
    private isEqualToSelectedText(element: History) {
        return element.basic_text.basic_text === this.chosedText;
    }
}

A: Ok, I have found the error. I was using my variable before it was initialized by "http get".
So the problem is resolved, thanks for help.


text:
Q: float to _bstr_t I know I can create a _bstr_t with a float by doing:
mValue = _bstr_t(flt);

And I can format the float string by first declaring a c string:
char* str = new char[30];
sprintf(str, "%.7g", flt);
mValue = _bstr_t(str);

I am a bit rusty on c++, especially when it comes to _bstr_t which is A C++ class wrapper for the Visual Basic string type.
Will the memory pointed to by str be managed by the _bstr_t object?
My problem is passing the float (flt) into the constructor of the _bstr_t causes a float with a number 33.03434 to turn into "33,03434" if for instance my current language set is Italian.  Is there another way to declare it perhaps?

A: When you create a _bstr_t instance using a conversion from char* a new BSTR is created, the object doesn't take ownership of memory pointed to by char*. You'll have to manage the memory pointed to by char* yourself.
In you case since you know that there's a limit on how long a produces string can be your best bet is to allocate the buffer on stack:
const int bufferLength = 30;
char str[bufferLength] = {};
snprintf(str, bufferLength - 1, "%.7g", flt);
mValue = _bstr_t(str);

A: I ended up using CString since it is memory managed:
CString cstr;
cstr.Format(_T("%.7g"),flt);
mValue = _bstr_t(cstr);

A: _bstr_t FormatBstr(LPCWSTR FormatString, ...)
{
    ATLASSERT( AtlIsValidString(FormatString) );
    unsigned int len = 10 + wcslen(FormatString);
    unsigned int used = 0;

    BSTR r = ::SysAllocStringLen(NULL, len);

    va_list argList;
    va_start( argList, FormatString );
    while(len < 2048) {
            used = _vsnwprintf_s(r, len+1, _TRUNCATE, FormatString, argList);
            if(used < len)
                    break;
            len += 10; // XXX
            ::SysReAllocStringLen(&r, NULL, len);
    }
    va_end( argList );
    ::SysReAllocStringLen(&r, r, used);
    return _bstr_t(r, false);
}

then
sprintf(str, "%.7g", flt);
mValue = FormatBstr(L"%.7g", flt);


text:
Q: Http failure response for http://localhost:3000/test: 401 Unauthorized while login via Browser I was trying to login via API using HTML Form through Chrome Browser but it is showing Http failure response for http://localhost:3000/test: 401 Unauthorized.
My Login API is working fine when I try to login via Postman.
I am not able to understand things are working fine in postman but once I call the same API in Angular 12, It's not working proerly.
Postman Response :-
API - http://localhost:3000/witslogin
Successfull Response :-
{
"msg": "Logged in!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIsImlhdCI6MTY3MTI4MjkxMywiZXhwIjoxNjcxMjg2NTEzfQ.Q7Gnxia3SvnD_v5B4D_7xblKh1y4j6NlQONNWmzyx8U",
"witsusers": {
"id": 12,
"fullname": "Test User",
"email": "test@test.com",
"password": "$2a$10$6qcx7ZgYe662jI70tz4ejegbgnhdoNJYYALVo059WaQF2e1NCAjny",
"last_login": "2022-12-17T12:56:51.000Z"
}
}
But while connecting via Angular, I am getting the below error:-

Code:-
Angular -
login(email: string, password: string) {
    const loginData: LoginData = {email:email, password:password}
    this.http.post<{token: string, expiresIn: number }>("http://localhost:3000/witslogin", loginData)
    .subscribe(response => {
      console.log(response);
    })
  }

<------------------------------------------------------------------------------------------>
Node Code :-
const witsLogin = async (req, res, next) => {
    console.log("Users Login API is working");
    db.query(
        `SELECT * FROM witsusers WHERE email = ${db.escape(req.body.email)};`,
        (err, result) => {
          // user does not exists
          if (err) {
            throw err;
          }
          if (!result.length) {
            return res.status(401).send({
              msg: 'Email or password is incorrect!'
            });
          }
          // check password
          bcrypt.compare(
            req.body.password,
            result[0]['password'],
            (err, bResult) => {
              // wrong password
              if (err) {
                throw err;
              }
              if (bResult) {
                const token = jwt.sign({id:result[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
                db.query(
                  `UPDATE witsusers SET last_login = now() WHERE id = '${result[0].id}'`
                );
                // console.log(token);
                return res.status(200).send({
                  msg: 'Logged in!',
                  token,
                  witsusers: result[0]
                })
              }
              return res.status(401).send({
                msg: 'Username or password is incorrect!'
              });
            }
          );
        }
      );

}

A: Ok.... I see the error. You have forgot the quotes in your query...
Switch this...
  db.query(
        `SELECT * FROM witsusers WHERE email = ${db.escape(req.body.email)};`,
        (err, result) => {

to this...
  db.query(
        `SELECT * FROM witsusers WHERE email = "${db.escape(req.body.email)}";`,
        (err, result) => {

The db.escape part: I use MySQL parameterized queries. It's more secure, too. It works like this:
db.query('SELECT * FROM witsusers WHERE email = ?', [email])

A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time. The most important reason to use parameterized queries is to avoid SQL injection attacks


text:
Q: How to tell python app I am returning JSON I have a shopify app I use to sync quantities between shopify and our POS systems. Recently it started throwing a "406 not acceptable" error. I have tracked it down (i think) to when I make the actual call to update the quantity, this line:
return shopify.Variant(dict(id=288275460, inventory_quantity=3.0)).save()

I have hard-coded values that should work but the moment it tries to execute this command i get the traceback posted below.
From what I think is happening is that shopify stopped returning XML and now the returned data isn't acceptable to the python application on my webhost that is executing these commands. What I don't understand is how I would specify that my application should expect the proper content-type. Currently I am not even processing the returned data in any way just executing the command without even a return causes the same error. Just really confused which is unfortunately rather easy.
TRACEBACK:
Internal Server Error: /inventory/process/
Traceback (most recent call last):
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/crabs/projects/webfaction/webdomain.com/apps/shopified/views.py", line 115, in process
    dictUpdated = update(sku, arraydata[0], arraydata[1])
  File "/home/crabs/projects/webfaction/webdomain.com/apps/shopified/inventory.py", line 72, in update
    return simplejson.dumps(shopify.Variant(dict(id=288275460, inventory_quantity=3.0)).save())
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/pyactiveresource/activeresource.py", line 775, in save
    data=self.to_xml())
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/pyactiveresource/connection.py", line 351, in put
    return self._open('PUT', path, headers=headers, data=data)
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/shopify/base.py", line 19, in _open
    self.response = super(ShopifyConnection, self)._open(*args, **kwargs)
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/pyactiveresource/connection.py", line 287, in _open
    http_response = self._handle_error(err)
  File "/home/crabs/.virtualenvs/webhostname/local/lib/python2.7/site-packages/pyactiveresource/connection.py", line 415, in _handle_error
    raise ClientError(err)
ClientError: Response(code=406, body=" ", headers={'status': '406 Not Acceptable', 'x-request-id': '6be354d6-686b-4146-bcf3-03ed080756a2', 'x-xss-protection': '1; mode=block', 'x-shopify-asset-version': '1', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'x-shardid': '0', 'x-stats-apiclientid': '149305', 'connection': 'close', 'server': 'nginx', 'x-stats-apipermissionid': '2992571', 'x-shopid': '2117110', 'x-stats-userid': '0', 'x-ua-compatible': 'chrome=1', 'http_x_shopify_shop_api_call_limit': '1/40', 'date': 'Wed, 16 Jul 2014 19:06:48 GMT', 'x-shopify-shop-api-call-limit': '1/40', 'content-type': 'application/xml'}, msg="Not Acceptable")


text:
Q: Angular 2 Add or Remove item from Array I have this method here:
messageSelected($event, index) {
  console.log($event.target.checked);
  console.log(index);
  if ($event.target.checked) {
    this.selectedMessages.push($event.target.getAttribute('name'));
  }
  else {
    var item = this.selectedMessages.indexOf($event.target.getAttribute('name'), 0);
    this.selectedMessages.slice(item, 1);
  }
  console.log(this.selectedMessages);
}

What I am trying to do is if an item is checked, add the item to the array (this part works) now I am trying to remove the item from the array if the checked is false (this part is not working)
The problem is that the item is not getting removed from the array. What am I doing wrong?
Here is my HTML:

      Username

{{i.subject}}

      {{i.updated_at | date: 'MM/dd/yyyy'}}

        <input type="checkbox" id="{{i.id}}" name="{{i.id}}" (change)="messageSelected($event, item)"/>

A: AngularJS binds to the Array Object, and the slice function in JS creates a new array as a result, leaving the original array as it is.
You should use splice (note the p) which will update the array.
For example:
var index = this.selectedMessages.indexOf($event.target.getAttribute('name'));
this.selectedMessages.splice(index, 1);

A: Besides the confusion between slice (not mutating option) and splice, it seems like you're using angular as vanilla js.
The whole idea of using a framework like this, is to get rid of DOM inspection / manipulation.
You don't need to overload the <input name>, you could call directly messageSelected($event.target.checked, i.id) (modifying the function firm as well, providing all the needed data).
Better than that, you could use two way binding [(ngModel)]="selectedItems[i.id]" to bind the checkbox to a map (object) of "selected items", and then simply extract the true entries, mapping this to an array.
Or, if you dont mind to mutate the i object, you could bind ngModel directly on a custom property like [(ngModel)]="i.selected".
The idea is to avoid wiring manually the change and the getAttribute('name').
Here's a living example: https://codesandbox.io/s/rjxn1y84wm


text:
Q: Geo Location aware Posts I am trying to publish a post on the user news feed with the users current location.
According to the documentation on 'Post' I need to add the location information to the 'place' attribute.
But is seems it is associated with an already defined 'place'. My requirement is to just push the lat / long info to dsiplay the city. Is this possible with the current graph API ?

A: Currently there is no public API to push a new place info, you can only pass existing "places".

A: You could begin by finding the name of the current city and country by inspecting some nearby places:
/search?type=place&center=LAT,LONG
Then you can try to find the Place ID of that city:
/search?type=place&center=LAT,LONG&q=CITY, COUNTRY&limit=1
(You may have to add the state field for countries that use that division.)
Now you have a Place ID to use for your post.


text:
Q: How to upload image and createview I don't understand how to add this image object on view.
please help me.
models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    image = models.ImageField(default='post.jpg', upload_to='image')

    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        super().save()

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

what i do for the image field is valid.
I want to be able to upload an image file using CreateView and a LoginRequiredMixin but I can't get it working - it seems the form doesn't bind any file data after choosing a file. Here's the current content of the view
views
 class PostCreateView(LoginRequiredMixin, CreateView):
       model = Post
       fields = ['title', 'content','image']

       def form_valid(self, form):
           form.instance.author = self.request.user

           return super().form_valid(form)

any think i do jast show the default photo. i do not understand how to handle this.I try my best i think.
post_form.html
 {% extends "blog/base.html" %}
 {% load crispy_forms_tags %}
 {% block content %}

    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Blog Post</legend>
            {{ form|crispy }}
        </fieldset>

            <button class="btn btn-outline-info"
        type="submit">Post</button>

       </form>

   {% endblock content %}

home.html
  {% extends "blog/base.html" %}
  {% block content %}
     {% for post in posts %}

          {{ post.author }}
          {{ post.date_posted|date:"F d, Y" }}

         {{ post.title }}

{{ post.content }}

     {% endfor %}
   {% endblock content %}

command line
OSError: [WinError 123] The filename, directory name, or volume label syntax
is incorrect: 'C:\\Users\\Arvan\\Desktop\\django_project\\medi
a\\<MultiValueDict: {}>'
[07/Dec/2018 04:04:39] "GET /media/%3CMultiValueDict%3A%20%7B%7D%3E HTTP/1.1"
500 80871

A: Instead of your current form_valid method in your view try:
def form_valid(self, form):
    post = form.save(commit=False)
    post.save()
    return HttpResponseRedirect(reverse('redirect'))

and in your template make sure your form has the following:
<form method="post" enctype="multipart/form-data">

key being the enctype for submitting files.


text:
Q: Is that possible to customize "files export path"? System - Data Transfer - Export
The files export is in /magento/var/export/. Can we custom this path?
And if we can custom. How to?

A: You can of course customize it, as everything in magento.
Step 1 : Check the url triggered by the export to find the controller used.
Step 2 : Analyse the controller code to find where the var/export path is used.
Step 3 : Make a preference from that class and change according to your own requirements.
That being said i don't see the goal behind all that.


text:
Q: почему не создает бд в пайтоне? SQLITE3 В общем не могу понять почему не создается бд и в нее не записываются данные. Использую библиотеку pyTelegramAPI . Буду рад совету.
def get_connection():
    print(1)
    __connection
    if __connection is None:
        __connection = sqlite3.connect('Notebook_log.db')
        conn.commit()

def init_db(force: bool=False): #Если сменить на True то пересоздастся
    conn = get_connection()
    c = conn.cursor()
    if force:
        c.execute('DROP TABLE IF EXISTS book_notebook')
        c.execute("\n"
                  "        CREATE TABLE book_notebook (\n"
                  "            id                  INTEGER PRIMARY KEY,\n"
                  "            user_id             INTEGER NOT NULL,\n"
                  "            text                TEXT NOT NULL\n"
                  "            )\n"
                  "\n"
                  "")

    conn.commit()
def add_message(user_id: int, text: str):
    conn = get_connection()
    c = conn.cursor()
    c.execute("INSERT INTO book_notebook (user_id, text ) VALUES (?,?)", (user_id, text))
    conn.commit()

A: Попробуйте взять этот код и адаптировать под себя.
import sqlite3

class DB:
   """Метод, создающий соединение с базой данных, либо новую базу данных(при её отсутствии по пути path_name)"""
   def __init__(self, path_name):
       self.path_name = path_name
       self.connection = sqlite3.connect(path_name)
       self.cursor = self.connection.cursor()
       print('Конструктор таблицы запущен')

x = DB(r"C:\Users\User\Desktop\tpy\mydatabase.db")
x.close()