text:
Q: MvvmCross Custom Binding not notified by RaisePropertyChanged I'm trying to implement a triggerable animation on an MvxImageView (within an android CardView) to overlay a color (green or red) onto the image on the change of a property on the card's ViewModel. I have created the custom class DynamicImageView using Stuart Lodge's example here.
public class DynamicImageView : MvxImageView
{
    public DynamicImageView(Context context) : base(context)
    {
    }

    public DynamicImageView(Context context, IAttributeSet attrs) : base(context, attrs)
    {
    }

    public DynamicImageView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
    {
    }

    protected DynamicImageView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }

    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        Drawable d = this.Drawable;

        if (d != null)
        {
            // ceil not round - avoid thin vertical gaps along the left/right edges
            int width = MeasureSpec.GetSize(widthMeasureSpec);
            int height = (int)Math.Ceiling(width * (float)d.IntrinsicHeight / d.IntrinsicWidth);
            this.SetMeasuredDimension(width, height);
        }
        else
        {
            base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    private ObjectAnimator colorFilterAnimation;

    private string _animatingColor;
    public string AnimatingColor
    {
        set
        {
            System.Diagnostics.Debug.WriteLine("Animation triggered");
            if (value != _animatingColor)
            {
                _animatingColor = value;
                colorFilterAnimation = ObjectAnimator.OfObject((ImageView)this, "colorFilter", new ArgbEvaluator(), 0, 0);
                switch (value)
                {
                    case "red":
                        colorFilterAnimation.SetObjectValues(0, new Color(100, 0, 0, 80).ToArgb());
                        System.Diagnostics.Debug.WriteLine("Starting Red Animation");
                        break;
                    case "green":
                        colorFilterAnimation.SetObjectValues(0, (int)Color.Green);
                        System.Diagnostics.Debug.WriteLine("Starting Green Animation");
                        break;
                }
                colorFilterAnimation.SetDuration(1000);
                colorFilterAnimation.Start();
            }
        }
    }
}

Within the ViewModel for this control, I have the matching property defined as well, following standard MvvmCross notation:
private string _animatingColor;
    public string AnimatingColor {
        get
        {
            return _animatingColor;
        }
        set
        {
            _animatingColor = value;
            Debug.WriteLine("AnimatingColor set to " + value);
            RaisePropertyChanged(() => AnimatingColor);
        }
    }

This property is changed on a click to the card, and when I click I do see the Debug print from within the property set, but it doesn't seem to trigger the set for AnimatingColor within the control at all. The control is referenced in axml as normal:
<DynamicImageView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:scaleType="centerCrop"
  local:MvxBind="ImageUrl 'http:'+Profile.Headshot.Url; AnimatingColor .AnimatingColor" />

and for what it's worth, the imageUrl does bind correctly, and updates as expected when the Url is changed in the ViewModel. Additionally, the Debug.PrintLine("Animation triggered") does print when the cards are created, but never when the property is changed on the ViewModel.

A: As the comments suggest, I believe you need to create a custom binding for your DynamicImageView control. Something like this should do it:
public class DynamicImageViewAnimatingColorBinding : MvxTargetBinding
{
    public DynamicImageViewAnimatingColorBinding(DynamicImageView target) : base(target)
    {
    }

    protected DynamicImageView View => Target as DynamicImageView;

    public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;

    public override Type TargetType => typeof(string);

    public override void SetValue(object value)
    {
        var view = View;
        if (view == null)
            return;

        view.AnimatingColor = (string) value;
    }
}

Then in your Setup class you need to register it so that MvvmCross can use it:
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
        registry.RegisterCustomBindingFactory<DynamicImageView>(
            nameof(DynamicImageView.AnimatingColor),
            image => new DynamicImageViewAnimatingColorBinding (image));

        base.FillTargetFactories(registry);
    }

I haven't tested this code and it's based on some very similar code I used on iOS but it should work fine on Android. Hopefully this helps.

A: James Mundy's questions led me to realize that the underlying issue is that I was not using an ObservableCollection in a list, so the changes to the underlying ViewModels were not being reflected in the UI.


text:
Q: AppScript UrlFetchApp.fetch() not working for WebApp accessible only by domain users I currently have an issue where I have:

*

*Main account who owns an appscript deployed as a WebApp with excute set to "Me"
  and acces set to "Anyone within @[mydomain].com" with doGet() and doPost()
  methods.

*Secondary account who ownsappscript sending UrlFetchApp.fetch("mainAppURL").
Running the script in the secondary account returns the HTML of the Google Sign Page with response.getContentText() and does not run the doGet() method, but running the mainAppURL in the address bar seems to work.
Why is the script not creating a pop up to request the user to sign in?

A: As @TheMaster said, the driveApp scope should be in the project properties (running a driveApp command will run the authorization) so that a script from a secondary account within the domain may perform a fetch request to as script owned by another account within that same domain.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to derive a relative path using Ant I'm using Ant and mxmlc to compile ActionScript classes and MXML into swfs, while maintaining the default organization of a Flex Builder (Flash Builder) project.  Many of my ActionScript classes are in project subdirectories, so my project is organized like the following:
MyBigProject
-build-imports.xml
-build.xml

-bin-debug
--src
---flash
---app
----CoolWidget1.swf
---Main.swf
--test

-src
--flash
---app
----build-imports.xml
----build.xml
----CoolWidget1.as
--build-imports.xml
--build.xml
--Main.mxml
-test

This directory structure maintains the default directory structure of a Flash Builder project so I can perform push-button builds from the Flash Builder IDE.  I've added the Ant build xml's to this project so I can also build from the command line.  I'm trying to create portable ant build scripts that require the least changes to reuse in other projects.  I have everything like I want except for deriving relative paths.
The build-imports.xml file at the root of the project contains the following:
<project name="project.root.imports">
    <dirname property="project.root.dir" file="${ant.file.project.root.imports}"/>
</project>

While the sub project folders contain build-imports.xml with the following:
<project name="MyBigProject.src.flash.app.imports">
    <import file="../build-imports.xml" />
</project>

Notice that sub project build-imports.xml walks up the directory hiearchy till it gets to the root build-imports.xml, and there I set the project.root.dir.
I can then use the ${project.root.dir}/bin-debug to specify where to place my binaries.  The only problem I have, is I do not know how to create the same directory structure as what lies under my src folder.  I need to be able to derive a relative path or perform some string manipulation to create new directorys.
Considering the above information, how do I take a known path like:
${project.root.dir}/src/app
and derive a directory path like:
${project.root.dir}/bin-debug/app
I've found some information about the Ant-contribu propertyregex task, which would allow some string manipulation, but I'm hoping there is an Ant guru out there that can point to a simple solution.  I believe it's highly likely as an Ant novice, I'm simply overlooking the obvious.

A: My build files have evolved a bit since I posted, but I've resolved the problem.  I believe the following would work correctly in the basic setup previously described:
Add this to the default target in the sub project's build.xml
<path id="build.path">
   <pathelement location="." />
</path>
<pathconvert property="build.dir" refid="build.path">
    <map from="${project.root.dir}" to="${project.root.dir}/bin-debug"/>
</pathconvert>


text:
Q: Can I reconnect history for an improperly extracted library in subversion? "Someone" has extracted
/giant-repo/trunk/sublib

into
/fancyname/trunk

Some of the directories and files were copied or moved correctly, using svn cp and svn mv, thus preserving history.
Others, both files and directories, were freshly constructed (isomorphically modulo renamings from sublib to fancyname) in the new location before file content was copied in from the original location (i.e. unversioned).
What I'm seeing is:
~/work/fancyname> svn log -r 1234 --verbose
...
   A /fancyname/trunk/foo.txt
   A /fancyname/trunk/bar.txt (from /giant-repo/trunk/sublib/bar.txt:950)
...

There are a total of about 140 files, and 100 commits to /fancyname/trunk at present.
Is there a way to tell subversion that foo.txt, that was added in r1234, really should have been a copy from sublib/foo.txt:950?
If not (and I suspect this is the case), how can I hack this into shape?
I imagine for files that haven't had any commits in the new repo, the easiest solution will be to remove the new file (is there a "super" revert that reverts the add from the repository?) and then issue a correct svn cp.
What about files with changes in the new repo, is there a way to "pickle" those changes, copy the file properly, then reapply the changes?

A: you can not modify history in SVN (without dumping the repo and modifying the dumpfile, which is heavy and cumbersome work).
So the easiest(not the correct!) way is to
svn rename foo.txt foo_wrong.txt, then
svn copy foo.txt@950 foo.txt (now commit)
by this you have repaired your history for foo.txt from now on. The time in between the version history is broken. And you cannot fix it with svn client.


text:
Q: React, Apollo, apollo-link-state. Useless re-rendering of simple components. DEMO This is the console log:

The reproduction demo is here: https://codesandbox.io/s/8n89yrwjx0
This is the relevant code:
const cache = new InMemoryCache();

const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {
      updateStatus: (_, { isEnabled }, { cache }) => {
        const data = {
          status: {
            __typename: "status",
            isEnabled
          }
        };
        cache.writeData({ data });
        return null;
      }
    }
  },
  defaults: {
    status: {
      __typename: "status",
      isEnabled: false
    }
  }
});

const client = new ApolloClient({
  link: stateLink,
  cache
});

Everytime it re-renders Hello component. Why?
I noticed in my Chrome console a difference in the "refetch" prop.
But, in any case, also if I use this code:
export default graphql(STATUS_QUERY, {
    props: ({ data: { loading, error, isEnabled } }) => {
      if (loading) {
        return { loading };
      }

      if (error) {
        return { error };
      }

      return {
        loading: false,
        isEnabled
      };
    }
  }
)(Hello);

it seems to re-render because props are different by reference. Why?


text:
Q: Inflating panel.java by default in android I'm using an android panel widget in my application to create a sliding panel effect from the top of my app (similar to the notification panel).  When clicked the panel opens to fill about 30% of the screen.  By default the panel is closed and has a handle to "show".  I'm trying to modify it to be in the shown state by default but am unsure how to do it.  I assume that I'll have to modify the Panel.java file but I suppose it might also be done in my layout file.. Any tips?

A: Assuming you're defining your own class which extends Panel...in your onCreate() override, you could try calling setOpen(true, false); ?
EDIT As you're not extending it yourself, you could simply call the setOpen() method as soon as your activity is created instead. Example...
public class MyActivity extends Activity {

    protected Panel topPanel = null;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate();
        setContentView(R.layout.main);

        topPanel = (Panel) findViewById(R.id.top_panel);
        topPanel.setOpen(true, false);
    }
}


text:
Q: Right Click on ASP.Net Treeview selects the Node (NOT Windows Forms) I've been googling in circles for hours now but can only find answers relating to WinForms and not ASP.NET web pages.
I would like my ASP Treeview to select the node that is being right clicked (so that I can use my ContextMenu without having to left click a node first)
Is this possible? It feels like it should be? I'm trying to avoid a situation where they have a subfolder open and selected but then right click on a child node and edit but the subfolder is still selected so it edits that


text:
Q: Командный файл, выполняющий действие над всеми архивами внутри рабочей директории Я открываю консоль, перехожу в папку D:\work_dir, и тут у меня лежат zip-фрхивы. У меня есть готовое консольное приложение myData.bat , которое выполняет установку данных из zip-архивов. Команда в cmd выглядит так:
myData.bat install -a file.zip

Здесь для установки я использую команду install , а сам архив указываю через опцию -a

Если надо установить данные из нескольких архивов, то пишу так:
myData.bat install -a file1.zip -a file2.zip -a file3.zip

Теперь надо усложнить немного: теперь у меня в папке D:\work_dir не лежат сразу же zip-aрхивы, а вместо этого находятся директории, а в них поддиректории, сколько именно не известно, разное количество. Но в конечном итоге в поддиректориях в итоге всё равно лежат zip-архивы. И вторая сложность в том, что я не знаю сколько этих архивов будет, может 3 а может 7, или ещё сколько-то. Структура подкаталогов такая:

В общем, подскажите мне плиз, как написать bat-файл, чтобы там получать все zip-архивы, и применять к ним команду на установку, как показано выше.

A: Создайте в папке D:\work_dir bat-файл и введите туда этот код:
@echo off
cd /d "D:\work_dir"
for /f "tokens=* usebackq" %%i in (`dir /b /s D:\work_dir\*.zip`) do (
    myData.bat -install -a %%i
)


text:
Q: how to give auto increment for a column in mysql? I have table which contains three field id(primary key),number and note.Id is auto increment.I want data in this table in which number field contain current date with five digit number.
For example current date is 24/11/2014,then my first entry become 201400001,second will be 201400002 and so on.On next year it will be 201500001,and so on.
Please help me.
Thanks

A: Refer Using Auto Increment in mysql

A: Did you try "ALTER TABLE your_table AUTO_INCREMENT = initial_value" ?


text:
Q: Handling JSON circular reference exception in ASP.NET 5 So I'm playing around with Web API in ASP.NET 5. At some point my app stopped working, only showing "Bad Gateway" IIS error page (I run it in IIS Express, by F5). It took me a while to figure out what the problem was - I introduced a circular reference into a class one of my Web API methods returns, like this:
public class CircularParent
{
    public CircularChild Data;

    public CircularParent()
    {
        Data = new CircularChild(this);
    }
}

public class CircularChild
{
    public CircularParent Owner { get; set; }

    public CircularChild(CircularParent owner)
    {
        Owner = owner;
    }
}

The result is JsonSerializationException. My question is not how to solve it, but rather how to deal with such a situation in future. How can I handle such an exception? Or at least how to log it or just see it logged somewhere? UseDeveloperExceptionPage() does not help. UseExceptionHandler(errorApp => errorApp.Run(...)) does not help either, the execution doesn't get into errorApp.Run(). The debugger does not break at the exception. All I get with IIS is that rather uninformative "Bad Gateway" page.

A: Try to add Newtonsoft.Json in the latest version 8.0.1-beta3 to dependencies in package.json and to use use
services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

See the issue for more details.

A: For ASP.NET Core:
var mvc = services.AddMvc(options =>
{
   //mvc options
});

mvc.AddJsonOptions(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

A: For  ASP.NET Core 2.2 use the Configure method in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    };
}

A: This might be a roundabout way, but I did a db first migration that had allot of virtual properties, while it worked it would result in circular references. I resolved this by adding
[JsonIgnore]

(Newtonsoft in my case) to all the virtual properties and it worked well.


text:
Q: FDMemTable Loses FieldDefs information when there is AutoInc Field in Delphi I am creating a memory table TFDMemTable for a delphi form, and define the fields under FieldDefs. After I am done with the definition of the fields manually, I go to the Fields Editor to add the fields that I just defined.
Everything works perfect until I have an AutoInc type field in my FDMemTable. I am using Delphi 10.3.2 version and I was wondering if I am missing anything or this is a IDE bug.
PS: I have done couple of tests, and I think that if the AutoInc field is not defined as the last field, everything disappears. I am not %100 sure of this case, but pretty much every time I try I loose the fields under FieldDefs.
Here is the steps:

*

*Place a FDMemTable icon

*Open FieldDefs window

*Create a bunch of fields (string, integer ...)

*define the names, types (and sizes for strings)

*Open FieldsEditor

*Add fields

until here everything works as they should.

*

*Go back to fieldDefs window

*create and name a new field with autoinc type

*open the fields editor screen and add the last added field.

everything is still good to go as long as there is no more changes in the structure.
Here the weird thing happens if you do the following.

*

*open FieldDefs window

*create any field ( lets say integer type )

*Go to Fields Editor window to add this last created field.

*and you will see that you don't see this new field to add.

*when you go  back to fieldDefs window to see why it is not showing,

*you will see all the previous and last added fields' definitions gone..

In order for me to go around this problem, I open the form in text form and insert the new field right before the last field which is autoinc,
add field editor entry manually in the text form,
and when everything is right, I toggle to form view.


text:
Q: Player not defined Im having some issues with player not defined errors this is the error and the codes i have putten links to the pictures of it.Im pretty new at python and i don't understand most of the errors,i will be happy if someone could help.
Player not defined errors
Code
Code

A: I have created a minimal working code about your attached pictures. Mostly your global variable handling was not correct. You can find my comments in the below code as comments.
Code:
# Define global variable
current_player = None

class Player(object):
    def __init__(self, name):
        self.name = name
        self.other = 100

def main():
    option = input("Option: ")
    if option == "1":
        start()

def start():
    # Use the global variable inside the function.
    global current_player
    user_name = input("Name: ")
    # Assign the Player instance to the global variable.
    current_player = Player(name=user_name)
    start1()

def start1():
    # Use the global variable inside the function.
    global current_player
    # Get the "name" attribute of the "Player" object.
    print("Hello my friend: {}".format(current_player.name))

main()

Output:
>>> python3 test.py
Option: 1
Name: Bill
Hello my friend: Bill

>>> python3 test.py
Option: 1
Name: Jill
Hello my friend: Jill

Note:
I suggest to get rid of the global variable usage. Pass the required variables as parameters. I have implemented a version which doesn't contain global variables.
def start():
    user_name = input("Name: ")
    # Assign the Player instance to the global variable.
    current_player = Player(name=user_name)
    start1(current_player)

def start1(current_player_info):
    # Get the "name" attribute of the "Player" object.
    print("Hello my friend: {}".format(current_player_info.name))

PS:
In your next question, do not attach or link pictures. Please add a minimal code and your issue (traceback). Please read it: https://stackoverflow.com/help/how-to-ask


text:
Q: Search Bar And Search Bar Controller Crashes By Just Tapping On It Ok this is the first time i am implementing a search bar. I have followed a couple of tutorials and started implementing it inside my project that contains a tableviewcontroller. Inside my Storyboard, I dragged and added a "Search Bar And Search Bar Controlller" above the custom tableview cell.
By default, if you just drag it inside your tableview controller and do nothing and just run the program and tap on the search bar, it won't do anything as there has been no implementation done.
But in my case, just by tapping on it, the program crash and shows the following:
2013-09-24 05:29:32.468 TechY[4189:a0b] *** Assertion failure in -[UISearchResultsTableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2903.2/UITableView.m:6235
2013-09-24 05:29:32.533 TechY[4189:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

So i am stopped here and can't do rest of the implementation. Can somebody point out what could be the problem? Thanks!

A: Well you need to take a look at your UITableViewDataSource's tableView:cellForRowAtIndexPath: and make sure you are returning a UITableViewCell. Most likely it is because your table view returns one when you run dequeueReusableCellWithIdentifier: but your UISearchDisplayController's tableView does not.
I end up running something like this:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil && tableView != self.tableView) {
    cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}


text:
Q: Given an array of x length, how can I find all the unique, non-repeating combinations of a fixed length? If I have the following array:
array(1,2,3,4,5)

How can I find all the unique, non-repeating, 3 selection combinations?
For instance, these would be valid values:
[1,2,3]
[1,2,4]
[1,2,5]

But this wouldn't be valid:
[1,3,2]

because it's the same as [1,2,3]

A: If you want to find all unique 3-tuples (without distinguishing the order (e.g. [1,2,3] is the same as [2,1,3])) you can do it with 3 nested for loops. The first one begins from the first element, the second for loop begins one element further each time, and so on.
$arr = array(1, 2, 3, 4, 5);

for ($i = 0; $i < count($arr) - 2; $i++) {
    $value = $arr[$i];
       for($j = $i+1; $j < count($arr) - 1; $j++) {
           $value2 = $arr[$j];
           for($k = $j+1; $k < count($arr); $k++) {
               $value3 = $arr[$k];
               echo "[".$value.",".$value2.",".$value3."]\n";
           }
       }
}

Output :
[1,2,3]
[1,2,4]
[1,2,5]
[1,3,4]
[1,3,5]
[1,4,5]
[2,3,4]
[2,3,5]
[2,4,5]
[3,4,5]

PS : The solution pointed out in @JuanLopes duplicate's question should be preferred as it is more general.


text:
Q: About Sobolev Space definition. I would like to know if this two definitions for Sobolev Spaces are equivalent:
$H_2^m([a,b]):=\{f: f',...,f^{(m-1)} \text{absolutely  continuous}, \int _a^b (f^{(m)})^2dx<\infty \}$
and  $H_2^m([a,b])$ contains all functions $f$ such that $D^\mu f \in L_2([a,b])$ for $\mu=0,1,...,m$
The first definition requires the $m$th derivative to be square integrable, while in the second one all derivatives (up to order m) must belong to $L_2([a,b])$ and no continuity is required.
I guess it has to do with the fact that absolute continuity is required, but I want to be sure that both are valid.
Any hint will be greatly appreciated.


text:
Q: Load picture from a .NET assembly resource in a simple HTML file? I have a .NET Server Control app that simply returns some HTML. I also need to embed several picture files into the assembly so that the HTML file can use them as its src= for each of them.
We will simply have a .HTML file that lives in the project as an embedded resource and the server control code will read this html and serve it up. Within THAT html, we will need to have all the picture src links (as well as CSS, js, etc) to point back to embedded resource files.
Does anyone know what code I would put in the HTML file for the pictures to make it point back to the embedded picture file?
I have to do this on a grand scale... hundreds of times. I really would like a programmatic approach to doing this so I can write a wrapper and never have to touch it again when we update the server control with new html, picture files, etc.
One might imagine a way to do this at compile time where I can loop through the embedded files with GetManifestResourceNames and then replace() the src links with the HTTP resource links I suppose?
Thank you for any guidance!

A: Hm, your question covers quite many aspects. Let me repeat to see if I got it: You have an assembly, with a raw HTML file in it. This file references some items, which are to be found within this same assembly, and you want to have them served to the client upon request as well.
One possible solution might be this.

*

*Instead of a raw HTML file, use a templated one. Then, feed all available resource names as proper URL's into the templating engine, to replace the placeholders.You may want to look at DotLiquid for this.

*Create a HTTP handler for each file type you want to serve. Inside the handler, you pull the item from the resources of the dll and serve them.

Alternatively, if those resources are rather small, you want to have a look into the data URI scheme, to save the extra requests and omit the handler. With this you could replace the placeholders with the data URI's directly, and serve a single HTML file with everything in it in the frist place.

A: Another choice is to have your .NET Server Control app check for optional GET arguments and return the image instead of the HTML.
Your original HTML request might be a simple:
GET netServerApp

Which returns the HTML with normal embedded links.
The HTML image links in the HTML might look like this:
<img src="netServerApp?src=Image1.svg">

or the like.  Your server app would then return the appropriate image, instead of the HTML.
It means several round trips to get everything, but that is normal for HTML anyway.


text:
Q: Removing the skip buttons from the flash source I am no flash expert however I need to edit the source of the flash project here: http://tools.assembla.com/1pixelout/browser/audio-player/
It's the "Wordpress audio player" I need to remove the skip forward and back buttons when there is more than one audio file.
Anyone know how to first of all use this folder structure, I thought it would simply be a .fla file that you edit but it seems to be loads of files. And then how do I compile it?
Thanks in advance,
Stefan

A: It appears to be FLA-based, meaning you will need to purchase a copy of Flash Professional (what version you need depends on the version of the FLA file).
It depends on how it was coded, either you need to edit the graphics / layout inside the FLA file, or you need to edit the code in one of the classes. The classes can either be embedded in the FLA file, or they can be in separate standalone AS files.


text:
Q: Why is it that period remains constant for an oscillation(SHM) experiencing light damping? It was stated during a physics lecture that a simple harmonic oscillation undergoing light damping would have a period that is slightly greater than it would be without damping but the new period would remain constant throughout. I don't understand it as it seems counter-intuitive that the period would remain constant. :(

A: The period stays constant because the solutions can be rescaled at will. So if you have some valid motion $\theta(t)$ describing the pendulum's angle $\theta$ as a function of time $t$, then you can scaled this motion up or down by any factor $s$ and still get a valid motion $s \theta(t)$. This scaling property follows from the niceness (specifically, linearity) of the underlying model. If you remove simplifying assumptions then you lose the scaling property.
Why does the scaling property mean the period is constant? Suppose you have a pendulum and release it from an angle $\theta_1$, then the pendulum will swing away and swing back to a maximum angle $\theta_2$ at some later time $T$. The motion after the time $T$ is the same as if you had simply released the pendulum from the angle $\theta_2$ But now you can use the scaling property to get the future motion of the pendulum. For example, the motion from $T$ to $2T$ must be $\dfrac{\theta_2}{\theta_1} \theta(t-T)$. In fact, this equation must hold for all $t>T$, therefore the pendulum must alway have zero velocity at integer multiples of $T$, and so it shouldn't be hard to believe that the period must be $T$ for all time.


text:
Q: Pass a struct as formal parameter when creating object .h:
class Note : public QWidget
{
    Q_OBJECT
public:
    explicit Note(Traymenu *trayMenuIn, int i = 0, QWidget *parent = 0);

.cpp:
Note::Note(Traymenu *trayMenuIn, int i, QWidget *parent) :

I am creating a new Note by this:
void Traymenu::newNote(){
    QSharedPointer<Note> note(new Note(this));
    m_noteList << note;

What do I have to write instead of int i = 0 and int i, if I want to pass a struct?
Before creating the note, I am building a structure like
struct properties {
     std::string title;
     int posX, posY;
}noteProp;

noteProp.title="name";

I tried passing that structure with struct properties notePropIn = 0 in the prototype, but I get the error cannot convert int 0 to struct. I need the 0 because this parameter is only used if a note gets loaded, not created the 1st time.
Then a new note should be created with
void Traymenu::newNote(){
    QSharedPointer<Note> note(new Note(this, noteProp));
    m_noteList << note;


text:
Q: oracle INACTIVE session is blocking active session need a way to find sqlid which is blocking I'm getting locks on oracle 11g database with information as follows
06112017:11:00:09    WELOPP@n1pv97/46581  (Session=('300,19867')Status=INACTIVE sqlid=>) blocking WELOPP@n1pv97/45876          (Session=('1803,10683')
                      Status=ACTIVE sqlid=fp5x2quh0zpqk) for the last 91850 seconds.

06112017:11:00:09    WELOPP@n1pv97/46581  (Session=('300,19867')Status=INACTIVE sqlid=>) blocking WELOPP@n1pv97/59864          (Session=('843,58185')
                       Status=ACTIVE sqlid=fp5x2quh0zpqk) for the last 5388 seconds.

How can an INACTIVE session can block an ACTIVE one?
How can I get more information on this INACTIVE session?

A: It's quite simple for an INACTIVE session to block an ACTIVE one.  First, the difference between ACTIVE and INACTIVE.
An ACTIVE session is simply one that is currently in a database call.  An INACTIVE session is not.  A simple example would be, if you have a database connection via SQL*Plus, and it's sitting at the SQL> prompt, that's an INACTIVE session.  As soon as you execute a SQL or PL/SQL statement, the session will become ACTIVE.
Now, as to how an INACTIVE session can block an ACTIVE one, well, that's pretty straightforward.
Imagine two SQL*Plus sessions, both sitting idle at SQL> prompt.  Both are INACTIVE.  Now, session 1 executes:
update taba set col2='Hello world' where col1=1;

Session 1 will momentarily become ACTIVE, and take a lock on the row(s) it updated, and return to INACTIVE state.
Now, what happens when Session 2 executes the same SQL?
It will try to update the same row(s), but will be blocked by the INACTIVE Session 1, which has not committed, and therefore continues to hold a lock.  Session 2, meanwhile, is still ACTIVE, and will remain blocked and remain ACTIVE until session 1 either commits or rolls back.


text:
Q: No picture with S-Video I have bought an S-Video cable so as that my old TV can be used as a second monitor, for watching iPlayer etc. I have an S-Video to Scart adaptor for the TV, Ubuntu knows there is a TV there and has set the correct resolution, but the TV shows no Picture??

A: NVIDIA GPU-based graphics cards with a TV-Out connector can use a television as another display device (the same way that it would use a CRT or digital flat panel). The TV can be used by itself, or in conjunction with another display device in a TwinView or multiple X screen configuration. If a TV is the only display device connected to your graphics card, it will be used as the primary display when you boot your system (i.e. the console will come up on the TV just as if it were a CRT).
Ubuntu Forums Configuring and Enabling TV out on Nvidia
Configuring TV-Out Nivdia


text:
Q: How to re-render a component when it changes its props async? I am using React and Redux in a project I've two components a parent and a child.
The parent component passes some props to the child when the child component receives those props it calls some action which change some of the props (async) that the parent passed to its child. Now my redux-store shows that the data has successfully stored in it. But my child component doesn't re-render itself.
Parent Component:
class Parent extends React.Component {
      getChilds(){
       let child = [];
       let i = 0;
       for (let keys in this.props.home.data) {
         child[i] = (
         <Child title={keys} data={this.props.home.data[keys]} key={keys} />
        );
         i++;
         if (i === 6) break;
       }

      return Rows;
      }
    render(){
     return (

I am gonna call my child

        {this.getChilds()}

)
      }
}

Child Component:
    class Child extends React.Component {
     // Here I'm not sure which lifecycle method to use to i'm gonna use
    // componentDidMount
    componentDidMount(){
      if(this.props.data.items.length === 0){
        // calling an action to fill this.props.data.items array with data
       this.props.getData(this.props.data.id);
      }
     }
     getGrandSong(){
     let grandSons = [];
     if(this.props.data.items.length > 0){
       grandSons = this.props.data.items.map( item => <GrandSon item={item}
                     />);
      }
     return grandSons;
     }
    render(){
      return (

 I am the child component and I will call my own child

        {this.getGrandSon()}

     )
   }

Props are updated when I check the props in react-dev tool.

A: You need the data to re-render whenever the prop changes, so you can call it on the render function and implement shouldComponentUpdate() to deeply compare props and call render().
So, in this case:
class Child extends React.Component {
    componentDidMount(){
      if(this.props.data.items.length === 0){
        // calling an action to fill this.props.data.items array with data
       this.props.getData(this.props.data.id);
      }
     }
    shouldComponentUpdate(nextProps){
        if(this.props.data.items.length === nextProps.data.items.length){
            for(let i=0; i< nextProps.data.items ; i ++){
                if(nextProps.data.items[i] !== this.props.data.items[i]) return true;
            }
        }
        return true;
    }
    render(){
        const getGrandSong = () => {
            let grandSons = [];
            if(this.props.data.items.length > 0){
                grandSons = this.props.data.items.map( item => <GrandSon item={item} />);
            }
            return grandSons;
        }
      return (

 I am the child component and I will call my own child

        {getGrandSon()}

     )
   }


text:
Q: How come the relation $\subseteq $ on the power set $2^N$ is antisymmetric? where $2^N$ is the power set with $n$ elements (subsets).
Does it hold true to any set or just the power set $2^N$?

A: By definition, two sets $A$ and $B$ are equal if and only if $A\subseteq B$ and $B\subseteq A$. Now a relation $R$ on a set $X$ is antisymmetric if $aRb$ and $bRa$ implies $a=b$ for all $a,b\in X$. Does this help you see why $\subseteq$ is antisymmetric?

A: Let me give an intuitive, not pure explanation. First, start out by understanding that antisymmetic means that for $x$ and $y$ of a set, $xRy$ implies $yRx$ is not the case, e.g., a bunch of males and none are brothers. So if we look at symmetric relations, i.e., symmetry is when $xRy$ does imply $yRx$, e.g., two different males, $x$ and $y$ satisfy the "is the brother of" relation. But again, symmetry assumes $x$ and $y$ are different, otherwise it's just reflexive, e.g., somebody is their own brother. In a way anti-symmetric is taking away the possibility that $x$ and $y$ are both different and symmetric, e.g., Josh and Will being brothers would be symmetric -- they're different guys and they're each other's brother. So insisting on the implication that Josh and Will are brothers, $xRy$ and $yRx$, only if they are the same person (one name is an alias?) flips the situation into antisymmetry. That is, when we insist $x$ and $y$ have to be the same element to be in a relation, we've taken away the possibility that any two elements of a relation can exhibit symmetry. So yes, we're still working in the context, language of symmetry, i.e., $xRy$, $yRx$, but creating exactly its opposite by insisting $x$ and $y$ must be the same thing (aliases) for $xRy$ and $yRx$ to hold; otherwise they're all in antisymmetric relationships. Long short, this is all just a round-about way of saying that if $xRy$ is true, then automatically $yRx$ is not true -- but doing it in a reductio ad absurdum way, I guess. Another example would be a set of natural numbers. Here "less than or equal to" is an antisymmetic relation on the set, and only when two different elements are actually the same are they also equal. I'm guessing all of this is necessary because math needs to have a precise way of giving the opposite of symmetry and not have it confused with asymmetry. Again, YMMV.


text:
Q: ASP.net Identity framework or Simple membership I am building ASP.net MVC 5 website which is having User login module as well.
Requirement is to store User custom information (ex: DOB, Email, Preferences, Security Question, Password & other information).
Whether I should use Simple Membership or ASP.net Identity framework or I should built a custom authentication module ?
-- I did search over Internet but didn't find sufficient information

A: For new applications being built with MVC 5, you should use ASP.NET Identity which is the new membership system for web apps. For more information on the features you can read this article http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity


text:
Q: CommonLibrary.NET repository and EF 4 working together? I would like to use CommonLibrary.NET in my project but I have legacy code and can't do Code First modeling, I use the VS2010 tool to generate my model from the DB.
But it seems that the out of the box entities that the design tool generated can't be used with the repositories in the CommonLibrary, It gives the error:

Error 1   The type 'RepositoryTest.UserInfo' cannot be used as type
  parameter 'T' in the generic type or method
  'ComLib.Entities.RepositorySql<T>'. There is no implicit reference
  conversion from 'RepositoryTest.UserInfo' to
  'ComLib.Entities.IEntity'.

Did anyone had this problem also, if so maybe there is a simple solution?
I would like also to know if anyone have a good alternative framework or project that implements repositories that support EF entities.
I am TDDing so I would like to have an implementation of a repository in memory in the same framework, This was the reason I choose this framework in the first place.

A: It looks that ComLib.Entities.RepositorySql<T> has a generic constraint, something like
public class RepositorySql<T> where T : IEntity
{
    // ...
}

This means that your Entity classes have to implement this interface ComLib.Entities.IEntity in order to be used as the generic type parameter of the repository. So your class must look like:
public class UserInfo : IEntity
{
    // implementation of IEntity
    // look in documentation what you have to implement
    // or hit ctrl-period in Visual Studio on IEntity
    // to get a default implementation

    // your custom code
}


text:
Q: How do I return only the matching regular expression when I select-string(grep) in PowerShell? I am trying to find a pattern in files. When I get a match using Select-String I do not want the entire line, I just want the part that matched.
Is there a parameter I can use to do this?
For example:
If I did
select-string .-.-.

and the file contained a line with:
abc 1-2-3 abc

I'd like to get a result of just 1-2-3 instead of the entire line getting returned.
I would like to know the Powershell equivalent of a grep -o

A: Instead of piping to % or select you can use simpler .prop Member Enumeration syntax, which magically works on multiple elements:
(Select-String .-.-. .\test.txt -All).Matches.Value

or less parentheses:
$m = Select-String .-.-. .\test.txt -All
$m.Matches.Value

A: Or just:
Select-String .-.-. .\test.txt -All | Select Matches

A: If you don't want to use ForEach operator, you can only use pipes and Select -Expand
For example, to get only the path after C:\, you could use :
Get-ChildItem | Select-String -Pattern "(C:\\)(.*)" | Select -Expand Matches | Select -Expand Groups | Where Name -eq 2 | Select -Expand Value

Where Name -eq 2 only selects the second match of the regex pattern specified.

A: David's on the right path.  [regex] is a type accelerator for System.Text.RegularExpressions.Regex
[regex]$regex = '.-.-.'
$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}
$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}

You could wrap that in a function if that is too verbose.

A: I tried other approach: Select-String returns property Matches that can be used. To get all the matches, you have to specify -AllMatches. Otherwise it returns only the first one.
My test file content:
test test1 alk atest2 asdflkj alj test3 test
test test3 test4
test2

The script:
select-string -Path c:\temp\select-string1.txt -Pattern 'test\d' -AllMatches | % { $_.Matches } | % { $_.Value }

returns
test1 #from line 1
test2 #from line 1
test3 #from line 1
test3 #from line 2
test4 #from line 2
test2 #from line 3

Select-String at technet.microsoft.com

A: You can use the System.Text.RegularExpressions namespace:
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

A: In the spirit of teach a man to fish ...
What you want to do is pipe the output of your select-string command into Get-member, so you can see what properties the objects have. Once you do that, you'll see "Matches" and you can select just that by piping your output to | **Select-Object** Matches.
My suggestion is to use something like: select linenumber, filename, matches
For example: on stej's sample:
sls .\test.txt -patt 'test\d' -All |select lineNumber,fileName,matches |ft -auto

LineNumber Filename Matches
---------- -------- -------
         1 test.txt {test1, test2, test3}
         2 test.txt {test3, test4}
         3 test.txt {test2}

A: None of the above answers worked for me. The below did.
Get-Content -Path $pathToFile | Select-String -Pattern "'test\d'" | foreach {$_.Matches.Value}

Get-Content -Path $pathToFile | # Get-Content will divide into single lines for us

Select-String -Pattern "'test\d'" | # Define the Regex

foreach {$_.Matches.Value} # only return the value of the Object's Matches field. (This allows for multiple result matches.)


text:
Q: Create DDL Trigger Dynamically I'm trying to create a DDL Trigger dynamically so I can create a job that checks each database and creates the trigger if it's not already in place. To do this, I'm using sp_foreachdb. The code works on it's on but I can't get it to work with sp_foreachdb so I'm guessing I've missed a single quote. However, I'm struggling to find the error. Any help is greatly appreciated.
EXEC master.dbo.sp_foreachdb
'
IF NOT EXISTS (SELECT * FROM sys.triggers T WHERE T.name =
''Database_DDL_Audit'') AND ''?'' <> ''TempDB''
BEGIN
EXEC
(
''
CREATE TRIGGER Database_DDL_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
BEGIN
DECLARE @EventDataXml   XML
DECLARE @SchemaName     SYSNAME
DECLARE @ObjectName     SYSNAME
DECLARE @EventType      SYSNAME

SET @EventDataXml = EVENTDATA()

SELECT
@EventType  = @EventDataXml.value(''''(/EVENT_INSTANCE/EventType)[1]'''', ''''SYSNAME'''')
, @SchemaName = @EventDataXml.value(''''(/EVENT_INSTANCE/SchemaName)[1]'''', ''''SYSNAME'''')
, @ObjectName = @EventDataXml.value(''''(/EVENT_INSTANCE/ObjectName)[1]'''', ''''SYSNAME'''')

INSERT [ServerAdmin].[dbo].[ServerChangeLog]
(
[CreateDate]
, [LoginName]
, [ComputerName]
, [ProgramName]
, [DBName]
, [SQLEvent]
, [SchemaName]
, [ObjectName]
, [SQLCmd]
, [XmlEvent]
)
SELECT  GETDATE()
        , SUSER_NAME()
        , HOST_NAME()
        , PROGRAM_NAME()
        , @EventDataXml.value(''''(/EVENT_INSTANCE/DatabaseName)[1]'''', ''''SYSNAME'''')
        , @EventType
        , @SchemaName
        , @ObjectName
        , @EventDataXml.value(''''(/EVENT_INSTANCE/TSQLCommand)[1]'''', ''''NVARCHAR(MAX)'''')
        , @EventDataXml
''
)
END
'

The error I'm getting is

Msg 102, Level 15, State 1, Procedure Database_DDL_Audit, Line 40 [Batch Start Line 0]
  Incorrect syntax near '@EventDataXml'.

A: You are missing an END. See updated as below:
Note: Use Aaron's version of sp_msforeachdb
declare @sql nvarchar(max)

set @sql = '
IF NOT EXISTS (SELECT * FROM sys.triggers T WHERE T.name =
''Database_DDL_Audit'') AND ''?'' <> ''TempDB''
BEGIN
EXEC
(
''
CREATE TRIGGER Database_DDL_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
BEGIN
DECLARE @EventDataXml   XML
DECLARE @SchemaName     SYSNAME
DECLARE @ObjectName     SYSNAME
DECLARE @EventType      SYSNAME

SET @EventDataXml = EVENTDATA()

SELECT
@EventType  = @EventDataXml.value(''''(/EVENT_INSTANCE/EventType)[1]'''', ''''SYSNAME'''')
, @SchemaName = @EventDataXml.value(''''(/EVENT_INSTANCE/SchemaName)[1]'''', ''''SYSNAME'''')
, @ObjectName = @EventDataXml.value(''''(/EVENT_INSTANCE/ObjectName)[1]'''', ''''SYSNAME'''')

INSERT [ServerAdmin].[dbo].[ServerChangeLog]
(
[CreateDate]
, [LoginName]
, [ComputerName]
, [ProgramName]
, [DBName]
, [SQLEvent]
, [SchemaName]
, [ObjectName]
, [SQLCmd]
, [XmlEvent]
)
SELECT  GETDATE()
        , SUSER_NAME()
        , HOST_NAME()
        , PROGRAM_NAME()
        , @EventDataXml.value(''''(/EVENT_INSTANCE/DatabaseName)[1]'''', ''''SYSNAME'''')
        , @EventType
        , @SchemaName
        , @ObjectName
        , @EventDataXml.value(''''(/EVENT_INSTANCE/TSQLCommand)[1]'''', ''''NVARCHAR(MAX)'''')
        , @EventDataXml
END
''
)
END
'
print @sql


text:
Q: Ninject + ASP.NET MVC + InRequestScope I have a problem with the Ninject.
My binding rules:
this.Bind<ISphinxQLServer>().To<SQLServer>();
this.Bind<IMySQLServer>().To<SQLServer>();

this.Bind<ISQLLogger>().To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();

this.Bind<SQLServer>().ToSelf()
    .InRequestScope()
    .WithConstructorArgument("connections", Kernel.Get<DatabaseConnections>())
    .WithConstructorArgument("logger", Kernel.Get<ISQLLogger>());

Where
SQLServer, ISphinxQLServer and IMySQLServer are:
public class SQLServer: ISphinxQLServer, IMySQLServer
{
    public DatabaseConnections Connections { get; internal set; }
    public ISQLLogger Logger { get; internal set; }

    public SQLServer(DatabaseConnections connections)
    {
        this.Connections = connections;
    }

    public SQLServer(DatabaseConnections connections, ISQLLogger logger)
    {
        this.Connections = connections;
        this.Logger = logger;
    }
}

I want that each user request to my asp.net mvc site creates a single SQLServer, a single ISQLLogger and a single DatabaseConnections. But my solution dont work. What am I doing wrong? =(

A: You don't need to specify the WithConstructorArgument. Resolving the parameters to the constructors of your injected objects is part of what Ninject does for you. So the definitions should look more like this:
this.Bind<SQLServer>()
    .ToSelf()
    .InRequestScope();

this.Bind<ISphinxQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<IMySQLServer>()
    .ToMethod( x => x.Kernel.Get<SQLServer>() );

this.Bind<ISQLLogger>()
    .To<StandardSQLLogger>()
    .InRequestScope();

this.Bind<DatabaseConnections>()
    .ToMethod(x => ConnectionFactory.GetConnections())
    .InRequestScope();


text:
Q: How to pyUSB inside Processing's python mode I am programming inside Processing.py and need to use pyUSB. I placed the downloaded files of pyUSB in the sketch folder and then run in the sketch
    import usb.core
    import usb.util
    import usb.control

Which runs successfully, however when I try to initialize the device I'm trying to communicate with, I get the error "No module named util" on the command below
   device = usb.core.find(idVendor=VENDOR_ID,
                               idProduct=PRODUCT_ID)

I don't know whether pyUSB is installed successfully. If anyone has installed this before please comment.

A: Python Mode for Processing cannot use any Python libraries that depend on native code, such as pyUSB.


text:
Q: Error when open up Eclipse Juno I want to ask a simple question. When I open up Eclipse Juno there is a pop out error box saying that :
 'Running Android Lint' has encountered a problem.
  Failed.

What could be the problem?

A: The problem is solved! This is due to runtime error is some project. This is also might be too much of runtime error. So, you guys need to solved the problem or if the project that contains error is no longer used just delete the project.


text:
Q: Truncating variable MATLAB I'm working with an array A in MATLAB. The values in this array have up to 5 decimals. I would like to truncate those values to a less number of decimal.
Is there a way to accomplish this?
Thanks!

A: Rounding Digits:
To round a value (or matrix) to given number of decimal places, use round, for example to 2 decimal places...
round(1.2345, 2)

ans = 1.2300

To also not display the trailing zeros, first change the format to shortg
format shortg

round(1.2345, 2)

ans = 1.23

The format compact can achieve similar results, choose the best one to suit your needs based on the documentation below.
Documentation:
Round: https://uk.mathworks.com/help/matlab/ref/round.html
Format: https://uk.mathworks.com/help/matlab/ref/format.html

A: For some reason, Matlab's "truncate" function is called fix. So
>> fix(3.5)
ans = 3

>> fix(-3.5)
ans = -3

To truncate, round, floor, or ceil anything to a given number of decimals, multiply by powers of tens, truncate, round, floor, or ceil, and then divide the result by powers of tens.
So:
>> fix(123.456 * 10^2)
ans = 12345

>> ans / 10^2
ans = 123.45


text: Q: vibrations of higher dimensional drums The solutions of the wave equation for a circular drum with fixed boundary are well known.  What do the solutions look like for a spherical drum in three spatial dimensions?  What about higher dimensions?


text:
Q: presentModalViewController:animated:NO displaying 20 pixel gap I begin with a view-based app template. In the automatically created viewcontroller's xib (call it VC1), I add a button, and define in its interface/implementation:
- (IBAction)showVC2;

- (IBAction)showVC2 {
      [self presentModalViewController:[[VC2 alloc] init] animated:NO];
}

I then create VC2. In both implementations, I allow only landscape orientations. In both xibs, I set the views to landscape. In the info.plist file, I specify starting orientation as landscape right.
When I run the project in the simulator and press the button in VC1, VC2 is displayed, but a 20 pixel gap shows both on the lower edge and on the right edge. Notably, rotation causes the view to be placed correctly on screen after rotation completes.
This issue is similar to others:
1 2 3, though the solutions identified do not seem to work in the present case. The correct/expected behavior occurs if the modal view is presented with animation (I do not want the transition animated, however). This issue has persisted since last summer (iOS 3.1.3?). It continues with 4.3. The issue does not occur in portrait orientation.
Can anyone provide a solution or explanation for why such a simple modal viewcontroller presentation does not give the expected result?
EDIT: Xcode project

A: I just tried building what you suggested and have no problems with a gap. I don't know if there is a way for you to post all of your code or your project. If you can do that I will try and help.


text:
Q: Error building ios platform in Cordova 6.4.0 Cordova create and add platform works fine but get error message while building in ios. i have Xcode 7.3.1 and cordova 6.4.0 mac version is 10.11
Error: xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

A: Solved this issue
$ sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer


text:
Q: How to set 2 shipping options I require 2 options for shipping to be set in magento 2.18.
First option is Home delivery @ £1
Second Option is using a delivery company by weight
is this possible?

A: Yes! Please read the following links from Magento2 docs for setting up your shipping methods:

*

*First option: Flat rate

*Second option: Dimensional weight


text:
Q: Async RenderAction I have a layout that calls several @Html.RenderAction in the layout
eg
@{ Html.RenderAction("TopPane", "Controller"); }
<div class="content-pane">
    @RenderBody()
</div>
@{ Html.RenderAction("BottomPane", "Controller"); }

Sometime the top pane can take a bit of time to render. Is it possible to make the render action async, eg
public class PartialAsyncController : AsyncController
{
    private long dt;
    public PartialAsyncController()
    {
        dt = DateTime.Now.Ticks;
    }

    public async Task<PartialViewResult> TopPane()
    {
        return PartialView(dt);
    }

    public async Task<PartialViewResult> BottomPane()
    {
        return PartialView(dt);
    }

}

I'd like to avoid using the ajax approach to rendering the top and bottom pane because they share expensive content that is scoped to once per request


text:
Q: Размер текста в TextView Здравствуйте! Хотелось бы узнать, как реализовать возможность того, чтобы в одной строке TextView использовался обычный текст и "ЖИРНЫЙ" текст. Сейчас использую данный способ:
<TextView
        android:id="@+id/1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/razmer0"
        android:isScrollContainer="true" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/2"
        android:isScrollContainer="true"
        android:textSize="@dimen/Razmer1"/>

в java- коде прописываю следующее:
    TextView text1 = (TextView)findViewById(R.id.1);
    en_text1.setText("123");
    TextView en_text2 = (TextView)findViewById(R.id.2);
    en_text2.setTypeface(null, Typeface.BOLD);
    en_text2.setText("456");

Если делать таким способом, то в первой строке будут обычные цифры 123, а в следующей строке будут "жирные" цифры 456. Вопрос заключается лишь в том, как можно сделать (и можно ли вообще) чтобы 123(простые) и 456(жирные) были на одной строке. Если говорить по-другому, то как сделать так чтобы в обычном тексте можно было выборочно сделать "жирные" слова и при этом не происходил переход на следующую строку?

A: Например так:
 TextView text1 = (TextView)findViewById(R.id.1);
 en_text1.setText(Html.fromHtml("" + "жирный" + "" +
        "" + "маленький" + ""));

A: Можно так еще, через spannable
SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");

    final StyleSpan boldSpanStyle= new StyleSpan(android.graphics.Typeface.BOLD);
    final StyleSpan normalSpanStyle = new StyleSpan(Typeface.NORMAL);
    sb.setSpan(boldSpanStyle, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    sb.setSpan(normalSpanStyle, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(sb);

A: Если вам необходимо условие на изменение стиля шрифта конкретного слова, то вот:
(работает с любыми символами и цифрами)
String text="Ваш текст";
Spannable span1 = new SpannableString(text); //основной (для вывода текста)
Spannable span2 = new SpannableString(text); //изменяемый (нужен для цикла)
String path="текст"; //слово которое необходимо изменить
int startIndexOfPath = span2.toString().indexOf(path); //получаем начальный индекс слова в тексте

while (startIndexOfPath!=-1) { //если есть совпадение по тексту, то выполняется цикл:

span1.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), //меняем стиль слова на "жирный"
              startIndexOfPath, startIndexOfPath + path.length(), 0);

StringBuilder sTextBuilder = new StringBuilder(span2); //создаем StringBuilder

//заменяем найденное слово на любые другие символы в таком же кол-ве как само слово
//например в слове текст 5 символов, поэтому меняем на 5 других символов
//(нужно если в тексте несколько совпадений)

sTextBuilder.replace(startIndexOfPath, startIndexOfPath + path.length(),"12345");

span2=new SpannableString(sTextBuilder); //присваиваем измененный текст

startIndexOfPath = span2.toString().indexOf(path); //снова получаем начальный индекс слова в тексте
}

textView.setText(span1); //выводим в textView конечный результат

Спасибо за внимание. Если ответ вам помог, то отметьте его как правильный.


text:
Q: Visual Studio Community freezes on creating new Xamarin project on macOS I tried to create a "HelloWorld" project with Xamarin on macOS and the wizard stops on the following step:

I can see that in the background it's initializing my new project - I can see the Solution panel with new files appearing but the wizard window can't be dismissed. I waited enough time in my opinion so I should have it finished. I suppose that it might be hanging because of some permissions or networking timeout - I was using "Native App (iOS, Android)" template.
Is there anything I can do to avoid it? When I closed the wizard window, it looked that I had a incompletely initialized project: a lot of packages was missing, so I guess it might be something connected to networking timeouts or permissions.
When I added those Packages, my iOS target works fine, but I still have a problem with Android.

A: I decided to start it from scratch and it turned out to fix my problems with dependencies and freezing on a project's initialization.
I suppose that adding packages manually unlocked something that blocked automatic package adding on startup. Previously when I tried to go with the wizard several times in row I got the same result - it froze on initialization and the dependencies were missing. Now when I use the same template, it works fine every time.
That's weird but maybe it will help someone. When it hangs on initialization of a template and the dependencies are missing, try to add them manually and then init from the template again.


text:
Q: Matplotlib scatter plot failed to display all legends (some are missing) In my data, they are 23 classes in total.
all_classes = ['E6Tle4', 'E2Rasgrf2', 'InV', 'E4Thsd7a', 'E3Rmst', 'E3Rorb','E5Galnt14', 'Clau', 'E4Il1rapl2', 'E5Parm1', 'OPC', 'Mis', 'E5Sulf1', 'Ast', 'OliM', 'E5Tshz2', 'InS', 'InN', 'InP', 'OliI', 'Endo', 'Mic', 'Peri']

I want to make scatter plots for points with these classes as label. However, the legend only showed 9 classes.
Here is a toy example to reproduce the err.
a = np.random.rand(23)/23
size= 2000
df = pd.DataFrame(
    {'x': np.random.rand(size),
    'y': np.random.rand(size),
     'classes': np.random.choice(all_classes, size, p=a/sum(a))
    })
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df["label"] = le.fit_transform(df["classes"])

fig, axes = plt.subplots(1, 3, figsize=(10,3))
fig.suptitle("true label")
ax1 = axes[0]
vis(ax1, df, df["label"], df["classes"], title="RNA")
fig.tight_layout()
fig.subplots_adjust(top=0.85)

def vis(ax, df, label_num, label_name, alpha=0.7, s=10, title="visualization", vis=False):
    points = ax.scatter(df.iloc[:, 0], df.iloc[:, 1], c=label_num, label=label_name, edgecolor='none',alpha=0.7, s=s)
    ax.spines["top"].set_visible(vis)
    ax.spines["right"].set_visible(vis)
    ax.set_title(title)

    ax.legend(handles=points.legend_elements()[0], labels=list(np.unique(label_name)),
              title="Classes", loc='center left', bbox_to_anchor=(1, 0.5))

Using the following code we can confirm that the column classes contains 23 classes.
len(df["classes"].unique())  # return 23

However, you can see that only 9 classes are shown in the legend.

A: You can set the num parameter in the handles=points.legend_elements()[0] call:
ax.legend(handles=points.legend_elements(num=len(all_classes))[0],...)

You'll need to edit the sizes of course, say with a single axes of figsize = (7,7) you get:

See the documentation here (which granted is kind of tucked away).  I guess by default the parameter is set to num="auto" which is vaguely automatic, but seems like it just sets a cutoff which is fine for most datasets.


text:
Q: Azure Function with KEDA Not scaling out I am experimenting with Azure Function and Kubernetes with KEDA. i deployed my function to Kubernetes and its working fine.
But when i wanted to test out scaling , it says the following error
Name:                                    keda-hpa-techshare
Namespace:                               default
Labels:                                  <none>
Annotations:                             <none>
CreationTimestamp:                       Thu, 14 May 2020 12:51:56 +0530
Reference:                               Deployment/techshare
Metrics:                                 ( current / target )
  "queueLength" (target average value):  <unknown> / 5
Min replicas:                            1
Max replicas:                            100
Deployment pods:                         1 current / 0 desired
Conditions:
  Type           Status  Reason                   Message
  ----           ------  ------                   -------
  AbleToScale    True    SucceededGetScale        the HPA controller was able to get the target's current scale
  ScalingActive  False   FailedGetExternalMetric  the HPA was unable to compute the replica count: unable to get external metric default/queueLength/&LabelSelector{MatchLabels:map[string]string{deploymentName: techshare,},MatchExpressions:[],}: unable to fetch metrics from external metrics API: the server could not find the requested resource (get
queueLength.external.metrics.k8s.io)
Events:
  Type     Reason                        Age                     From                       Message
  ----     ------                        ----                    ----                       -------
  Warning  FailedGetExternalMetric       8m53s (x332 over 129m)  horizontal-pod-autoscaler  unable to get external metric default/queueLength/&LabelSelector{MatchLabels:map[string]string{deploymentName: techshare,},MatchExpressions:[],}: unable to fetch metrics from external metrics API: the server could not find the requested resource (get queueLength.external.metrics.k8s.io)
  Warning  FailedComputeMetricsReplicas  4m4s (x351 over 129m)   horizontal-pod-autoscaler  Invalid metrics (1 invalid out of 1), last error was: failed to get queueLength external metric: unable to get external metric default/queueLength/&LabelSelector{MatchLabels:map[string]string{deploymentName: techshare,},MatchExpressions:[],}: unable to fetch metrics from external metrics API: the server could not find the requested resource (get queueLength.external.metrics.k8s.io)

I have tried redeploying the image as well. Any help?


text:
Q: Socket Injection (Theoretical)
Ok, so we have our data. Our data is a raw DNS Packet data, with all the information that is needed to tell the DNS to connect to a server, including the header, etc
[Data]

But the socket that we are allowed to use is only AF_INET and SOCK_DGRM. So when it sends it will not end up using the data as we intended, it would be like:
[HEADER]
[Data]
[END HEADER]

My question is: Is it possible to include some sort of data, so that when the socket sends, it would make it a raw socket? (AKA Socket Injection?)
Example:
[HEADER]
[Fake END HEADER w/ Data]
[END HEADER]

A:
Is it possible to include some sort of data, so that when the socket sends, it would make it a raw socket?

No it's not. By design the data you write to a normal socket (i.e. SOCK_DGRAM, SOCK_STREAM) are just the payload of the UDP or TCP packet and gets not interpreted in any way by the kernel or by Python.
Thus if this would be possible then it would be a bug.


text:
Q: LabDefaultTemplate-> ExecuteRemoteTestRun2 doesn't take in account the Order field of the test in the MTM The Scenario:

*

*Create 2 codedui tests. First Test will be Test1 and the second Test2.

*Create 2 test cases in the mtm.

*Create 2 suites in the MTM. Suite1 and Suite2.

*Add to Suite1 the tests in the following order, Test1 then Test2.

*Add to Suite2 the tests in the following order, Test2 then Test1.
Now create a build with the template "LabDefaultTemplate" In the Tests add Suite1 and Suite2
Now Use the MTM and change the order of the tests in the suites and run the build again.
The Test Agent run the tests in the Suites in the order they where inserted and will not use the order field.
We user Test controller 2013, Test Agent 2013 , TFS 2013.
Now for the Details.
The WorkFlow LabDefaultTemplate runs the following activity "ExecuteRemoteTestRun2"
In the method TestRunCreation.CreateTestRun the test point is requested according to the suite and configuration
We can see that the Select has no "Order by" and this is the reason we got the test no in the order of the Test in the Suite.
  private ITestRun CreateTestRun(CodeActivityContext context, ITestManagementService testManager, ITestManagementTeamProject project)
      {
....

foreach (ITestPoint point in (IEnumerable<ITestPoint>) this.plan.QueryTestPoints(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "SELECT * FROM TestPoint WHERE SuiteId={0} AND ConfigurationId={1}", new object[2]
              {
                (object) testSuiteId,
                (object) this.TestParameters.Get((ActivityContext) context).TestConfigurationId
              })))
              {
                flag = true;
                testRun.AddTestPoint(point, (TeamFoundationIdentity) null);
              }

I think it is a bug, Can someone approve it?
What is the workaround for execution of suite in the order of the MTM.
Barak


text:
Q: With modern social networking and scaling, can Cassandra replace the standard relational database such as MySQL? Is it possible to build the entire social networking application on cassandra?
Sure, it takes longer to set up, but it scales much better.  Correct?
Please list the situations when Cassandra should be used.

A: Cassandra is in use at Digg, Facebook, Twitter, Reddit, Rackspace, Cloudkick, Cisco etc. so the answer to your first question would be yes.
The short version of the list that describes the situations in when Cassandra should be used.

*

*You need the possibility to add new
nodes to yout cluster, with no downtime.

*You need a richer data model (column
oriented) than simple key/value

*You need the possibility to have both
synchronous and asynchronous
replication for each update.

A: yes, Cassandra is really highly used and showing its performance at Digg, Facebook, Twitter, Reddit, Rackspace, Cloudkick, Cisco etc. and its really scalable nosql database with a tiny code base and memory consumption so its will be really nice choice for big 24-7-365 web-projects and for reference you can see at
http://www.datastax.com/dev/blog/why-does-scalability-matter-and-how-does-cassandra-scale
http://www.slideshare.net/scode/scaling-with-apache-cassandra/

A: To briefly summarize Brewer's CAP Theorem, your database is going to give you at most two of the following three properties:

*

*Consistency

*Availability

*Partition Tolerance
A relational database such as SQL Server or MySQL will give you consistency and sacrifices either availability or partition tolerance. A distributed database such as Cassandra will sacrifice consistency to give you both availability and partition tolerance.
So in short, use Cassandra if you don't need immediate consistency and are OK with eventual consistency.


text:
Q: How do you get the mean and std of a column in a csr_matrix? I have a sparse 988x1 vector (a column in a csr_matrix) created through scipy.sparse. Is there a way to gets its mean and standard deviation without having to convert the sparse matrix to a dense one?
numpy.mean seems to only work for dense vectors.

A: Since you are performing column slicing, it may be better to store the matrix using CSC rather than CSR. But that would depend on what else you are doing with the matrix.
To calculate the mean of a column in a CSC matrix you can use the mean() function of the matrix.
To calculate the standard deviation efficiently is going to involve just a bit more effort. First of all, suppose you get your sparse column like this:
col = A.getcol(colindex)

Then calculate the variance like so:
N = col.shape[0]
sqr = col.copy() # take a copy of the col
sqr.data **= 2 # square the data, i.e. just the non-zero data
variance = sqr.sum()/N - col.mean()**2


text:
Q: Feasibility of making a synchronous call to FIleSystem from chrome.webRequest callbacks set up as "blocking" I am writing a Chrome extension which listens for chrome.webRequest events, some are set up for blocking, so that I can cancel the request.  I need to be able to make a SYNCHRONOUS call from within the chrome.webRequest callback, which writes to the HTML5 FileSystem.  Is there any way to accomplish this synchronously, i.e., so that I have my result of the FileWrite before I return from the chrome.WebRequest callback?

A: I don't think so.
Some webRequest calls can be made synchronous, but file operations in FileSystem API are asynchronous and JS can't "wait" for async operations in a blocking manner.


text:
Q: Write the vector field such that its integral curves are the meridians of $S^2$ I have problems in  writing down a vector field $X$ on the sphere $S^2$ such that the integral curves of $X$ are the meridians of $S^2$.
I proceed in this way.
I consider this parametrisation of $S^2$: $$ x=\cos(\varphi) \cos(\alpha),$$$$ y=\cos(\varphi) \sin(\alpha), $$ $$ z=\sin(\varphi) .$$
A meridian is a curve:
$$\sigma(t)=(\sigma_1(t),\sigma_2(t),\sigma_3(t)) =(\cos(\varphi+t) \cos(\alpha),\cos(\varphi+t) \sin(\alpha),\sin(\varphi+t)).$$
Then I have that:
$$\dot\sigma_1(t)=\cos(\alpha)\sin(\varphi+t)$$
$$\dot\sigma_2(t)=-\sin(\alpha)\sin(\varphi+t)$$
$$\dot\sigma_1(t)=\cos(\varphi+t)$$
Now, in order to find the components of the vector field, should I calculate these derivates for $t=0$ ? In this way is the vector field written in respect to the basis $\partial x$, $\partial y$, $\partial z$?
My ideas are quite confused. Thanks for the help!


text:
Q: Finding URL on which the form was filled I have set up a simple email id form which is reused on various pages. I have currently set up a mail to me each time the form is filled which includes the mail id filled by the person. However, I would also like to know which page (URL) the person filled the form on, as that would help our sales team get more context.
I tried to do this by including a hidden field:

<input type="hidden" id="msg" name="message" value="my_hidden_field">

Then I included a script at the end of the page:
function setWindowURL(){
  current_URL = window.location.href;
  document.getElementById('msg').value = current_URL;
  console.log(document.getElementById('msg').value);
}

I then included this parameter in the mail that I sent to myself (accessing using forms' POST API):

html: '
Email: '+req.body.email+'URL: '+req.body.message // html

I saw that the console was showing the right information, but the mail was just sending "my_hidden_field" as the value of the URL. I assumed that this would be because the script ran before the page had loaded, so added a body.onload as well:

However, even this isn't helping out.
When I logged req.body, this is what I saw on the server logs: { email: 'example@gmail.com', message: 'my_hidden_field' }
I would just like to receive the mail id and the URL on which the form was filled. Any thoughts on this?

A: My bad. I was using the same id multiple times on the page which was causing this error. Otherwise, the above implementation works.


text:
Q: Spring Boot 2 Embedded Tomcat Jndi Datasource Configuration Good morning in my timezone
I already have follow this two Stack Overflow questions :
Spring Boot Using Embedded Tomcat with JNDI
and
Howto use JNDI database connection with Spring Boot and Spring Data using embedded Tomcat?
And none have worked.
I am using Spring Boot 2.
I want to configure embedded Tomcat Server to work with JNDI.
I have try to approaches :
Snippet of code :
 @SpringBootApplication
   public class MyApplication {

    public static void main ...

    @Bean
   public ServletWebServerFactory servletContainer() {      TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {

     @Override
     protected void postProcessContext(Context context) {
                    ContextResource resource = new ContextResource();
                    resource.setName("jdbc/CCC");
                    resource.setType(DataSource.class.getName());
                    resource.setProperty("driverClassName", "oracle.jdbc.driver.OracleDriver");
                    resource.setProperty("url", "jdbc:oracle:thin:@a77k11111188.tt.ddd.test:3000:BHJR00TT00");
                    resource.setProperty("username", "user");
                    resource.setProperty("password", "pass");
                    context.getNamingResources().addResource(resource);             }

     @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat){
                    tomcat.enableNaming();
                    TomcatWebServer container =  super.getTomcatWebServer(tomcat);
                    for(Container child  :container.getTomcat().getHost().findChildren()){
                        if (child instanceof Context) {
                            ClassLoader contextClassLoader = ((Context)child).getLoader().getClassLoader();
                            Thread.currentThread().setContextClassLoader(contextClassLoader);
                            break;
                        }
                    }
                    return container;           }

            };      return tomcat;

An then use the application.properties
spring.datasource.jndi-name=java:comp/env/jdbc/CCC

Error log:
 Unable to start embedded Tomcat
Error creating bean with name 'servletEndpointRegistrar'
Error creating bean with name 'dataSource'
 DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'java:comp/env/jdbc/CCC'
.NamingException: Could not create resource factory instance
ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
Instead if i not use the application properties and i configure the datasource bean directly in the Spring Boot Application like this
@Bean(destroyMethod = "")
    public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("java:comp/env/jdbc/CCC");
        bean.setProxyInterface(DataSource.class);
        bean.setLookupOnStartup(false);
        bean.afterPropertiesSet();
        return (DataSource) bean.getObject();
    }

The error log
UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'
BeanCreationException: Error creating bean with name 'jpaVendorAdapter'
JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object
NamingException: Could not create resource factory instance
In my pom i have the following dependecies
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
     <groupId>com.oracle</groupId>
     <artifactId>ojdbc7</artifactId>
     <version>12.1.0.2</version>
   </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

I am out of solutions
Thanks in advance
Best regards

A: I was also facing the same issue and most of the example on internet was using
TomcatEmbeddedServletContainerFactory however after trying several things finally i was able to get jndi connection in my application.
I am still figuring out exact root cause of the problem but following is the code for your reference.
@SpringBootApplication
public class MybatisJNDISampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisJNDISampleApplication.class, args);
    }

    @Bean
    public TomcatServletWebServerFactory tomcatFactory() {
        return new TomcatServletWebServerFactory() {
            @Override
            protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
                tomcat.enableNaming();
                return super.getTomcatWebServer(tomcat);
            }

            @Override
            protected void postProcessContext(Context context) {
                ContextResource resource = new ContextResource();
                //resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
                resource.setName("jdbc/myDatasourceName");
                resource.setType(DataSource.class.getName());
                resource.setProperty("driverClassName", "oracle.jdbc.OracleDriver");
                resource.setProperty("url", "db_url");
                resource.setProperty("username", "db_username");
                resource.setProperty("password", "db_password");
                context.getNamingResources().addResource(resource);
            }
        };
    }
}

Following is my configuration class :
@Configuration
@MapperScan("com.sample.mybatis")
public class DataConfig {

    public final String MAPPER_LOCATIONS_PATH = "classpath:mybatis-mappers/*.xml";

    @Bean(destroyMethod="")
    public DataSource dataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("java:comp/env/jdbc/myDatasourceName");
        //bean.setResourceRef(true); // this was previously uncommented
        bean.setProxyInterface(DataSource.class);
        //bean.setLookupOnStartup(false); // this was previously uncommented
        bean.afterPropertiesSet();
        return (DataSource)bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() throws NamingException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        configureSqlSessionFactory(sessionFactory, dataSource());
        return sessionFactory.getObject();
    }

    public void configureSqlSessionFactory(SqlSessionFactoryBean sessionFactoryBean, DataSource dataSource) throws IOException {
        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(pathResolver.getResources(MAPPER_LOCATIONS_PATH));
    }
}

Hope this helps you to resolve your issue.


text:
Q: UnsafeMutablePointer returned by vDSP_fft_zip being overwritten immediately In Swift 4 I'm creating a DSPSplitComplex to use in vDSP_fft_zip(), but it's being immediately overwritten the next time I create another DSPSplitComplex.
( DSPSplitComplex structure has 2 UnsafeMutablePointer<Float> )
//--Create the DSPSplitComplex
var A = [Float](repeating:0, count:32);
var B = [Float](repeating:0, count:32)
var splitComplex1 = DSPSplitComplex(realp: &A, imagp: &B)

//--Perform fft
log2Size = vDSP_Length(log2f(Float(32)))
setupFFT = vDSP_create_fftsetup(log2Size, FFTRadix(FFT_RADIX2))!;
vDSP_fft_zip(setupFFT, & splitComplex1, 1, log2Size, FFTDirection(FFT_FORWARD));

//--Create another DSPSplitComplex
var C = [Float](repeating:0, count:32);
var D = [Float](repeating:0, count:32)
var splitComplex2 = DSPSplitComplex(realp: &C, imagp: &D)

I can now see in the debugger that the UnsafeMutablePointer of splitComplex2.realp is the same address as splitComplex1.realp, and consequently anything I do with splitComplex2 overwrites splitComplex1
I guess the clue might be in the title 'unsafe', but if it's actually unusable, then what is the correct strategy for storing the contents of the returned DSPSplitComplex?
I guess creating new [Float] arrays from them is a way to make a permanent copy
let arrary = Array(UnsafeBufferPointer(start: splitComplex1.realp, count: 32))

...but it seems, despite reading the Swift docs, I'm still misunderstanding the point of UnsafeMutablePointer, as why would vDSP_fft_zip() return something that is unusable from the get-go?

A: Your way of creating DSPSplitComplex is wrong.
When you pass Array<Float> to UnsafeMutablePointer<Float> using &, the address passed to the function is only valid within the function.
So, in your code, two addresses passed DSPSplitComplex(realp: &A, imagp: &B) are not valid when the initializer of DSPSplitComplex finished.
To avoid this sort of behavior, you can try something like this:
var A = [Float](repeating:0, count:32)
var B = [Float](repeating:0, count:32)
A.withUnsafeMutableBufferPointer {aumbp in
    B.withUnsafeMutableBufferPointer {bumbp in
        var splitComplex1 = DSPSplitComplex(realp: aumbp.baseAddress!, imagp: bumbp.baseAddress!)

        //--Perform fft
        let log2Size = vDSP_Length(log2f(Float(32)))
        let setupFFT = vDSP_create_fftsetup(log2Size, FFTRadix(FFT_RADIX2))!
        vDSP_fft_zip(setupFFT, &splitComplex1, 1, log2Size, FFTDirection(FFT_FORWARD))
    }
}

Or else, you can allocate UnsafeMutableBufferPointer<Float>s and use them instead of Array<Float>.


text:
Q: ¿Cómo puedo transformar esta data en SQL Server? se me encargó la tarea de pasar esta información de un Excel a una Base de Datos SQL Server (La imagen está con datos demo).

Y bueno, esa información se sube tal y como está al SQL Server. y es necesario transformarlo así:

Sería de mucha utilidad una pista de como conseguir eso(la idea no es modificar la tabla, si no pasarlo a otra tabla).

A: No entiendo muy bien lo que quieres. ¿Sabes SQL? Lo digo por que si no sabes nada de SQL lo tienes difícil.  Tendrías primero que crear las diferentes tablas con sus relaciones lo que viene a ser un diagrama aunque sea básico (yo ahí con esos datos demos veo al menos 5 tablas), luego te creas las tablas, y ya si eso utilizas una vista o una consulta. Creo que no te vale solo con una tabla por que se ve que hay diferentes relaciones en tu excel. Luego si estas trabajando con un gestor de bases de datos SQL pues sería muy fácil en un nivel básico:
Para crear tablas:
CREATE TABLE nombre_tabla (
columna tipo_dato [RESTRICCIONES]
[mas columnas]
[restricciones a nivel de tabla] );
https://www.w3schools.com/sql/sql_create_table.asp
Para insertar datos:
INSERT INTO tabla (columnas[mas columnas]) VALUES (datos[mas datos]);
https://www.w3schools.com/sql/sql_insert.asp
Luego puedes hacer la consulta con un SELECT o crear una vista con CREATE VIEW.
En w3c encontrarás la información que necesitas, pero vamos si no sabes de SQL lo veo difícil, yo llevo 4 meses estudiando SQL y aún estoy empezando.


text:
Q: AttributeError when checking if a key exist in a dictionary, using python I am using Python 2.7.2+, and when trying to see if a dictionary holds a given string value (named func) I get this exception:
Traceback (most recent call last):
  File "Translator.py", line 125, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if unary.has_key(func) :
AttributeError: 'function' object has no attribute 'has_key'

This is where I define the dictionaries:
binary = {"add":'+', "sub":'-', "and":'&', "or":'|'}
relational = {"eq":"JEQ" , "lt":"JLT", "gt":"JGT"}
unary = {"neg":'-'}

Here's the function where the exception is raised:
def parseFunc():
    func = parser.arg1
    print func
    output.write("//pop to var1" + endLine)
    pop(var1)
    if unary.has_key(func) : // LINE 95
        unary()
        return
    output.write("//pop to var2" + endLine)
    pop(var2)
    result = "//"+func + endLine
    result += "@" + var1 + endLine
    result += "D=M" + endLine
    result += "@" + var2 + endLine
    output.write(result)
    if binary.has_key(func) :
        binary()
    else : relational()

Also, I tried changing if unary.has_key(func) to if func in unary but then I got
Traceback (most recent call last):
  File "Translator.py", line 126, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if func in unary:
TypeError: argument of type 'function' is not iterable

P.s I tired it also using python 3.2
Any ideas? Thanks

A: In Python 3, dict.has_key() is gone (and it has been deprecated for quite some time).  Use x in my_dict instead.
Your problem is a different one, though.  While your definition shows unary should be a dictionary, the traceback shows it actually is a function.  So somewhere in the code you did not show, unary is redefined.
And even if unary was a dictionary, you would not be able to call it.

A: It seems from your trace that you override the value of unary with a function (do you have any function called "unary"?). Therefore you are trying to call "has_key" method on a function that obviously has no such method. Pay attention with variable names, variable x will override def x() if it's placed after it in your code, and vice versa.


text:
Q: Fade in a partial view I have a mvc asp.net c# app
I have 2 pages.
The 1st page loads.
On that 1st page the user can press a button that calls my jquery function.
This function loads a partial view.
This works well
What I thought would look good is to fade/blend from 1st div contents to 2 div contents.
Can this be done?
Part of my _Layout.cshtml page:

    @RenderBody()

My index page:
@{
    ViewBag.Title = "Welcome";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@{Html.RenderPartial("Welcome2", null); }

My Welcome2 page:
@{
    ViewBag.Title = "Welcome2";
    Layout = null;
}

    @Html.Hidden("MyURL", @Url.Action("Lite", "Service"))

                We offer Cloud solutions for small businesses to help them manage their workflow requirements

                Our core sectors of expertise are professional services, data management and outsourcing.

my jquery function:
$("#my_button").click(function () {
    $('#mainContent').load(url);
    return false;
});

my controller:
public ActionResult Index()
{
    Response.Redirect("~/Welcome");
    ViewBag.Title = "Home Page";
    return View();
}

[Route("~/Welcome")]
public ActionResult Welcome()
{
    ViewBag.Title = "Welcome Page";
    return View();
}

[HttpGet]
[Route("~/Welcome2")]
public ActionResult Welcome2()
{
    return PartialView();
}

I appreciate that the answer lays in my jquery function but thought I would post the whole thing in case asked to do so
EDIT:
Change jquery to this:
$("#divHomeBanner").click(function () {
    var url = '/Welcome2';
    $('#divPager').load(url);
    $('#divPager').show('slow')
    return false;
});

and in my layout to this:

    @RenderBody()

but nothing changed - the page did not show


text:
Q: simultaneous jumps of independent Levy processes Suppose I have two independent Levy processes $X_t$ and $Y_t$, both not continuous.
Is anyone familiar and can refer me to a result(or a counterexample) which states that
${\displaystyle \sum_{0\leq s\leq t}}|\bigtriangleup X_{s}(\omega)\bigtriangleup Y_{s}(\omega)|=0
 $ for all $t\in \mathbb{R}$ a.s?
A different yet equivalent formulation of this is
$\bigtriangleup X_{t}=0$  or  $\bigtriangleup Y_{t}=0$ a.s. for all $t\in \mathbb{R}$
In words, every two independent Levy processes have no simultaneous jumps a.s. I know it holds for independent Poisson processes and I'm wondering if it generalizes.

A: Consider a finite time interval, let $J_i$ denote the set of (times of) jumps of the $i$'th process, and let $J_{i,n}$ denote the set of jumps of the $i$'th process of size $(\frac 1 n,\frac 1{n-1}]$.  Note that $J_{i,n}$ is finite a.s. and therefore $J_{i,n}\cap J_{j,m}=\emptyset$ a.s. for all $n,m$ and $i\neq j$.  Since there are countably many such intersections, it follows that $J_i\cap J_j = \emptyset$ a.s.

A: The following proposition will be proved:
Proposition Suppose that $X,Y$ are càdlàg adapted processes and $X$ have no fixed time of discontinuity, that is
$$ \mathsf{P}(\Delta X_t\ne 0)=0, \qquad  \forall t\ge 0.$$
If $X,Y$ are independent, then
$$ \mathsf{P}\Bigl(\sum_{s}|\Delta X_s| |\Delta Y_s|>0\Bigr)
=\mathsf{P}(\text{$X,Y$ have simultaneous jumps})=0.\tag{1}$$
Remark. If $X,Y$ are two independent Lévy processes, then it satisfy the conditions of above proposition.
Proof. 1 Since $X$ is càdlàg adapted process, then the random set
\begin{align}\{\Delta X\ne 0\}&=\bigcup_{m=1}^\infty[\![S_m]\!],\\
\{(\omega,t)\in\Omega\times\mathbb{R}_+: \Delta X_t(\omega)\ne 0\}
&=\bigcup_{m=1}^\infty\{(\omega,t)\in\Omega\times\mathbb{R}_+:S_m(\omega)=t\}.
\end{align}
where $S_m$ is a sequence stopping time
(cf. Jacod, J. and  A. N. Shiryayev, Limit Theory for Stochastic Processes, 2ed. Springer, 2003. I.1.32, p.8).
This means
\begin{gather}
\{\omega:\Delta X_t(\omega)\ne0\}=\bigcup_{m=1}^\infty\{\omega:S_m(\omega)=t\}, \qquad \forall t\in\mathbb{R}_+.\\
\{\omega: \text{the path of $X_s(\omega)$ has jumps}\}=\bigcup_{m=1}^\infty\{\omega:S_m(\omega)<\infty\}
\end{gather}
The $\{S_m, m\ge 1\}$ is also a sequence stopping time with respect to natural filteration of $X$, that is
$$ (S_m\le t)\in \mathcal{F}^X_t\stackrel{\text{def}}{=}\bigcap_{u\ge t} \sigma(X_s,s\le u)\vee \mathcal{N},\qquad \forall t>0.$$
2 Similarly, for $Y$,
$$\{\Delta Y\ne 0\}=\bigcup_{n=1}^\infty[\![T_n]\!], \qquad  (Y_n\le t)\in \mathcal{F}^Y_t. $$
For $X$ and $Y$,
\begin{align}
&\biggl\{\omega: \sum_{s}|\Delta X_s| |\Delta Y_s|>0\biggr\}=\{\omega: \text{$X_s(\omega),Y_t(\omega)$ have simultaneous jumps}\}\\
&\quad =\bigcup_{m=1}^\infty\bigcup_{n=1}^\infty\{\omega:S_m(\omega)=T_n(\omega)<\infty\}. \tag{2}
\end{align}
3 Since $X$ has no fixed time of discontinuity, that is
$$ \mathsf{P}(\{S_m=s\})\le \mathsf{P}\Bigl(\bigcup_{m\ge 1}\{S_m=s\}\Bigr) =\mathsf{P}(\Delta X_s\ne 0)=0, \quad\forall s>0, m\ge 1.$$
Hence $F_{S_m}(s)=\mathsf{P}(S_m\le s)$, the distribution function of $S_m$, is continuous and
$$\Delta F_{S_m}(s)=0,\qquad \forall s\ge 0, m\ge 1.\tag{3}$$
4. Using the independence of $X, Y$ and the measurability of $\{S_m, m\ge 1\}(\{T_n,n\ge 1\})$ with respect to
 $\mathcal{F}^X_{\infty}(\mathcal{F}^Y_{\infty}$, respectively),
we find that $\{S_m, m\ge 1\},\{T_n,n\ge 1\}$ are independent and
\begin{align}
&\mathsf{P}(S_m=T_n<\infty)=\int_0^\infty\int_0^\infty1_{\{s=t\}}(s,t)\,dF_{S_m}(s)dF_{T_n}(t)\\
&\quad=\int_0^\infty \Delta F_{S_m}(t)dF_{T_n}(t)=0 \quad \forall m,n\ge 1.\qquad \text{by (3)}. \tag{4}
\end{align}
Now (1) follows from (2),(4).

A: Besides the detailed answer you got from the double posting on math.stackexchange, one can even say a bit more:
When you consider the 2-dim Lévy process $(X(t), Y (t))$ without Gaussian part, the components are independent if and only if the support of the corresponding Lévy measure ν is in the set $\{(x, y) : xy = 0\}$.
Intuitively, the measure is concentrated on the axis and the two components of the process never jump
simultaneously. (see Proposition 5.3. in [1])
As a textbook reference I recommend to have a look at Section 5.4 in [1].

References
[1] Cont, R., Tankov, P. Financial modelling with jump processes, Chapman Hall/CRC, Boca Raton, FL, 2004, xvi+535


text:
Q: setup SQL server on windows server 2012 I am building my first application in ASP.NET.  I managed to publish the application to the windows server we bought, but I have no idea how to setup the SQL server. (everything works when running it local)
I use the IIS manager. When I check the database manager, it seems like it also uploaded the database config correct, but when I double click I get an error about the server not being accesible. I have no idea how to setup.

webconfig ( updated)
       <configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework"
      type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      requirePermission="false"/>
  </configSections>
  <connectionStrings>

    <add name="asr_database" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ASR-20150921042209.mdf;Initial Catalog=aspnet-ASR-20150921042209;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <authentication mode="None"/>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>