How to compile .sass files on save in Visual Studio 2015

Question: How can one get a full sass (i.e. scss) precompiler environment up and running in Visual Studio 2015? This is a sibling question to this one concerning less.
Answer: This can also be achieved without gulp or grunt by simply clicking your way in Visual Studio.
Install Web Compiler

In Visual Studio, press Tools -> Extensions and updates.
Search for Web Compiler (created by Mads Kristensen) and install.
Restart of Visual Studio will be needed.

Compile files

Right-click the .scss-file in Solution Explorer to setup compilation.
Press Web Compiler -> Compile File (Shift+Alt+Q).

A file called compilerconfig.json is created in the root of the project where you can modify the behavior of the compiler. Right-clicking the compilerconfig.json file let's you easily run all the configured compilers.
Any time a .scssfile is modified within Visual Studio, the compiler runs automatically to produces the compiled output file.
Compile on Build

Right-click the compilerconfig.json file
Press Web Compiler -> Enable compile on build
Clicking the menu item will prompt you with information that a NuGet package will be installed into the packages folder without adding any files to the project itself. The NuGet package contains an MSBuild task that will run the exact same compilers on the compilerconfig.json file in the root of the project.
Comment: I guess the NuGet package needs to be added to the project for this to be integrated into an automated build chain, right?
Comment: Mads Kristensen confirmed that it only worked with MsBuild which I believe the ASP.NET Core template doesn't use.  So I'm now looking for other solutions.
Comment: I'm not getting the 'Enable compile on build' option
Comment: Hmm guess it's because I'm using a new ASP.NET Core template
Comment: @ChrisNevill I had the same thing.  Restarting VS made it show up, but it's still grayed out/inactive.  Did you find a solution?  I'm on community version of VS2015 and an older .NET Framework.
Comment: Nice one, didn't know about the Compile on Build feauture
Comment: Be careful for the *Compile on Build*, I had to first generate the CSS file (by right clicking on the SCSS file > Web Compiler > Compile file) so an entry is added in the file _compilerconfig.json_. Only afterwards, the auto-compilation worked fine for that file.
Answer: If using Gulp + Visual Studio 2015

First install gulp-sass this is the package.json file

{
      "name": "ASP.NET",
      "version": "0.0.0",
      "devDependencies": {
        "gulp": "3.8.11",
        "gulp-concat": "2.5.2",
        "gulp-cssmin": "0.1.7",
        "gulp-uglify": "1.2.0",
        "rimraf": "2.2.8",
        "gulp-sass": "2.2.0"
      }

On the gulpfile.js

   var sass = require("gulp-sass");
   var paths = {
     webroot: "./wwwroot/"
   }
   paths.scss = paths.webroot + "css/**/*.scss";
   gulp.task('sass', function() {
     gulp.src(paths.scss)
       .pipe(sass())
       .pipe(gulp.dest(paths.webroot + "css"));
   });
   gulp.task('watch-sass', function() {
     gulp.watch(paths.scss, ['sass']);
   })

Now open the "Task Runner Explorer" and double click on the task: "watch-sass"

Now every time you save the scss the css will compile and change sass file.
Comment: also, right click watch-sass from the Task Runner Explorer pane and select Bindings > Project Open.  Now every time you open this project and change and save *.scss files it will already be watching and transpiling. Also, probably obvious, but put your *.scss files in your wwwroot/css folder, and it will auto hide the generated *.css file behind the sass files.
Comment: I need to revisit this question, things have changed a lot in just a year, your way using gulp (which I have "switched" to from grunt - in quotes because I'm hardly any expert in it) is the way I am most interested in, it is a native way of doing things. So when I get back into this I may need to mark this as the answer. Thanks to everyone elses answers here as well though, those are good contributions on how to skin this cat. But I like the native way.
Comment: More info can be found here: http://developer.telerik.com/featured/css-preprocessing-with-visual-studio/
Answer: Web Compiler Extension for VS2015
Gulp is required.
npm install -g gulp
Hope this helps... a few less hoops.
Edit:
I encountered an issue with the web compiler converting strings to Unicode characters when it should not have been doing so.  I switched to this implementation  http://blog.oxfordcc.co.uk/compiling-sass-gulp-visual-studio/ in VS2015 and it's compiling the CSS correctly.  Added just in case someone else encounters the same issue.
Comment: Sure about Gulp being required? There is no mention of it in the Web Compiler description or Q&A..
Comment: @st3inn appears to be correct.  For the webcompiler gulp is not needed, however it is required if you use the Task Runner.
Comment: This is an interesting new option.
Answer: If you don't want to mess around with the intricacies of setting up  the compilation manually, there are a number of amazingly simple extensions available that can handle this for you:
WebCompiler (FREE)
It's been mentioned already but Mads Kristensen (the author of web essentials) has created a standalone compilation tool called Web Compiler. All you have to do is install it, then right click on any of the SASS files you want to compile and select Web Compiler > Compile File. From that point on it is watched and anytime it is saved, the file will be compiled.
Download Web Compiler

CompileSASS (FREE)
Similar to Web Compiler this is a standalone extension that was created to work in both VS2013 and VS2015 because compilation was removed from the popular Web Essentials extension. It's lightweight and does the job very well with great error reporting. Read the author's blog about the extension here.
Download Compile SASS

Web Workbench (FREE/PAID)
Mindscape's Web Workbench was my favourite extension for many years when compiling SASS but I have since moved away in favour of the free alternatives. Still, the Pro version is a powerful tool with many ways to customise the outputted files but it is also quite expensive ($39) considering there are free tools out there.
Download Web WorkBench
Answer: Most of the steps in answer to this question are identical to the steps that were given by 'Maverick' on this post that concerned how to do the same thing for less. However, someone did not allow me to alter that question to simply include sass (which maybe was best, I don't know). So the following answer relies on the steps specified by Maverick in that post above, with these differences:
(Pre-step for Empty Projects)
If you started with an empty project, first add Grunt and Bower:

Right click solution -> Add -> 'Grunt and Bower to Project' (then wait for a minute for it to all install)

package.json:
"devDependencies": {
    "grunt": "^0.4.5",
    "grunt-bower-task": "^0.4.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-contrib-sass": "^0.9.2"
}

(FYI: grunt-contrib-sass link)
Then:

Dependencies -> right-click NPM -> Restore Packages.

gruntfile.js
1) Add or make sure these three lines are registered near the bottom (as NPM tasks):
grunt.loadNpmTasks("grunt-bower-task");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-sass");

2) Again in gruntfile.js, add init configurations, something like the following.
{ Caveat: I am no expert on such configurations. I found the sass configuration on an excellent blog post some time ago that I can't locate at this time in order to give credit. The key was I wanted to find all files in the project within a certain folder (plus descendants). The following does that (notice "someSourceFolder/**/*.scss", and see important related note here). }
// ... after bower in grunt.initConfig ...
"default": {
    "files": [
        {
            "expand": true,
            "src": [ "someSourceFolder/**/*.scss" ],
            "dest": "wwwroot/coolbeans", // or "<%= src %>" for output to the same (source) folder
            "ext": ".css"
        }
    ]
},
"watch": {
    "sass": {
        "files": [ "someSourceFolder/**/*.scss" ],
        "tasks": [ "sass" ],
        "options": {
            "livereload": true
        }
    }
}

Now follow the instructions for Task Runner Explorer as given in the other answer. Make sure to close and reopen project. It seems you have to run (double click) 'watch' (under 'Tasks') every time the project is started to get the watch watching, but then it works on subsequent saves.
Comment: Right click solution -> Add -> 'Grunt and Bower to Project' does not appear for me. Is this an extension?


Bathroom fan/light wiring help

Question: I have old switches at home for the fan and lights.
In short, 2 switches to control fan and lights separately.
Recently, I've been trying to add a timer switch which requires neutral and it doesn't seem to work as expected.
The wire setup, which worked with regular switches,

on left, there is black, red, and white and copper
on right, there is black, white, and copper.

Red(left) + black(right) = light on
Black(left) + black(right) = fan on

My old switches didn't have ground connected and only had the above two connected. Copper ones and white ones were connected to each other- which I don't quite understand why.
Anyways, what I tried was
- For light switch, have red(left) and black(right) connected.
- For fan switch, have black(left) and black(right) as hot and load, and use white one from connected white wires as neutral.
What happened was initially, the switch seemed to work (well, at least the light indicator was on), but as soon as I touched any buttons, it died. light switch continued to work.
Was hot and load possibly flipped? I still don't quite understand why the switch behaved/died the way it did even with this assumption.
Any help here would be tremendously appreciative!!
Comment: What did you do with the *other* neutral?
Comment: What exactly did you do with the neutrals?  All you say is "I don't quite understand why they are connected" and "use white one as neutral".
Comment: @Harper sorry for confusion, previously in the box, white ones from 2 incoming wires to the junction were connected to each other. and same with the copper wires. Previosuly owner did it, and I don't know why.
Answer: You believe the multiple neutrals are spare
It's real common for novices in electrical to see extra wires, and just assume they are spare wires waiting around for you.
That is not the case.  It is quite rare for electricians to install "extra" wires.  Every wire has a job.
Electricity flows in loops
Hot is available at the supply wire, and there's a second wire in the supply line - neutral.  Those ultimately go back to opposite sides of the supply transformer - that's half a loop.
Electricity flowed out the hot wire, went through the switch, out the fan cable and on to the fan where it did the work, and then where?  Not the ground, that's for safety.  It came back on the fan cable's neutral wire.  Then did it just end in the box capped off?  No, the neutrals were connected, so it went onto the supply neutral wire, completing the loop.
You attached the supply neutral to the switch so at least it would power up.
... or not
As for the fan, power goes to it, tries to come back on the neutral, and can't... which raises the voltage on the fan's neutral wire to 120V, as voltage is simply backing up with nowhere to go.   Tell me you insulated it and capped it off.
If you just left this "spare" neutral loose in the box, then it's a 120V time bomb. If the wire manages to short to either neutral or safety ground, the fan will power up momentarily, but the connection will be poor, causing a series arc fault.  If it shorts to ground, it also creates a ground fault, a particularly bad thing in a bathroom.
Double especially if there is another problem with the ground, because that ground fault could electrify all the grounds between here and the problem.
You wouldn't have expected a neutral to be hazardous (it's connected back to the panel, right? Oh wait...) Anyway, yeah. Electrical tends to be full of minefields.

So.  The right answer is to rejoin the neutrals, and add the smart switch's neutral to that bundle of neutrals, so all are connected.
Also, I would say that if you want to do any future electrical, I recommend getting a primer on the subject so you can get a well-rounded understanding of how things work.  A book on electrial that feels accessible to you is a good start.  You can't really google it; the subject is too broad.
Comment: Thanks for the detailed answer. Now I have a much better understanding of the situation. I did connect to the wires but never disconnected the joined neutral though. May be it was a faulty switch? I am out of ideas on why it wouldn't work though. I will try to find a good primer as you suggested.

Bathroom fan/light wiring help


to post image file in windows phone 7 application

Question: I am developing an application for windows phone 7.From here I want to upload an image file  to the remote server.I am using the following code to receive the file at my receiving end:
if (Request.Files.Count > 0)
{
    string UserName = Request.QueryString["SomeString"].ToString();
    HttpFileCollection MyFilecollection = Request.Files;
    string ImageName = System.Guid.NewGuid().ToString() + MyFilecollection[0].FileName;
    MyFilecollection[0].SaveAs(Server.MapPath("~/Images/" + ImageName));
}

Now my problem is, how can I post the file from my windows phone 7 platform (using PhotoChooserTask).I have tried the following code but with no success.(the following code is called from the PhotoChooserTask completed event handler.
private void UploadFile(string fileName, Stream data)
{
    char[] ch=new char[1];
    ch[0] = '\\';
    string [] flname=fileName.Split(ch);

    UriBuilder ub = new UriBuilder("http://www.Mywebsite.com?SomeString="+ussi );
    ub.Query = string.Format("name={0}", flname[6]);
    WebClient c = new WebClient();
    c.OpenWriteCompleted += (sender, e) =>
    {
        PushData(data, e.Result);
        e.Result.Close();
        data.Close();
    };
    c.OpenWriteAsync(ub.Uri);
}

private void PushData(Stream input, Stream output)
{
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

Please help me out to get out from this problem.
Thanks
Answer: I was able to get this working, but not using the Files collection.  From my post at http://chriskoenig.net/2011/08/19/upload-files-from-windows-phone/:
Client Code
public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    private void SelectButton_Click(object sender, RoutedEventArgs e)
    {
        PhotoChooserTask task = new PhotoChooserTask();
        task.Completed += task_Completed;
        task.Show();
    }

    private void task_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult != TaskResult.OK)
            return;

        const int BLOCK_SIZE = 4096;

        Uri uri = new Uri("http://localhost:4223/File/Upload", UriKind.Absolute);

        WebClient wc = new WebClient();
        wc.AllowReadStreamBuffering = true;
        wc.AllowWriteStreamBuffering = true;

        // what to do when write stream is open
        wc.OpenWriteCompleted += (s, args) =>
        {
            using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
            {
                using (BinaryWriter bw = new BinaryWriter(args.Result))
                {
                    long bCount = 0;
                    long fileSize = e.ChosenPhoto.Length;
                    byte[] bytes = new byte[BLOCK_SIZE];
                    do
                    {
                        bytes = br.ReadBytes(BLOCK_SIZE);
                        bCount += bytes.Length;
                        bw.Write(bytes);
                    } while (bCount < fileSize);
                }
            }
        };

        // what to do when writing is complete
        wc.WriteStreamClosed += (s, args) =>
        {
            MessageBox.Show("Send Complete");
        };

        // Write to the WebClient
        wc.OpenWriteAsync(uri, "POST");
    }
}

Server Code
public class FileController : Controller
{
    [HttpPost]
    public ActionResult Upload()
    {
        string filename = Server.MapPath("/Uploads/" + Path.GetRandomFileName();
        try
        {
            using (FileStream fs = new FileStream(filename), FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    using (BinaryReader br = new BinaryReader(Request.InputStream))
                    {
                        long bCount = 0;
                        long fileSize = br.BaseStream.Length;
                        const int BLOCK_SIZE = 4096;
                        byte[] bytes = new byte[BLOCK_SIZE];
                        do
                        {
                            bytes = br.ReadBytes(BLOCK_SIZE);
                            bCount += bytes.Length;
                            bw.Write(bytes);
                        } while (bCount < fileSize);
                    }
                }
            }

            return Json(new { Result = "Complete" });
        }
        catch (Exception ex)
        {
            return Json(new { Result = "Error", Message = ex.Message });
        }
    }
}

Note that I'm using ASP.NET MVC to receive my file, but you should be able to use the same, core logic with WebForms.
/chris


View doesn't find ViewModel in different Assembly

Question: I am starting a new project and oriented my projectstructure on the structure recommended in this question.
Now I am seeing strange behaviour. When I am setting the datacontext in the View-XAML, it isn't found at runtime (getting a XamlParseException). When I set it in the constructor in the codebehind-file, everything is working just fine.
Is this official (documented) behaviour when using different assemblies, or am I doing something wrong?
The code:
Not Working:
MainView.xaml:
<UserControl x:Class="ViewsRoot.Views.MainView"
         xmlns:baseControls="clr-namespace:BaseControls;assembly=BaseControls"
         xmlns:viewModels="clr-namespace:ViewModelsRoot;assembly=ViewModelsRoot">
<UserControl.DataContext>
    <viewModels:ShellViewModel />
</UserControl.DataContext>

MainView.xaml.cs
public MainView()
{
    InitializeComponent();
    // No DataContext set in codebehind-file
}

Working:
MainView.xaml:
<UserControl x:Class="ViewsRoot.Views.MainView"
         xmlns:baseControls="clr-namespace:BaseControls;assembly=BaseControls"
         xmlns:viewModels="clr-namespace:ViewModelsRoot;assembly=ViewModelsRoot">

MainView.xaml.cs:
public MainView()
{
    InitializeComponent();
    DataContext = new ViewModelsRoot.ShellViewModel();
}

Update:
The Exception-Text is:

{"The file or assembly \" ViewModelsRoot, PublicKeyToken = null \ "or one of its dependencies was not found. The system can not find the file specified."}

And the only inner Exception I can see is a System.IO.FileNotFoundException.
Update 2:
Thanks for the comments, but I haven't forgotten a namespace. I shortened it here for showing the code, but I double- and triplechecked (again). The DataContexts namespace is also filled in by intellisense. The whole <viewModels:ShellViewModel /> is written by intelli-sense. So it is found at designtime... ...so any more ideas?
Update 3:
The xaml is "correctly" parsed as I am able to bind the DataContext to a class in the same assembly.
Comment: Is there any inner exception?
Comment: You may have forgotten some namespaces in your `UserControl`. Check if this one helps: http://stackoverflow.com/questions/8852912/xamlparseexception-in-view
Comment: Well, I know I faced this exception in the past. Check that all the references used in the assembly of your viewmodel, are also referenced in the one of your View. As the inner exception states, some files are missing. Up to you to find which one!
Comment: Thanks for your help @Guillaume but there are no references missing or otherwise it wouldn't work in the codebehind-file. Also adding all references of the viewmodel-project to the view-project would completely work against the mvvm-pattern and I wouldn't need seperation of them in the first place.
Comment: I'm more thinking of some Framework assemblies, like Microsoft.CSharp or so. Which are used by the XAML engine to render the control. The stuff that needs to transform `` into `this.DataContext = new ShellViewModel();`
Comment: have you tried adding `using ViewModelsRoot;` into your code-behind file?
Answer: I have reproduced this error using a three project solution, with the specified dependencies between them:

StartupProject → ViewsRoot
ViewsRoot → ViewModelsRoot
ViewModelsRoot

"StartupProject" has "exe" output type, while the other two have "dll".
In my case, I solved the problem by adding "ViewModelsRoot" to the References list of "StartupProject". It is not a coding problem, but rather a runtime problem, because "ViewModelsRoot.dll" is not copied to "StartupProject" output folder.
When you specify the DataContext in code-behind, Visual Studio notices the need for that "dll" and adds it to the output after compilation. This doesn't happen when setting the DataContext from XAML. It is tricky because "ViewModelsRoot" code is used from XAML with Reflection. Adding it to References list forces Visual Studio to copy the "dll" in both cases.
You can also copy "ViewModelsRoot.dll" to the output folder directly, but it will not be updated when you change the code.
Comment: This is interesting.  I had the same issue and resolved it with this fix but to me it's a dirty fix.  I don't want to have that reference in my startup project and I do want my projects independent.  I noticed this never happened to me in the past but in the past I always had some coding reference to a ViewModel.  So... A less obvious hack is to just add a private class to your Views project and call it whatever you want and just add a field to a ViewModel in the ViewModel project.  It doesn't even have to be instantiated, just there for reference.
Answer: I've often found this error when the project target framework was set to "Client Profile" (this was set by default on VS2010, IIRC), if this is the case, try changing it to 3.5 or 4.0.
Comment: Sorry. No luck - it is .net4-Full Profile.
Comment: Any chance you can upload your project so I can take a look?


3rd party authorization: Cognito User Pools vs Lambda Authorization

Question: I am studying aws and encountered the following use case:

The development team at a company creates serverless solutions using
AWS Lambda. Functions are invoked by clients via AWS API Gateway which
anyone can access. The team lead would like to control access using a
3rd party authorization mechanism.

I think that Cognito User Pools should be used in this case, because it is clearly stated, that the system should use 3rd party authorization mechanism.
But the course gives an answer Lambda Authorizer, which would require custom implementation of authorization, right?
So which one is correct?
Answer: Looks like 3rd party means something, not related to AWS, in this case a custom solution involving Lambda Authorization is needed.


How to make ffmpeg automatically fill frames?

Question: I want to use ffmpeg to convert a sequence of images to a video, the images are got in realtime, the interval of getting image is changeable, maybe i get next image in 1 second or even 1 millisecond.
I want the target video in a special fps(like 100), now my implement is creating a loop, which fade ffmpeg last image then sleep(like 10ms).
Do you guys know some options could let ffmpeg fill frames automatically?
If that option do exist, i wonder is that possible to make video real fps is half of it is claimed.
My ffmpeg command likes follow:
ffmpeg -f image2pipe -r 100 -i pipe:0 -f flv -r 100 pipe:1

Comment: Do you wish to interpolate frames or duplicate till the next input frame is received?
Comment: yes i want ffmpeg use last image received
Answer: You can use
ffmpeg -f image2pipe -use_wallclock_as_timestamps 1 -i pipe:0 -f flv -vsync cfr -r 100 pipe:1

FFmpeg will set each incoming frame's timestamp to the time it is received. SInce the output rate is set and mode is constant frame rate, ffmpeg will duplicate the last frame till next input frame is received, or drop if two frames are less than 10ms apart. Change -r to 1000 to keep frames only a millisecond apart.


Casting a value with CCSID to match another hexidecimal in db2

Question: I have a query that works manually in my editor for DB2:
SELECT          *
FROM            TableOne T1
WHERE           CAST(T1 . IDENITIFIER AS CHAR(26) CCSID 65535) = x'0213725502A3BC45706AEE6001';

However, When I try this with the hex value being a param, it isn't working:
    SELECT          *
    FROM            TableOne T1
    WHERE           CAST(T1 . IDENITIFIER AS CHAR(26) CCSID 65535) = x':identifier'

How can I either properly append the x to the sting value/param in order to have a dynamic query where I can inject the identifier? Or is there another way I can get the same result by casting this origin value with the ccsid to match?
Comment: Try [HEXTORAW](https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_72/db2/rbafzscavarbinaryformat.htm) function.
Comment: @MarkBarinstein will this work for the IBM Iseries version 7 on the 400?
Comment: @MarkBarinstein hextoraw(:Value) executes but returns no results, where my intial query returns a result
Comment: Try `CAST(HEXTORAW(:Value) AS CHAR(26) CCSID 65535)` with a string constant `0213725502A3BC45706AEE6001`.
Comment: @MarkBarinstein I tried ```CAST(HEXTORAW(T . IDENTIFIER) AS CHAR(26) CCSID 65535) = '0213725502A3BB8F2149C82001'``` but it says Argument 01 of function VARBINARY_FORMAT not valid
Comment: `... WHERE CAST(T1.IDENITIFIER AS CHAR(26) CCSID 65535) = CAST(HEXTORAW(:Value) AS CHAR(26) CCSID 65535)`
Comment: @MarkBarinstein YES!!! Thank you so much, that worked! I'll accept an answer whenever you make it
Answer: You may use the string 0213725502A3BC45706AEE6001 (hex representation of x'0213725502A3BC45706AEE6001') as a parameter value in the following statement:
SELECT *
FROM TableOne T1
WHERE CAST(T1.IDENITIFIER AS CHAR(26) CCSID 65535) = CAST(HEXTORAW(:identifier) AS CHAR(26) CCSID 65535)


C# console application Streaming API 1.1 + Oauth

Question: I am using swhitley's Twitter Stream Client to download tweets via Twitter Streaming API with username and password. It was using https://stream.twitter.com/1.1/statuses/filter.json.
I modified the code to add OAuth, but I am getting a 400 error. Can anyone pls provide me code or direct me to an opensource project. Or just give me some tips on how to fix the issue.
Comment: I did this yesterday, is this any help? http://stackoverflow.com/questions/17067996/authenticate-and-request-a-users-timeline-with-twitter-api-1-1-oauth There is a link to the GitHub project with a console app inside.
Comment: @hutchonoid Thank you for the comment. But your app is using REST API, while I am trying to use the Streaming API. Your code is not working for me. Thank you.
Comment: No probs, I thought it might work in a similar way. If I get time I will try and get it working with the streaming api and post an answer.
Answer: If you are having some troubles with your API you can try using Tweetinvi
The API has been developed by myself and another developer in the goal of using the Streaming API.
It is pretty easy to use and you can find examples in the solution (Examplinvi).
Basically, you just have to define a method that will be called foreach of the Tweet received from the API. We have been able to process 3.5 millions tweets a day with this API (storing in MySQL Database).
<code>// Creating the stream and specifying the delegate
SimpleStream myStream = new SimpleStream("https://stream.twitter.com/1.1/statuses/sample.json");
// Create the credentials
IToken token = new Token("userKey", "userSecret", "consumerKey", "consumerSecret");
// Starting the stream by specifying credentials thanks to the Token
myStream.StartStream(token, x => Console.WriteLine(x.Text));
</code>
If you need any help, feel free to ask me.
Comment: Hello Mike. Please download the latest version. What you have been experiencing might be related with the fact that the default streaming URL was using Twitter 1.0 API. I've update the default URL.

Also if you want to change the stream URL (https://dev.twitter.com/docs/streaming-apis/streams/public), you can update the StreamUrl by specifically setting the StreamUrl property.

myStream.StreamUrl = "https://myStreamUrl";
myStream.StartStream(token);

Please let me know if this solves your issue.
Sincerely,
Linvi
Comment: Looks like TweetInvi would do what we need, but it just doesn't work. The sample code you provide leads me to a null reference exception in UrlEncode.
Comment: Would you please provide me more information concerning your code.
Did you provide your own Token information?
Comment: Indeed, I had to update the URL. After a few more fixes to the source code, we're off to the races.
Comment: If you don't provide any code, I cannot help you. As I said the solution has been used on many different projects, from many different servers with different type of account, so I think it is reliable enough.

Now I don't quite get where is your issue as I tested the stream from Tweetinvi and everything seems to work.

I would be happy to help you, but I need a little more information for that.
Comment: Sorry if I Wasn't clear; the problems were in Tweetinvi, not in my code.
Comment: SimpleStream  and IToken are undefined, using latest version of tweetiniv??? plz help @user2465083
Comment: @user2465083 - Can you please share any code samples for implementing TweetInvi in our Web based application (developed using ASP.NERT, C#, Javascript)? I need a solution for any user by clicking a button in our Web App should get one post (say - Welcome) in their Twitter account (after popup of Twitter sign in).


Can't center in html/css

Question: This code should work (in my opinion) but, I ca't figure out why it won't. Thanks in advance

EDIT:
I'm trying to center it. It stays in the upper left hand corner. Adding a height and width of auto to both divs also did not work.
Comment: in which  browser and which version???
Comment: What about it "doesn't work"? How is anyone going to help you if you don't say what you want your code to actually do?
Comment: As the title says "Can't center"

It stays in the default upper left hand corner of the screen. I just want the logo.png to center.
Answer: If you want to horizontally center the logo then you have to also specify the width of the containing div. Here is a sample code.

</html?

Answer: The inner div must have a set width for the margin auto to work.
Answer: Is the width of the inner div less than the width of the #wrap div?
Answer: I imagine that the wrap has a set width, the div holding the image will need a set width as well.
Fiddle so you can see that it does work. (a bit overkill for this question, I know :) )
Answer: you need to check 2 things before you set your division's to center.

Doctype : check whether it is not in quirks mode.
Width of inner div must me less that width of parent div.

do check these things you will get your answer...All the best.

Can't center in html/css


Error Message: redirect_uri URL is not properly formatted error

Question: The following error started popping up in my applications about 2 hours ago.
All three applications are hosted on the same server using shared SSL.

An error occurred with <application name>. Please try again later.
API Error Code: 100 API Error Description: Invalid parameter Error
  Message: redirect_uri URL is not properly formatted

Any ideas on what would cause this sudden change in my apps?
The error pops up when I try to use the function sendRequestToManyRecipients() or when posting to a users wall.
Code used to generate the popup

Answer: You can do the following :

1) encode the url before sending, ie both fb url as well as return url
   u can use javascript functions or php functions for encoding url

//encodeURIComponent(url); // in javascript u can do this

2) Also check that the return url specified is valid

Comment: Im lost here. Not sure exactly which URLs need to be encoded and also where do I check to return URL?
Comment: Yeah the url is encoded to skip special characters , the return url should be url encoded , and if the whole url contain any special character that too u can encode
Comment: I take it the URL that needs to be encoded would be the Canvas URL? I can't find any place to encode it or the return URL.

Any suggestions?
Comment: can u please share the url/code here , so that i can suggest u details clearly
Comment: Thanks for the feedback. The URL to the app is https://secure780.websitewelcome.com/~untitle2/payntwagon/facebook/ and the app sits inside Facebook at https://www.facebook.com/payntwagon?sk=app_279329708764904

The code to generate the popup to invite I will post in the original question.
Comment: While using facebook applications , first we need to authenticate our session with facebook using the secret key and id that we get while creating a fb app, after that e need to get a session key to access our app and after getting that we proceed with comamnds to facebook to do things, so while getting a session key , we need to pass a return url to facebook , the fb will automatically send the session key to that url after authenticating our app, so if this is the context , please go though fb app details, also u can post ur need..
Comment: Thanks for the help. This is making no sense to me. Applications worked 100% until 3 hours ago when the post to wall and share with friends features stopped working on all three applications.
Comment: This just started happening in my application... was working perfectly fine for months and I went on to check and none of the comment boxes are showing up it just says "href URL is not properly formatted" did you ever find a solution to this issue?


How to Filter a Disconnected Table

Question: I have a main table (Table 1) and I have created another table which is called rangeBefore (Table 2):
rangedBefore (Table 2) =
FILTER (
SUMMARIZE ( 'Campaign Overview', 'Campaign Overview'[campaign],'Campaign Overview'[range_name], 'Campaign Overview'[ranged_flag_in_words] ),
'Campaign Overview'[ranged_flag_in_words] = "RANGED")

What I am trying to do is return the main table but do not show any names which appear in Table 2, but I'm not quite sure how to go about this using DAX.
Comment: Can you share a .pbix?
Comment: I've shared it, so basically when I filter table 1, and filter table 2 (they aren't currently linked) if a name shows up in Table 2, then that name should not appear in Table 1.
Answer: Create a new measure as follows:
Measure Test =
VAR x = VALUES(rangedBefore[range_name])
VAR y = SELECTEDVALUE('Campaign Overview'[range_name])
RETURN
IF(y in x, 1)

Add it to the visual filters on your first table as follows:

How to Filter a Disconnected Table


Can I add arbitrary properties to DOM objects?

Question: Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT> or <SELECT> elements?  Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?
Answer: ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.
const wm = new WeakMap();
el = document.getElementById("myelement");
wm.set(el, "my value");
console.log(wm.get(el)); // "my value"

Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.
Comment: But doesn't that mean that you have to maintain the `wm` reference throughout? Seems a little limiting.
Comment: You don't want to maintain that wm reference? No need to expose it, if you rather use a utility function like setArbitraryValueTo(el,value) or getArbitraryValueFrom(el).
Answer: Yes, you can add your own properties to DOM objects, but remember to take care to avoid naming collisions and circular references.
document.getElementById("myElement").myProperty = "my value";

HTML5 introduced a valid way of attaching data to elements via the markup - using the data- attribute prefix.  You can use this method in HTML 4 documents with no issues too, but they will not validate:

Which you can access via JavaScript using getAttribute():
document.getElementById("myElement").getAttribute("data-myproperty");

Comment: data- attributes can only store strings (or objects serializable/deserializable to/from strings), not general runtime objects, whereas setting a new property on a dom object can.
Comment: @matteo - Back in 2010, when Andy wrote this answer, there was an issue in Internet Explorer related to DOM elements having references to JavaScript objects on arbitrary properties. But that was fixed in a later version of IE, so the circular references thing is no longer an issue.
Comment: Should that last line be `setAttribute()`?
Comment: @alex: nope, still made a mistake though :-)
Comment: What's exactly the issue with circular references? An object A having a reference to an object B which has a reference to A is not an issue in general, so what is the situation that must be avoided in the case of arbitrary properties attached to a DOM element?
Comment: @matteo A circular reference *could* lead to a memory leak. https://stackoverflow.com/questions/7347203/circular-references-in-javascript-garbage-collector
Answer: Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.
If you are looping code with for..in your code may break because you will now be enumerating through these newly attached properties.
I suggest using something like jQuery's .data which keeps metadata attached to objects. If you don't want to use a library, re-implement jQuery.data
Comment: How would `for...in` loops break just by having an extra property?
Comment: `$.data` is defined by jQuery. You would use it like `$('#el').data('key', 'value')`.
Comment: It's `$(element).data('name', value)` to set a value, and `$(element).data('name')` to read it.
Comment: I assume you know how to do it the manual DOM way, `el['data-foo'] = 'value';`
Comment: There are bugs/inconsistencies with `getAttribute` and `setAttribute` in IE, if you dont decide to use `$.data` prefix your attribute with `data-`
Comment: Cool... Is `data` used by jQuery itself or am I free to assign any value to it?
Comment: One option these days (2023) would be to use a property keyed by a [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) instead of a string - those are guaranteed not to clash with anything else and they are ignored by `for ... in`
Answer: Do you want to add properties to the object, or attributes to the element?
You can add attributes using setAttribute
var el = document.getElementById('myelement');
el.setAttribute('custom', 'value');

or you can just add properties to the javascript object:
var el = document.getElementById('myelement');
el.myProperty = 'myValue';

Comment: if anyone forgot the difference between property and attribute -> quick link https://stackoverflow.com/a/6004028
Answer: In case someone is wondering in 2015, yes, you can - and jQuery is doing just that in data. Just pick future-proof names like vendor prefixes or time-based random suffixes (jQuery).
Comment: But jQuery is using an internal cache were the data is saved, the data is not saved in the DOM Element itself. See also: https://stackoverflow.com/questions/7200722/jquery-expando-properties
Comment: You linked to the master branch of jQuery. Since master branches change, please consider linking to a particular version.
Answer: If you must, don't use standard HTML attributes. Here's a tutorial on using custom attributes:
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
It's HTML5, but it's backward-compatible.
Answer: I was exploring answers, none have mentioned that in modern JavaScript we can set attributes on domElements using dataset property, it could use on HTMLOrForeignElement (that's a mixin of several features common to the HTMLElement, SVGElement and MathMLElement interfaces).
According to MDN

The dataset property on the HTMLOrForeignElement interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM. It is a map of DOMStrings, one entry for each custom data attribute.

let element = document.getElementById("test");
let footer = document.querySelector("#output");

/* get element values using camelCase names through .dataset */
let sample = element.dataset.sample;
let sampleNumber = element.dataset.sampleNumber;

let dataFromElement = sample + " :: " + sampleNumber;

footer.innerHTML = element.innerHTML  + dataFromElement;
<input type="hidden" id="test" data-sample="Sample" data-sample-number=34 />

Although there are concerns about Internet Explorer support and performance on this you can check here.
Comment: The issue with this is that the dataset properties are just attributes and so passing in an object results in it being flattened to `[object Object]`.


onFocus method for the textField

Question: I want to change the cursor position from one textField  to another textField. I want set that programatically. How I do that? Is there any method for that in iPhone?
Answer: Send the setFirstResponder message to the second text field.

onFocus method for the textField


need help with completing Zone, Thermostat and low pressure wiring for a Alpine Boiler ALP150

Question: i have completed most of the connections to the boiler expect for
Zone values, Thermostat and low pressure monitoring.
i need help with understanding if i need to purchase a 24v transformer ? and how to serial connect the wiring with regard to zones valves, thermostat and low pressure monitoring.
Comment: Do you have a zone controller? What is the make and model of the zone valves?
Comment: I don't have a zone controller installed as it was not required.   the model zone valves are Honeywell V8043E1012
Answer: First things first, you'll need a transformer to step power down from 120 volts to 24 volts. Next, you'll obviously need a zone valve.  You'll also need a thermostat, to actually determine when the heat should come on.  You'll need a thermostat and zone valve for each zone, but a transformer should be able to supply a few zones.
Start by connecting one of the yellow leads from all the zone valves, to one of the leads from the transformer.  Next connect a wire from the R terminal of each thermostat, to the other transformer lead.  Connect the other yellow lead from each zone valve, to the W terminal of the corresponding thermostats.
Gather up one of the red leads from each of the zone valves, and connect them to one of the Heating T-Stat terminals in the boiler (using a pigtail is the proper way to do this, as you're only allowed one wire under screw terminals. Gather up all the other red leads from the zone valves, and connect them to the other Heating T-Stat terminal in the boiler.

Example wiring for a single zone
That's it.  Now when a thermostat calls for heat, it will open the appropriate valve, and signal the boiler.
Comment: thank you so much... just one last thing, does it matter which red is connected to the T stat are they interchangeable ? ....  Also I have a safguard low water cut off.. Model 1100...  would this come off the same low voltage transformer ?
Comment: There should be two red wires coming out of the zone valves, and two `Heating T-Stat` terminals in the boiler. So each red wire will go to one of the `Heating T-Stat` terminals. According to the [Manufacturer's installation instructions](http://bostonheatingsupply.com/Burnham/Burnham%20Alpine%20I&O%20Manual.pdf), there should be a [special cable that connects the low water cut off to the boiler](http://i.stack.imgur.com/nauVe.png) (see page 56).
Comment: Thanks, this really helped me in getting my Sensi hooked up to my apartment/condo Honeywell zone valve, which was using a thermostat labelled R,Y which has the same effect as the R,W connecting up to Rh, W/E in this case.  I did have to add a 24v transformer to provide power for wifi/constant power to the Rc/C and cut the jumper, but fantastic after struggling with it for a few hours to figure out which terminals to use.


Can you help me identify the maker of this shower door roller?

Question: I've a broken roller on my shower door. I'm looking for replacement parts but I can't identify the maker of the piece so it makes the search a bit harder. I post a picture of the intact piece. Any of you have an idea of the maker ?
Thanks
Comment: I would take it to a plumbing or speciality store.
Comment: I tried a couple places but no luck so far.
Comment: If you get a picture of this without your hand, google images has a function to search by image. Go to http://google.com/imghp then click the little camera next to the search icon, and upload the image there. Then scroll down and click "Visually similar images"
Comment: Tried it with no success but I finally found the maker of the part with a helpful men in a local plumming shop. For the record, it's made by Fleurco  (http://www.fleurco.com/)
Answer: I finally found the maker of the part with an helpful men in a local plumming shop. For the record, it's made by Fleurco (fleurco.com)
Thanks for your help


Wifi doesn't find any networks after 18.04.3 update

Question: Edit: After reinstalling the network manager the WiFi worked for 2 days, but now again it appears to be on, but doesn't show any available networks. I tried to connect to to the networks by the "connect to hidden networks" option, but that also failed.
sudo systemctl restart network-manager doesn't show a message anymore and seems to restart the network (I'm connected to the internet via an USB cable to my phone)
systemctl status NetworkManager shows:

● NetworkManager.service - Network Manager
    Loaded: loaded (/lib/systemd/system/NetworkManager.service;
  enabled; vendor p
    Active: active (running) since Thu 2019-09-26 11:40:55 +07; 4min > 8s ago
      Docs: man:NetworkManager(8)
  Main PID: 3202 (NetworkManager)
     Tasks: 4 (limit: 4915)
    CGroup: /system.slice/NetworkManager.service
            ├─3202 /usr/sbin/NetworkManager --no-daemon
            └─3222 /sbin/dhclient -d -q -sf /usr/lib/NetworkManager
  /nm-dhcp-helpe
Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3530]
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3532]
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3599]
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3601]
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3605]
  Sep 26 11:40:56 mehrdad-Latitude dhclient[3222]: bound to
  192.168.42.112 -- rene
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3727]
  Sep 26 11:40:56 mehrdad-Latitude NetworkManager[3202]:
  [1569472856.3729]
  Sep 26 11:40:57 mehrdad-Latitude NetworkManager[3202]:
  [1569472857.6882]
  Sep 26 11:41:01 mehrdad-Latitude NetworkManager[3202]:
  [1569472861.8343]

sudo iwconfig shows following:

wlp2s0    IEEE 802.11  ESSID:off/any
           Mode:Managed  Access Point: Not-Associated   Tx-Power=200 dBm
           Retry short limit:7   RTS thr:off   Fragment thr:off
           Encryption key:off
           Power Management:on
enp0s20u1  no wireless extensions.
eno1      no wireless extensions.
lo        no wireless extensions.

Everything was fine before, but after I updated to Ubuntu 18.04.3 LTS just an hour or so ago, my WiFi doesn't find any networks.  I restarted my system several times and nothing changed.
Here's the output of 'lspci -knn | grep Net -A3; rfkill list'

00:19.0 Ethernet controller [0200]: Intel Corporation 82579LM Gigabit >Network Connection (Lewisville) [8086:1502] (rev 04)
    Subsystem: Dell 82579LM Gigabit Network Connection (Lewisville) >[1028:0533]
    Kernel driver in use: e1000e
    Kernel modules: e1000e
   00:1a.0 USB controller [0c03]: Intel Corporation 7 Series/C216 Chipset
   Family USB Enhanced Host Controller #2 [8086:1e2d] (rev 04)
   --
   02:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM43228
   802.11a/b/g/n [14e4:4359]
    Subsystem: Dell BCM43228 802.11a/b/g/n [1028:0014]
    Kernel driver in use: wl
    Kernel modules: bcma, wl
  1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
  2: brcmwl-0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
  3: dell-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: no
  4: dell-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
  5: dell-wwan: Wireless WAN
    Soft blocked: no
    Hard blocked: no
  7: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

How may I troubleshoot this?
Comment: From what version of Ubuntu did you upgrade from? Does `iwconfig` show anything? What about `systemctl status NetworkManager`? Please add to your question.
Comment: Now I restarted the laptop again after a few hours and it works again. I'm really confused
Answer: If your network manager is not restarting then try to reinstall and restart your pc. Maybe it will work.
Here is the network manager deb file find which one is suitable for you.
network manager
I am not sure it will work or not ...
Comment: Today the WiFi worked at first, but after I restarted the computer it stopped working. The network manager shows me no available WiFi networks. I tried reinstalling the network manager and did several restarts, but it still doesn't work.
Comment: i picked the network manager file with the most recent date and it worked.
Thanks a lot!


Are intersection multiplicities independent of the base field?

Question: Let $F, G$ be affine curves over some field $K$, i.e. elements of $K[x, y]$. The intersection multiplicity $\mu_P(F, G)$ of $F$ and $G$ in $P=(x_0, y_0)$ is defined as
$$
\mu_P(F, G) := \dim_K \mathcal{O}_P/(F, G)\;,
$$
where $\mathcal{O}_P$ is the local ring of $\mathbb{A}^2$ at $P$, i.e. the localisation of $K[x, y]$ in the maximal ideal $(x-x_0, y-y_0)$.
I am wondering if the quantity $\mu_P(F, G)$ is independent of the base field, i.e. if
$$
\dim_K \mathcal{O}_{P, K}/(F, G)=\dim_L \mathcal{O}_{P, L}/(F, G)\;,
$$
where we denoted $\mathcal{O}_{P, K}:=K[x, y]_{(x-x_0, y-y_0)}$ and analogously for $L$ for simplicity. Specifically, I am interested in the case $K=\mathbb{R}$ and $L=\mathbb{C}$.
My idea is to show that there is an isomorphism
$$
\mathbb{C}\otimes_{\mathbb{R}}\mathcal{O}_{P, \mathbb{R}}/(F, G)\cong \mathcal{O}_{P, \mathbb{C}}/(F, G)\;,
$$
of $\mathbb{C}$-vector spaces, from which the result would follow as scalar extension preserves dimensions. My guess is that such an isomorphism is given by
$$
\begin{split}
\varphi: \mathbb{C}\otimes_{\mathbb{R}}\mathcal{O}_{P, \mathbb{R}}/(F, G)&\rightarrow \mathcal{O}_{P, \mathbb{C}}/(F, G) \\
a\otimes f&\mapsto af
\end{split}
$$
with inverse
$$
\begin{split}
\psi: \mathcal{O}_{P, \mathbb{C}}/(F, G)&\rightarrow \mathbb{C}\otimes_{\mathbb{R}}\mathcal{O}_{P, \mathbb{R}}/(F, G) \\
\sum_{i, j} a_{ij}x^iy^j&\mapsto \sum_{i, j} a_{ij}\otimes x^iy^j\;.
\end{split}
$$
(Note that we can WLOG assume $F$ and $G$ to be irreducible since
$$
\mu_P(R, ST)=\mu_P(R, S)+\mu_P(R, T)
$$
for any $R, S, T\in K[x, y]$ and then we can furthermore assume that $F$ and $G$ are coprime. In such a case, I can show that any element of $\mathcal{O}_P/(F, G)$ has a polynomial representative, so it is indeed enough to define the above map on polynomials only.)
Indeed, I can show that $\varphi$ and $\psi$ are mutually inverse $\mathbb{C}$-linear maps. I can also show that $\varphi$ is well-defined, but I am struggling with the well-definedness of $\psi$: While I do not have any problems showing that $\psi(AF+BG)=0$ for $A, B\in \mathbb{C}[x, y]$, I am a bit clueless as to how to show
$$
\psi\left(\frac{AF+BG}{C}\right)=0
$$
for $C\not\in (x-x_0, y-y_0)$ with the property that $C\mid AF+BG$ in $\mathbb{C}[x, y]$.
It seems that this should be the right way to do this, but I cannot figure out this last step, does anyone have an idea how to finish the argument? Or, alternatively, how to prove the statement in a different way?
Answer: Assume that $L/K$ is finite Galois with Galois group $G$.
Let us first show that $\mathcal O_{P,K} \otimes_K L \cong \mathcal O_{P,L}$, i.e. let's solve the case $F=G=0$. Let $S=k[X,Y] \setminus (x-x_0,y-y_0)$. Then we have
$$\mathcal O_{P,K} \otimes_K L \cong \mathcal O_{P,K} \otimes_{K[x,y]} K[x,y] \otimes_K L \cong \mathcal O_{P,K} \otimes_{K[x,y]} L[x,y] \cong S^{-1} L[x,y]$$
This is almost $\mathcal O_{P,L}$, but not quite: $\mathcal O_{P,L}$ is the localization at $T:=L[x,y] \setminus (x-x_0,y-y_0)$ not at $S$. We do have $S \subset T$, so that we obtain a map $S^{-1}L[x,y] \to T^{-1} L[x,y]$. We want to show that this map is an isomorphism, for this it suffices to show that any element of $T$ is a unit in $S^{-1}L[x,y]$. $G$ acts coefficient-wise on $L$. Let $f \in T$, then we get that $\prod_{\sigma \in G}\sigma(f) \in S$ (use Galois theory to show that it is in $K[x,y]$ and evalute at $(x_0,y_0)$ to get that it is in $S$). Thus $f$ is a unit in $S^{-1}L[x,y]$, as that ring contains $$\frac{\prod_{\sigma \in G \setminus \{\mathrm{id}\}}\sigma(f)}{\prod_{\sigma \in G}\sigma(f)}=\frac{1}{f}$$
This finishes the proof that $\mathcal O_{P,K} \otimes_K L\cong \mathcal O_{P,L}$
We can deduce the general result from this. Consider the exact sequence of $K$ vector spaces
$$(\mathcal O_{P,K})^2\to \mathcal O_{P,K} \to \mathcal O_{P,K}/(F,G) \to 0$$
where the map $(\mathcal O_{P,K})^2\to \mathcal O_{P,K}$ is given by $(a,b) \mapsto aF+bG$
Now we tensor with $L$ over $K$ and obtain the exact sequence
$$\mathcal O_{P,L}^2 \to \mathcal O_{P,L} \to \mathcal O_{P,K}/(F,G) \otimes_K L \to 0$$
where again  the map $(\mathcal O_{P,L})^2\to \mathcal O_{P,L}$ is given by $(a,b) \mapsto aF+bG$. From the exactness of this sequence, we obtain
$$\mathcal O_{P,L}/(F,G) \cong \mathcal O_{P,K}/(F,G) \otimes_K L$$ as desired.


It is possible to get by query maximum input NUMBER value in column?

Question: For example i have a table with column "example" NUMBER(5,2), if I right - max input value is 999,99.
It's possible get by query value that could be stored in that column? May be any SQL query or by java api?
Comment: `max(example)` gets the *highest number stored in that column*. From how I understood the question, it's about the highest number that **could be stored** in that column.
Comment: Do you mean like `SELECT MAX(example) FROM MyTable` ?
Comment: did you check [max function](http://docs.oracle.com/javadb/10.6.1.0/ref/rrefsqlj27781.html)?
Comment: well, as Peter mentioned you can use MAX, but this will use actual table contents... if you want to know that just by the COLUMN data type you will need to look&parse the DESCRIBE of the given table/column ( no library I am aware of now does that )
Comment: @Joachim Sauer understood my question right, sorry for my english guys
Answer: try this
    ResultSet rs = ...
    ResultSetMetaData md = rs.getMetaData();
    int precision = md.getPrecision(column);
    int scale = md.getScale(column);

Answer: If you already have the values for precision and scale, you should be able to calculate the maximum value like this:
int precision = 5;
int scale = 2;
double maxValue = (Math.pow(10, precision) - 1) / Math.pow(10, scale);

If you don't know the values for precision and scale, you can query the database metadata:
ResultSet rs = conn.getMetaData().getColumns("", "%", "{TABLENAME}", "{COLUMNNAME}");

if(!rs.next()) {
    // unknown table/column
}

int precision = rs.getInt("COLUMN_SIZE");
int scale = rs.getInt("DECIMAL_DIGITS");

Comment: thank you @jarnbjo but i can't here accept 2 right answers :(, but Evgeniy Dorofeev was first.
Comment: No problem, but you actually asked for the max value, given a specified precision and not how to obtain that precision from the database. If you need to query the database for the precision, it's IMHO better to query the connection metadata (like I did) instead of making an unnecessary "SELECT ... FROM TABLE" as Evgeniy suggests.
Answer: select max(column_name) as 'Max_number' from table_name


Python httplib2 Access is denied

Question: I am facing a problem on executing simple code.
import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")

Output is
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 1175, in __init__
    self.cache = FileCache(cache)
  File "C:\Python27\lib\site-packages\httplib2\__init__.py", line 700, in __init__
    os.makedirs(self.cache)
  File "C:\Python27\lib\os.py", line 157, in makedirs
    mkdir(name, mode)
WindowsError: [Error 5] Access is denied: '.cache'

Anyone with any suggestions to fix this error?
Comment: It looks like you cannot create the .cache directory in your working directory. Maybe switching your current directory fixs it.
Comment: Do you have permission to create folders where the script is executing?
Comment: Pretty sure it's a permissions issue...
Answer: To get this working you could just leave out the cache directory:
import httplib2
h = httplib2.Http()
resp, content = h.request("http://example.org/", "GET")

As the comments say above, you don't have permission to create the .cache directory relative to the path you're running the code from.
Of course, having a cache is better...
For a simple, in-memory cache which won't cause you permissions headaches, checkout this article I wrote: http://grahamlyons.com/article/a-simple-in-memory-cache-for-python-s-httplib2

Python httplib2 Access is denied


Read "n" number of lines from a file C++

Question: Quick question,
Assuming that you were told to read input, only 10 lines, from a text file; nevertheless, the text file has 40 lines. Would it be bad programming to do the following:
while ( infile >> input && num_lines < 10 ) {
      do whatever...
      num_lines++;
}
// closed file
infile.close();

Is there a better way to do this??
I should have mentioned that when i said "lines" i merely meant the following:
planet
tomorrow
car
etc

So yes, to read a line of text, get line function should be implemented
Comment: [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) springs to mind. start with that, and a `for-loop` may make more sense, since right now you're code will read 11 *strings*, "do whatever..." for 10 of them, and throw the last one away (assuming you start `num_lines` at zero).
Comment: If you are to read a fixed number of lines, it's more idiomatic to use a `for` loop.
Answer: It wouldn't be bad programing. That you're checking your input success is better than most people new to this, so don't feel bad about it. Your current loop, however, would not be correct.
Things wrong:

It reads strings, not lines
It could actually read eleven lines, processing the first ten and discarding the last.

Try this:
int num_lines = 0;
std::string input;

for (; num_lines < 10 && std::getline(input); ++num_lines)
{
    // do-whatever
}

// num_lines holds the number of lines actually read

Edit: Updated after question changed.
The input file you have are words. If you want to ensure you receive only a single word off each line, and they must be line-separated, more work is involved:
#include <iostream>
#include <sstream>

int num_lines = 0;
std::string input;

while (num_lines < 10 && std::getline(input))
{
    std::istringstream iss(input);
    std::string word;
    if (iss >> word)
    {
        // do-whatever with your single word.

        // we got a word, so this counts as a valid line.
        ++num_lines;
    }
}

This will skip blank lines and only process the single word at the beginning of each line that has content. It could further be enhanced to ensure the word read was the only content on the line aside from whitespace and the newline or EOF, but I seriously doubt you need error checking that tight (or even this tight).
Example Input
one
two
three four
five

six
seven
eight
nine
ten
eleven twelve

Processed Words
one
two
three
five
six
seven
eight
nine
ten
eleven

Both four and twelve are ignored, likewise the blank line between five and six. Whether this is what you seek is your call, but at least you have something closer than before.
Answer: infile >> input is not the right method to read a line of input. It stops reading when a whitespace character is encountered in a line. You should to use std::getline(infile,input).
while ( std::getline(infile, input) && num_lines < 10 ) {
      do whatever...
      num_lines++;
}


Strange Error: QObject::~QObject: Timers cannot be stopped from another thread

Question: This code is running fine as far producing the required output is concerned but is displaying a strange error message:

QObject::~QObject: Timers cannot be stopped from another thread.

from multiprocessing import Pool,Manager
import matplotlib.pyplot as plt
import numpy as np
import time

def scatter_join(args):
    num = args[2]
    print(num)
    plt.scatter(args[0],args[1],s=1)
    plt.savefig('test_p'+str(num)+'.png')
    if args[3].empty() is False:
        args[4].acquire()
        (ax,fig) = args[3].get()
        ax.scatter(args[0],args[1],s=1)
        args[3].put((ax,fig))
        args[4].release()
    else:
        args[4].acquire()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.scatter(args[0],args[1],s=1)
        args[3].put((ax,fig))
        args[4].release()

    return None

if __name__ == '__main__':
    p = Pool()
    m = Manager()
    q = m.Queue()
    l = m.Lock()
    snap = []
    for looper in range(0,50):
        np.random.seed(int(time.time()))
        snap.append( np.random.normal(0+np.random.randint(-5,5),20+np.random.randint(-5,5),(10000,2)) )

    task = [(snap[x][:,0],snap[x][:,1],x,q,l) for x in range(0,50)]
    t = time.time()
    results = p.map(scatter_join,task,chunksize=18)

    p.close()
    p.join()
    print('Time Elapsed(Parallel): ', abs((time.time()-t)))

    (ax,fig) = q.get()
    fig.savefig('superimposedimg.png')

    t = time.time()
    for looper in range(0,50):
        print(looper)
        np.random.seed(int(time.time()))
        plt.scatter(snap[looper][:,0],snap[looper][:,1],s=1)
        plt.savefig('test_s'+str(looper)+'.png')
        plt.clf()
    print('Time Elapsed(Linear): ',abs(time.time()-t))

I basically want to use multiprocessing to plot plot graphs in a simgle matplotlib object.
Comment: I am a bit surprised that this works at all.... If you never want to see the GUI windows, I suggest using a non-interactive backend (ex agg `matplotlib.use('agg')` before importing pyplot).
Comment: @tacaswell I want to plot the result in a .png rather than seeing anything on runtime.
Answer: When plotting like that, you need to make sure the backend
is set to the agg backend.  You can do that in a matplotlibrc file or
directly in the plotting script, immediately after importing matplotlib
and before importing pyplot (if you use pyplot at all).
# do this before importing pylab or pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

http://matplotlib.org/faq/howto_faq.html#howto-webapp
Also you may plot in isolation. For eg:
fig = plt.figure()
fig, ax = plt.subplots()
 > plot stuff, scatterplot, etc..., set title, lables, etc...
fig.savefig(filename, format='png', dpi=100, facecolor='w',
edgecolor='k')
plt.close(fig)

NB: Since we close the plot after you don't have to use fig.clf() to clear.


An error occurred building visual studio cordova app using multi-device-hybrid-apps only in Release and Distribution configuration

Question: I am developing a mobile app using Cordova by multi-device-hybrid-apps in Visual Studio 2013,
Everything is fine on Debug configuration, the app will compile correctly and is installed on the device. But when I try to compile and deploy via Release or Distribution configuration it will give me this error
Error code 1 for command: cmd with args: /s,/c,ant,release,-f,d:\PhoneGap\projects\MyWeddingCard\MyWeddingCard\bld\Distribution\platforms\android\build.xml,-Dout.dir=ant-build,-Dgen.absolute.dir=ant-gen
1>  Command finished with error code 2: d:\phonegap\projects\MyWeddingCard\MyWeddingCard\bld\Distribution\platforms\android\cordova\build.bat --release,
1>
1>  C:\Users\RezaRa\AppData\Roaming\npm\node_modules\vs-mda\node_modules\q\q.js:126
1>                      throw e;
1>                            ^
1>EXEC : error : d:\phonegap\projects\MyWeddingCard\MyWeddingCard\bld\Distribution\platforms\android\cordova\build.bat: Command failed with exit code 2
1>      at ChildProcess.whenDone (C:\Users\RezaRa\AppData\Roaming\npm\node_modules\vs-mda\node_modules\cordova\node_modules\cordova-lib\src\cordova\superspawn.js:131:23)
1>      at ChildProcess.emit (events.js:98:17)
1>      at maybeClose (child_process.js:756:16)
1>      at Process.ChildProcess._handle.onexit (child_process.js:823:5)

I know this a general error but is there any way to undrestand what is the problem.
p.s I have created Keystore file and added to ant.properties file.
Answer: I found the problem I changed keystore file path in ant properties from
key.store=D:\PhoneGap\projects\MyWeddingCard\Key\MyWeddingCardKeystore.keystore
to
key.store=D:\\PhoneGap\\projects\\MyWeddingCard\\Key\\MyWeddingCardKeystore.keystore
Comment: Thanks so much for posting this. I had the same issue and couldn't find a solution anywhere. Much appreciated.


dr.Read() dont execute my ELSE code block when the work is on HOLD and i cant find how i add EndTime for HOLDED work

Question: I wanna make an worktime-following program on ASP.NET in c# with access database. I know how to prevent SQL injection and so its okay about that my codes will a little be basic.
When user select the work and clicks START button(btnisBaslat button) the work will started , and program will add Start Time , when user click "Beklemeye al" and click STOP button (btnisDurdur button) it means work is not completed and just holding the work like not finished. And user may start it again and after that he/she can finish this work by clicking STOP button and clicking "Bitir" Radio button.
If user clicks "Beklemeye al" (HOLD the work) radio button the program adding End Time to this work , and after that user can see how much minute he working total.after that program adds StartTime again for calculating (HOLDing time) like how much this work was hold by the user.
The problem is: when user select other work from DropdownList and click start the last finished work Just Dont add EndTime for Holding time.And adding StartTime to second work. And ta-daa! the EndTime column for first work will empty.
I want to ask how i can coding the EndTime too. And also
SECOND PROBLEM is When first work on database "is_durum" column like "Beklemede" it means the work is HOLD (waiting to start again when user wants but not finished work). then read my IF block ,
But when I click second work to Start and HOLD it,on database "is_durum" column its updates to "Beklemede" (waiting) it should read my IF block again but it reads only ELSE block all the time. Where is my problem ?. I will share the screenshots and codes now.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Configuration;

    protected void btnisBaslat_Click(object sender, EventArgs e)
    {

            OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("Database1.accdb") + "");
            con.Open();
            //OleDbCommand cmd = new OleDbCommand("update Personel set is_Tanimi='" + txtisTanimi.Text + "', baslangic_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where ID = " + Session["UserID"], con);
            OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='true' where ID=" + Session["UserID"], con);
            cmd.ExecuteNonQuery();
            //OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Gorevler(Kadi,is_tanimi,baslangic_zamani,kull_id) values ('" + Session["Adi"] + "','" + DDLisSec.SelectedValue + "','" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "','" + Session["UserID"] + "')", con);
            //cmd2.ExecuteNonQuery();
            OleDbCommand cmd2 = new OleDbCommand("Select * from Temsilci where is_durum='Beklemede'", con);
            OleDbDataReader dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                if (dr["is_durum"].ToString() == "Beklemede" && dr["ID"].ToString() == DDLisSec.SelectedValue.ToString())
                {
                    OleDbCommand cmd4 = new OleDbCommand("UPDATE Temsilci set Tipdurum=1 where Tipdurum=2 AND ID=" + DDLisSec.SelectedValue + " AND personel_id=" + Session["UserID"], con);
                    cmd4.ExecuteNonQuery();
                    OleDbCommand cmd3 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=2 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                    cmd3.ExecuteNonQuery();
                    OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Temsilci.ID,Temsilci.personel_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Temsilci where Temsilci.Tipdurum=1 and Temsilci.personel_id=" + Session["UserID"], con);
                    cmd7.ExecuteNonQuery();

                    Response.Write("Beklemede olanlar çalıştı");
                }
                else
                {
                    //Response.Write(DDLisSec.SelectedValue);
                    OleDbCommand cmd4 = new OleDbCommand("UPDATE Temsilci set Tipdurum=1 where ID=" + DDLisSec.SelectedValue + " AND personel_id=" + Session["UserID"], con);
                    cmd4.ExecuteNonQuery();
                    OleDbCommand cmd3 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=2 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                    cmd3.ExecuteNonQuery();
                    //OleDbCommand cmd4 = new OleDbCommand("INSERT INTO Gorevler(is_tanimi,kull_id,durum) values ('" + DDLisSec.SelectedValue + "','" + Session["UserID"] + "',1)", con);
                    //cmd4.ExecuteNonQuery();
                    //OleDbCommand cmd3 = new OleDbCommand("UPDATE Temsilci set temsilcigorevid=Gorevler.ID WHERE Temsilci.ID='" + DDLisSec.SelectedValue + "'", con);
                    //cmd3.ExecuteNonQuery();
                    //OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Gorevler.ID,Gorevler.kull_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Gorevler where Gorevler.durum=1 and Gorevler.kull_id=" + Session["UserID"], con);
                    //cmd7.ExecuteNonQuery();
                    OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Temsilci.ID,Temsilci.personel_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Temsilci where Temsilci.Tipdurum=1 and Temsilci.personel_id=" + Session["UserID"], con);
                    cmd7.ExecuteNonQuery();
                    Response.Write("Null lar çalıştı");
                }

            }

                    //OleDbCommand cmd6 = new OleDbCommand("UPDATE GorevHareket set StartTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' Where [ID] = (SELECT MAX([ID]) FROM GorevHareket)", con);
                    //cmd6.ExecuteNonQuery();

        //cmd.ExecuteNonQuery();

            btnisBaslat.Visible = false;
            btnisDurdur.Visible = true;
            rbtnBekle.Visible = true;
            rbtnBitir.Visible = true;
            con.Close();
            dr.Close();

    }
    protected void btnisDurdur_Click(object sender, EventArgs e)
    {

        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("Database1.accdb") + "");
            con.Open();
            //OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
            //cmd.ExecuteNonQuery();
            //OleDbCommand cmd2 = new OleDbCommand("update Gorevler set bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where kull_id=" + Session["UserID"], con);
            //// OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler SET bitis_zamani='"+ DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")+ "',kull_id='"+Session["UserID"]+"' FROM Gorevler INNER JOIN Personel ON Personel.ID=Gorevler.kull_id WHERE kull_id="+Session["UserID"],con);

            //OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler INNER JOIN Personel ON Gorevler.kull_id=Personel.ID SET bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "',kull_id='" + Session["UserID"] + "' WHERE kull_id=" + Session["UserID"], con);
            //cmd2.ExecuteNonQuery();
            //OleDbDataReader dr = cmd.ExecuteReader();
            btnisDurdur.Visible = false;
            btnisBaslat.Visible = true;
            if(rbtnBekle.Checked==true)
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("update Temsilci set Tipdurum=2 WHERE ID=" + DDLisSec.SelectedValue + " and Tipdurum=1 and personel_id=" + Session["UserID"], con);
                cmd2.ExecuteNonQuery();
                OleDbCommand cmd4 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=1 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                cmd4.ExecuteNonQuery();
                OleDbCommand cmd5 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,Tip,StartTime,SessionId) SELECT Temsilci.ID,'2' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime,Temsilci.personel_id From Temsilci where Tipdurum=2 AND ID=" + DDLisSec.SelectedValue + " AND Temsilci.personel_id=" + Session["UserID"], con);
                cmd5.ExecuteNonQuery();
                OleDbCommand cmd3 = new OleDbCommand("update Temsilci set is_durum='Beklemede' where ID="+DDLisSec.SelectedValue+" and personel_id="+Session["UserID"], con);
                cmd3.ExecuteNonQuery();

                //OleDbCommand cmd2 = new OleDbCommand("Select top 1 * from Gorevler where kull_id="+Session["UserID"]+" Order by ID DESC",con);
                //OleDbDataReader dr = cmd2.ExecuteReader();
                //while (dr.Read())
                //{
                //    Response.Write(dr["is_tanimi"].ToString());
                //}
            }
            else if (rbtnBitir.Checked == true)
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler SET bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "',is_durum='Bitti' where is_tanimi='" + DDLisSec.SelectedValue + "' and [ID] = (SELECT MAX([ID]) FROM Gorevler)", con);
                cmd2.ExecuteNonQuery();
                OleDbCommand cmd3 = new OleDbCommand("update Temsilci set is_durum='Bitti' where isin_adi='" + DDLisSec.SelectedValue + "'and personel_id=" + Session["UserID"], con);
                cmd3.ExecuteNonQuery();
            }
            else
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("update Gorevler set bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where kull_id=" + Session["UserID"], con);
                cmd2.ExecuteNonQuery();
            }
            rbtnBekle.Visible = false;
            rbtnBitir.Visible = false;

            con.Close();

    }

    protected void DDLisSec_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

}

Comment: I couldn't do that for above 4 weeks. and lastly i share here. I hope you can help. thank you so much.
Comment: Use parameters to avoid sql injection and formatting errors.  You make it difficult to answer your question because you posted a wall of code.  Limit your code examples to just the minimal required.
Comment: i'm already solved the problem. thx for suggestion :)
Answer: **I made it like this and it worked. Sadly nobody answers this :/ Belki birinin işine yarar **
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Configuration;

    protected void btnisBaslat_Click(object sender, EventArgs e)
    {

            OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("Database1.accdb") + "");
            con.Open();
            //OleDbCommand cmd = new OleDbCommand("update Personel set is_Tanimi='" + txtisTanimi.Text + "', baslangic_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where ID = " + Session["UserID"], con);
            OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='true' where ID=" + Session["UserID"], con);
            cmd.ExecuteNonQuery();
            //OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Gorevler(Kadi,is_tanimi,baslangic_zamani,kull_id) values ('" + Session["Adi"] + "','" + DDLisSec.SelectedValue + "','" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "','" + Session["UserID"] + "')", con);
            //cmd2.ExecuteNonQuery();
            OleDbCommand cmd6 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE StartTime IS NOT NULL AND EndTime IS NULL AND SessionId=" + Session["UserID"], con);
            cmd6.ExecuteNonQuery();

            OleDbCommand cmd2 = new OleDbCommand("Select * from Temsilci where ID=" + DDLisSec.SelectedValue, con);
            OleDbDataReader dr = cmd2.ExecuteReader();
            while (dr.Read())
            {
                if (dr["is_durum"].ToString() == "Beklemede")
                {
                    OleDbCommand cmd4 = new OleDbCommand("UPDATE Temsilci set Tipdurum=1 where Tipdurum=2 AND ID=" + DDLisSec.SelectedValue + " AND personel_id=" + Session["UserID"], con);
                    cmd4.ExecuteNonQuery();
                    OleDbCommand cmd3 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=2 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                    cmd3.ExecuteNonQuery();
                    OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Temsilci.ID,Temsilci.personel_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Temsilci where Temsilci.Tipdurum=1 and Temsilci.personel_id=" + Session["UserID"], con);
                    cmd7.ExecuteNonQuery();

                    Response.Write("Beklemede olanlar çalıştı");
                }
                else
                {
                    //Response.Write(DDLisSec.SelectedValue);
                    OleDbCommand cmd4 = new OleDbCommand("UPDATE Temsilci set Tipdurum=1 where ID=" + DDLisSec.SelectedValue + " AND personel_id=" + Session["UserID"], con);
                    cmd4.ExecuteNonQuery();
                    OleDbCommand cmd3 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=2 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                    cmd3.ExecuteNonQuery();
                    //OleDbCommand cmd4 = new OleDbCommand("INSERT INTO Gorevler(is_tanimi,kull_id,durum) values ('" + DDLisSec.SelectedValue + "','" + Session["UserID"] + "',1)", con);
                    //cmd4.ExecuteNonQuery();
                    //OleDbCommand cmd3 = new OleDbCommand("UPDATE Temsilci set temsilcigorevid=Gorevler.ID WHERE Temsilci.ID='" + DDLisSec.SelectedValue + "'", con);
                    //cmd3.ExecuteNonQuery();
                    //OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Gorevler.ID,Gorevler.kull_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Gorevler where Gorevler.durum=1 and Gorevler.kull_id=" + Session["UserID"], con);
                    //cmd7.ExecuteNonQuery();
                    OleDbCommand cmd7 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,SessionId,Tip,StartTime) SELECT Temsilci.ID,Temsilci.personel_id,'1' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime From Temsilci where Temsilci.Tipdurum=1 and Temsilci.personel_id=" + Session["UserID"], con);
                    cmd7.ExecuteNonQuery();
                    Response.Write("Null lar çalıştı");
                }

            }

                    //OleDbCommand cmd6 = new OleDbCommand("UPDATE GorevHareket set StartTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' Where [ID] = (SELECT MAX([ID]) FROM GorevHareket)", con);
                    //cmd6.ExecuteNonQuery();

        //cmd.ExecuteNonQuery();

            btnisBaslat.Visible = false;
            btnisDurdur.Visible = true;
            rbtnBekle.Visible = true;
            rbtnBitir.Visible = true;
            con.Close();
            dr.Close();

    }
    protected void btnisDurdur_Click(object sender, EventArgs e)
    {

        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("Database1.accdb") + "");
            con.Open();
            //OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
            //cmd.ExecuteNonQuery();
            //OleDbCommand cmd2 = new OleDbCommand("update Gorevler set bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where kull_id=" + Session["UserID"], con);
            //// OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler SET bitis_zamani='"+ DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")+ "',kull_id='"+Session["UserID"]+"' FROM Gorevler INNER JOIN Personel ON Personel.ID=Gorevler.kull_id WHERE kull_id="+Session["UserID"],con);

            //OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler INNER JOIN Personel ON Gorevler.kull_id=Personel.ID SET bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "',kull_id='" + Session["UserID"] + "' WHERE kull_id=" + Session["UserID"], con);
            //cmd2.ExecuteNonQuery();
            //OleDbDataReader dr = cmd.ExecuteReader();
            btnisDurdur.Visible = false;
            btnisBaslat.Visible = true;
            if(rbtnBekle.Checked==true)
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("update Temsilci set Tipdurum=2 WHERE ID=" + DDLisSec.SelectedValue + " and Tipdurum=1 and personel_id=" + Session["UserID"], con);
                cmd2.ExecuteNonQuery();
                OleDbCommand cmd4 = new OleDbCommand("update GorevHareket set EndTime='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE Tip=1 AND EndTime IS NULL AND GorevId=" + DDLisSec.SelectedValue + " AND SessionId=" + Session["UserID"], con);
                cmd4.ExecuteNonQuery();
                OleDbCommand cmd5 = new OleDbCommand("INSERT INTO GorevHareket(GorevId,Tip,StartTime,SessionId) SELECT Temsilci.ID,'2' AS Tip,'" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' AS StartTime,Temsilci.personel_id From Temsilci where Tipdurum=2 AND ID=" + DDLisSec.SelectedValue + " AND Temsilci.personel_id=" + Session["UserID"], con);
                cmd5.ExecuteNonQuery();
                OleDbCommand cmd3 = new OleDbCommand("update Temsilci set is_durum='Beklemede' where ID="+DDLisSec.SelectedValue+" and personel_id="+Session["UserID"], con);
                cmd3.ExecuteNonQuery();

                //OleDbCommand cmd2 = new OleDbCommand("Select top 1 * from Gorevler where kull_id="+Session["UserID"]+" Order by ID DESC",con);
                //OleDbDataReader dr = cmd2.ExecuteReader();
                //while (dr.Read())
                //{
                //    Response.Write(dr["is_tanimi"].ToString());
                //}
            }
            else if (rbtnBitir.Checked == true)
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("UPDATE Gorevler SET bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "',is_durum='Bitti' where is_tanimi='" + DDLisSec.SelectedValue + "' and [ID] = (SELECT MAX([ID]) FROM Gorevler)", con);
                cmd2.ExecuteNonQuery();
                OleDbCommand cmd3 = new OleDbCommand("update Temsilci set is_durum='Bitti' where isin_adi='" + DDLisSec.SelectedValue + "'and personel_id=" + Session["UserID"], con);
                cmd3.ExecuteNonQuery();
            }
            else
            {
                OleDbCommand cmd = new OleDbCommand("update Personel set tiklama='false' where ID=" + Session["UserID"], con);
                cmd.ExecuteNonQuery();
                OleDbCommand cmd2 = new OleDbCommand("update Gorevler set bitis_zamani='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' where kull_id=" + Session["UserID"], con);
                cmd2.ExecuteNonQuery();
            }
            rbtnBekle.Visible = false;
            rbtnBitir.Visible = false;

            con.Close();

    }

}


Chained methods and continuation indent in Intellij

Question: I've never figured out how to make Intellij handle continuation indent for chained methods properly, and apparently today is the day it's annoyed me enough to consult you lovely people.
What I want is this:
makeAThing(
  "with",
  "params"
)
.setProperty("with some more params")
.start();

What I get is this:
makeAThing(
  "with",
  "params"
)
  .setProperty("with some more params")
  .start();

I get this in Java, Groovy, JavaScript and a bunch of other places.  How can I persuade Intellij not to add continuation indent after a chained method call?
Comment: This comes up a lot when using angular.js, because the convention is to break lines when defining modules.
Comment: We badly need this for `SwiftUI` too in AppCode
Answer: I just switched to intellij and also have found this rather annoying.
Only found two solutions:

forcing the coding style to have 0 for "continuation indent" which I'm starting to like anyway albeit not very canonical Java.
Turing off the formatter for blocks of code and press shift tab

Works for Java not sure for JS:
// @formatter:off
...
// @formatter:on


Does it make a difference whether I make a panel active or inactive?

Question: When hacking a wall panel successfully (the sort where you are met with a handprint after interacting), you are greeted with two options: active and inactive.
There appears to be no visual difference to the panel between clicking either of these options, and I can't interact with the panel again to change my choice, so what effect, if any, does clicking on either of the two buttons do?
Comment: You mean the alarm panels? I'm pretty sure if it's set to "inactive" guards can use it to trigger an alert.
Comment: All you're doing is disabling the panels so that guards can't use them. (Allows you to more-easily get the `Smooth Operator` reward in some cases, but seldom necessary.)
Answer: The panels with a handprint on them are alarm panels. My understanding is that if an enemy panics and hits one, it will alarm the facility and send them running.
By disabling it you will keep them from alerting the whole facility, should an enemy make it to one.
Update: I went and got myself into a situation where some guards panicked. They ran to the panel, but since I hacked everything in the area already it did nothing while they used it. This can give you time to line up a headshot if you wish or run up for a takedown.
Comment: Just as an addendum - if you hack and disable all the panels and then the alarm is set off some other way (e.g. detected by a camera), you _won't_ be able to use a panel to disable the alarm!
Comment: @Kromey I just hack everything for the XP. ;)
Comment: Huh. I'd been ignoring those. Maybe it's time I start hacking them...
Comment: I meant that I didn't hack them because I didn't know they could be hacked; that they can be hacked *and* disable those pesky alarms is just icing on the cake as far as I'm concerned!


Remove 2d slice from 3d numpy array

Question: I need to remove the last arrays from a 3D numpy cube. I have:
a = np.array(
[[[1,2,3],
 [4,5,6],
 [7,8,9]],

[[9,8,7],
 [6,5,4],
 [3,2,1]],

[[0,0,0],
 [0,0,0],
 [0,0,0]],

[[0,0,0],
 [0,0,0],
 [0,0,0]]])

How do I remove the arrays with zero sub-arrays like at the bottom side of the cube, using np.delete?
(I cannot simply remove all zero values, because there will be zeros in the data on the top side)
Comment: Did either of the posted solutions work for you? Any feedback on the solutions?
Answer: For a 3D cube, you might check all against the last two axes
a = np.asarray(a)
a[~(a==0).all((2,1))]

array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])

Comment: If one is specifically looking for zeros, one could even do `a[a.any((2, 1))]`, since `0` is considered equivalent to `False`.  Makes the code a bit less readable for a negligible speedup though.
Answer: If you know where they are already, the easiest thing to do is slice them off:
a[:-2]

Results in:
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])

Answer: Here's one way to remove trailing all zeros slices, as mentioned in the question that we want to keep the all zeros slices in the data on the top side -
a[:-(a==0).all((1,2))[::-1].argmin()]

Sample run -
In [80]: a
Out[80]:
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])

In [81]: a[:-(a==0).all((1,2))[::-1].argmin()]
Out[81]:
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])

Answer: Hope this helps,
a_new=[] #Create a empty list
for item in a:
        if not (np.count_nonzero(item) == 0): #check if inner matrix is empty or not
            a_new.append(item) #appending to inner matrix to the list

a_new=np.array(a_new) #creating numpy matrix with removed zero elements

Output:
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])

Answer: Use any and select :)
a=np.array([[[1,2,3],
 [4,5,6],
 [7,8,9]],

[[9,8,7],
 [6,5,4],
 [3,2,1]],

[[0,0,0],
 [0,0,0],
 [0,0,0]],

[[0,0,0],
 [0,0,0],
 [0,0,0]]])
a[a.any(axis=2).any(axis=1)]

Remove 2d slice from 3d numpy array


Using Transactions and Facade in JPA 2

Question: I am creating a Java EE web application which will operate on a database using JPA 2 EclipseLink. I am also using the application-managed Entity Managers so I could manually setup transactions, although I am not sure about a few things.
Initial information (for purpose of this post only because there are details/design parts)
I have JPA Entities:
UserEntity and UserDetailsEntity
While creating a new user I have to create instances of both entities which are linked together.
While using a wizard to create JSF Pages from Entity classes I noticed that NetBeans created an AbstractFacade and an Enterprise Java Bean implementing that Facade: UserFacade and UserDetailsFacade. These EJBs are basic wrappers around JPA CRUD operations.
Questions:

Is the Facade pattern really useful, especially in my situation when I want to combine few JPA operations in a specific transaction? Is this pattern good/bad for my design and why?
Will the transaction mechanism work if I have "transaction process in UserManagement", but instead of executing .persist directly from within a transaction block I am executing wrapper methods:
    utx.begin();
    userFacade.create(userEntity);
    userDetailsFacade.create(userDetailsEntity);
    utx.commit();

I am not sure about the EntityManager, should I have more than one instance of it? Apart from user authentication (to know the currently logged in user) I don't see a reason for keeping one instance of EntityManager. I think I could just use EntityManagerFactory to obtain instances every time I need them. But what concerns me is the performance here and good/bad design practices. Or should I keep one EntityManager (obtained somewhere in a config class and shared through Singleton or CDI?)
Would it be good design to have a structure like: JSF Pages with Forms -> ManagementBean gathering information and passing it accordingly to the right EJB Beans -> EJB beans would do business methods and pass information to Facade EJBs responsible for CRUD -> FacadeEJBs would persist information.

Code for AbstractFacade:(Draft)
public abstract class AbstractFacade<T> {
private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
    this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity) {
    getEntityManager().persist(entity);
}

public void edit(T entity) {
    getEntityManager().merge(entity);
}

public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {
    return getEntityManager().find(entityClass, id);
}

public List<T> findAll() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    return getEntityManager().createQuery(cq).getResultList();
}

public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(range[1] - range[0]);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(getEntityManager().getCriteriaBuilder().count(rt));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

}
Code for UserFacade(Draft, because I will modify this class to retreive EntityManagers from the Factory rather than using CDI):
@Stateless
public class UserEntityFacade extends AbstractFacade<UserEntityEntity> {
@PersistenceContext(unitName = "FMSBetaPU")
private EntityManager em;

@Override
protected EntityManager getEntityManager() {
    return em;
}

public TestEntityFacade() {
    super(TestEntity.class);
}

}

Code for UserManagement EJB (Draft)
@Stateless
public class UserManagement {

@Resource
private UserTransaction utx;
@EJB
private UserEntityFacade userFacade;
@EJB
private UserDetailsEntityFacade userDetailsFacade;

public void createUser(int id, String name)
{
    UserEntity userEntity = new UserEntity(id);
    UserDetailsEntity userDetailsEntity = new UserDetailsEntity(name);
    try {
            utx.begin();
            userFacade.create(userEntity);
            userDetailsFacade.create(userDetailsEntity);
            utx.commit();
        }
    catch (Exception e) {
            try {
                utx.rollback();
            } catch (IllegalStateException ex) {
                Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SystemException ex) {
                Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}

}

Answer:
EntityManager, should I have more than one instance of it?

The entityManager is like your current database session. So using a singleton for it is really really bad design. It's not thread safe. It holds references (thanks it's associated persistenceContext) to all objects fetched from the DB, so it is supposed to be a short-time-living object.
Regarding performance : creating an entityManager from the entityManagerFactory is really fast. (on the other hand creating an entityManagerFactory cost a lot... so it is good practice to have a singleton for the entityManagerFactory)

Using Transactions and Facade in JPA 2