Q: Access value of Struct data I need to access value in a struct defined as mydata:struct<1:array<int>>.
I tried accessing using mydata.1 but it is not a valid syntax.
Sample data {1=[154873, 155630, 157698, 157945, 159058, 163148]}

A: Simply quote the 1 with double quotes:
SELECT mydata."1" FROM my_table

A: This can be queried using unnest operator.You can use below query to fetch the items from array :
select t1.* from test cross join UNNEST("mydata"."1") as t1(record);


Q: Disable -Wreturn-type checking I am trying to compile Model 5.0 under OS X 10.8.3
I am getting a lot of warnings and errors while compiling. Several of those error are something like
xwin.c:31523:2: error: non-void function 'scrfrg' should return a value
      [-Wreturn-type]
        return;

What flag in C/C++ checks that? I want to disable it and try to finish the compilation.
I'm not sure if this is the best forum to ask this, sorry for the inconvenience.

A: As per the link you posted, seems you're using gcc. You can disable a lot of error/warning checks with a -Wno-xxxx flag, in your case -Wreturn-type is causing an error so you can disable it with:
-Wno-return-type
Frankly, it's better to just fix the errors/warnings when you can, and that one seems easy to fix.


Q: Spark createdataframe cannot infer schema - default data types? I am creating a spark dataframe in databricks using createdataframe and getting the error:
'Some of types cannot be determined after inferring'

I know I can specify the schema, but that does not help if I am creating the dataframe each time with source data from an API and they decide to restructure it.
Instead I would like to tell spark to use 'string' for any column where a data type cannot be inferred.
Is this possible?

A: This can be easily handled with schema evaluation with delta format. Quick ref: https://databricks.com/blog/2019/09/24/diving-into-delta-lake-schema-enforcement-evolution.html


Q: Add RSS feed to a section of a View in Codeigniter I am completely new to Codeigniter and am trying to add an RSS feed to a section of my Home view as follows. I have asked this question already but I wasn't clear in how I presented my code so I have submitted it again. I have researched this on multiple forums especially this one and I am going round in circles but cant find an answer.
Home View
The home view contains a header image, a nav bar, a jumbotron and a login form. It also has the following section into which I want to add the RSS content.

Latest News

<?php

// RSS FEED HERE

?>

I have one controller called "User that has the following code in its index function
User Controller Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller{

public function __construct()
{

  parent::__construct();
  $this->load->model('user_model');
  $this->load->library('rssparser');

}

 public function index()
 {

  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }

 else
 {

 $data['title']= 'Home';
 $this->load->view('include/header',$data);
 $this->load->view('pages/home.php', $data);
 $this->load->view('include/footer',$data);

 }

}

Controller method in User Controller to get RSS data
The rss feed results are currently being stored in an unordered list
 public function get_news()
 {

 // Get 6 items from latest news
 $this->rssparser->set_feed_url('http://www.datadomain.com');  // get feed
 $this->rssparser->set_cache_life(30);  // Set cache life time in minutes
 $rss = $this->rssparser->getFeed(6);

 echo '
';

foreach ($rss as $item)

{
   echo '
';
   echo $item['title'];
   echo '
';

   echo '
';
   echo $item['description'];
   echo '
';

   echo '
';
   echo $item['link'];
   echo '
';

   echo '
';
   echo $item['pubDate'];
   echo '
';
}

echo '
';
}

If I insert the following into my index function in my controller I can get the feed on my homepage but it appears at the top of the page and not in the section I need it in.
$data['rss'] = $this->get_news();

I have tried adding $rss into the section of the view in my Home page but I just get an undefined variable error.
I would appreciate if someone could help shed some light on this for me as I cant find a solution.
Other methods and views used in my project
Controller method Welcome()
public function welcome()
{
 $data['title']= 'Welcome';
 $this->load->view('include/header',$data);
 $this->load->view('pages/welcome_view.php', $data);
 $this->load->view('include/footer',$data);
 }

welcome_view
This view represents the members area of the application. It doesn't hold any real content at the minute because the application is at the early stages of construction.

<img class="img-responsive" src="<?php echo site_url('../images/black_header.jpg'); ?>"   />

 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs- example-navbar-collapse-1">
  Toggle navigation

  </button>
  <a class="navbar-brand" href="<?php echo site_url('user/index') ?>">Premier Games

<a href="<?php echo site_url('user/index') ?>">Home

<a href="<?php echo site_url('user/register') ?>">Register

Signed in as <?php echo $this->session->userdata('user_name'); ?>

<?php echo $this->session->userdata('user_name'); ?>, Welcome Back

This section represents the area that only logged in members can access.

<?php echo anchor('user/logout', 'Logout'); ?>

A: Typically, you do the html parsing in a view. Not sure if you are loading a view... it isn't clear whether we are working with a logged in user or not.
Let's assume we are not dealing with a logged in user and are calling
 $data['title']= 'Home';
 $this->load->view('include/header',$data);
 $this->load->view('pages/home.php', $data);
 $this->load->view('include/footer',$data);

The easiest way to do it would be to just dump the data into the view and do the layout/parsing there:
controller:
$data['title']= 'Home';
$data['rss'] = $this->get_news();
$this->load->view('include/header',$data);
$this->load->view('pages/home.php', $data);
$this->load->view('include/footer',$data);

pages/home.php

<?php
echo '
';

foreach ($rss as $item)

{
   echo '
';
   echo $item['title'];
   echo '
';

   echo '
';
   echo $item['description'];
   echo '
';

   echo '
';
   echo $item['link'];
   echo '
';

   echo '
';
   echo $item['pubDate'];
   echo '
';
}

echo '
';
?>

controller get_news():
public function get_news()
{
    // Get 6 items from GAA latest news
    $this->rssparser->set_feed_url('http://www.rte.ie/rss/gaa.xml');  // get feed
    $this->rssparser->set_cache_life(30);  // Set cache life time in minutes
    $rss = $this->rssparser->getFeed(6);
    return $rss;
}


Q: Cordova APP - Is it possible to show camera feed in a container? I am using ionicFramework with Cordova to build an App. My requirement is to show (front) camera feed inside my app (say at top right corner of the app).
Unfortunately "cordovaCapture" is not working for me. "navigator.camera" just opens camera view, but my requirement is to show its feed in a container so its also not fitting in requirement.
I tried backgroundvideo plugin also.
Please help me in understanding, Is it possible to access camera feed without going native app approach ? Please share any leads.
Thanks in Advance.

A: I'll just point you to the right direction:

*

*https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview

*https://github.com/donaldp24/CanvasCameraPlugin
Try these plugins (in order) and lemme know if either of them worked out for you.


Q: What's a functional replacement for if-then statements? I've been learning F# and functional programming and trying to do things the functional way. However, when it comes to rewriting some code I'd already written in C# I get stuck at simple if-then statements (ones that only do something, not return a value). I know you can pull this off in F#:
if expr then do ()

However, I thought this was an imperative approach to coding? Maybe I've not learned enough about functional programming, but it doesn't seem functional to me. I thought the functional approach was to compose functions and expressions, not simply execute statements one after the other which is what if-then seems to encourage.
So, am I missing something and if-then is perfectly fine in the functional world? If not, what is the functional equivalent of such a statement? How could I take an if-then and turn it functional?
Edit: I might've asked the wrong question (sorry, still fairly new to functional programming): Let's take a real world example that made me even ask this:
if not <| System.String.IsNullOrWhiteSpace(data) then do
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    let postStream : System.IO.Stream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length)
    postStream.Flush()
    postStream.Dispose()

The body of that if-then doesn't return anything, but I don't know how I could make this more functional (if that's even possible). I don't know the proper technique for minimizing imperative code. Given F#'s nature it's fairly easy to just transport my C# directly, but I'm having difficulties turning it functional. Every time I reach such an if statement in C#, and I'm trying to transport it to F#, I get discouraged that I can't think of a way to make the code more functional.

A: It's considered functional if your if statement has a return value and does not have side effects.
Suppose you wanted to write the equivalent of:
if(x > 3) n = 3; else n = x;
Instead of doing that, you use the return statement from the if command:
let n = (if x > 3 then 3 else x)
This hypothetical if is suddenly functional because it has no side effects; it only returns a value.  Think of it as if it were the ternary operator in some languages:  int n = x>3?3:x;

A: An important point that hasn't been mentioned so far is the difference between if .. then .. else and if .. then without the else branch.
If in functional languages
The functional interpretation of if is that it is an expression that evaluates to some value. To evaluate the value of if c then e1 else e2 you evaluate the condition c and then evaluate either e1 or e2, depending on the condition. This gives you the result of the if .. then .. else.
If you have just if c then e, then you don't know what the result of the evaluation should be if c is false, because there is no else branch! The following clearly does not make sense:
let num = if input > 0 then 10

In F#, expressions that have side-effects like printf "hi" return a special value of type unit. The type has only a single value (written as ()) and so you can write if which does an effect in just a single case:
let u = if input > 0 then printf "hi" else ()

This always evaluates to unit, but in the true branch, it also performs the side-effect. In the false branch, it just returns a unit value. In F#, you don't have to write the else () bit by hand, but conceptually, it is still there. You can write:
let u = if input > 0 then printfn "hi"

Regarding your additional example
The code looks perfectly fine to me. When you have to deal with API that is imperative (like lots of the .NET libraries), then the best option is to use the imperative features like if with a unit-returning branch.
You can use various tweaks, like represent your data using option<string> (instead of just string with null or empty string). That way, you can use None to represent missing data and anything else would be valid input. Then you can use some higher-order functions for working with options, such as Option.iter, which calls a given function if there is a value:
maybeData |> Option.iter (fun data ->
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    use postStream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length) )

This is not really less imperative, but it is more declarative, because you don't have to write the if yourself. BTW: I also recommend using use if you want to Dispose object auotmatically.

A: There are two observations that can assist in the transition from imperative to functional ("everything is an expression") programming:

*

*unit is a value, whereas an expression returning void in C# is treated as a statement. That is, C# makes a distinction between statements and expressions. In F# everything is an expression.

*In C# values can be ignored; in F# they cannot, therefore providing a higher level of type safety. This explicitness makes F# programs easier to reason about and provides greater guarantees.

A: There's nothing wrong with if-then in functional world.
Your example is actually similar to let _ = expr since expr has side effects and we ignore its return value. A more interesting example is:
if cond then expr

which is equivalent to:
match cond with
| true -> expr
| false -> ()

if we use pattern matching.
When the condition is simple or there is only one conditional expression, if-then is more readable than pattern matching. Moreover, it is worth to note that everything in functional programming is expression. So if cond then expr is actually the shortcut of if cond then expr else ().
If-then itself is not imperative, using if-then as a statement is an imperative way of thinking. From my experience, functional programming is more about the way of thinking than concrete control flows in programming languages.
EDIT:
Your code is totally readable. Some minor points are getting rid of redundant do keyword, type annotation and postStream.Dispose() (by using use keyword):
if not <| System.String.IsNullOrWhiteSpace(data) then
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    use postStream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length)
    postStream.Flush()

A: It's not the if-expression that's imperative, it's what goes in the if-expression. For example, let abs num = if num < 0 then -num else num is a totally functional way to write the abs function. It takes an argument and returns a transformation of that argument with no side effects. But when you have "code that only does something, not return a value," then you're writing something that isn't purely functional. The goal of functional programming is to minimize the part of your program that can be described that way. How you write your conditionals is tangential.

A: In order to write complex code, you need to branch at some point.  There's a very limited number of ways you can do that, and all of them require a logical flow through a section of code.  If you want to avoid using if/then/else it's possible to cheat with loop/while/repeat - but that will make your code far less reasonable to maintain and read.
Functional programming doesn't mean you shouldn't execute statements one after the other - it simply means that you shouldn't have a mutable state.  Each function needs to reliably behave the same way each time it is called.  Any differences in how data is handled by it need to be accounted for by the data that is passed in, instead of some trigger that is hidden from whatever is calling the function.
For example, if we have a function foo(int, bool) that returns something different depending on whether bool is true or false, there will almost certainly be an if statement somewhere in foo().  That's perfectly legitimate.  What is NOT legitimate is to have a function foo(int) that returns something different depending on whether or not it is the first time it is called in the program.  That is a 'stateful' function and it makes life difficult for anyone maintaining the program.

A: My apologies for not knowing F#, but here is one possible solution in javascript:
function $if(param) {
    return new Condition(param)
}

function Condition(IF, THEN, ELSE) {
    this.call = function(seq) {
        if(this.lastCond != undefined)
            return this.lastCond.call(
                sequence(
                    this.if,
                    this.then,
                    this.else,
                    (this.elsif ? this.elsif.if : undefined),
                    seq || undefined
                )
            );
         else
            return sequence(
                this.if,
                this.then,
                this.else,
                (this.elsif ? this.elsif.if : undefined),
                seq || undefined
            )
    }

    this.if   = IF ? IF : f => { this.if = f; return this };
    this.then = THEN ? THEN : f => { this.then = f; return this };
    this.else = ELSE ? ELSE : f => { this.else = f; return this };
    this.elsif = f => {this.elsif = $if(f); this.elsif.lastCond = this; return this.elsif};
}

function sequence(IF, THEN, ELSE, ELSIF, FINALLY) {
    return function(val) {
        if( IF(val) )
            return THEN();

        else if( ELSIF && ELSIF(val) )
            return FINALLY(val);

        else if( ELSE )
            return ELSE();

        else
            return undefined

    }
}}

The $if function returns an object with the if..then..else..elsif construct, using the Condition constructor.
Once you call Condition.elsif() you'll create another Condition object - essentially creating a linked list that can be traversed recursively using sequence()
You could use it like:
var eq = val => x => x == val ? true : false;

$if( eq(128) ).then( doStuff ).else( doStuff )
.elsif( eq(255) ).then( doStuff ).else( doStuff ).call();

However, I realize that using an object is not a purely functional approach. So, in that case you could forgo the object all together:
sequence(f, f, f, f,
    sequence(f, f, f, f
        sequence(f, f, f)
    )
);

You can see that the magic is really in the sequence() function.
I won't try to answer your specific question in javascript. But I think the main point is that you should make a function that will run arbitrary functions under an if..then statement, then nest multiples of that function using recursion to create a complex logical chain. At least this way you will not have to repeat yourself ;)
This code is just a prototype so please take it as a proof of concept and let me know if you find any bugs.


Q: Google Spreadsheet Script Trigger: This app is blocked I am trying to create a trigger for a script in google spreadsheet and upon trying to save the trigger I am getting the following error:

This app is blocked This app tried to access sensitive info in your
Google Account. To keep your account safe, Google blocked this access.

I don't have G-Suite, I don't have an organization, I am simply using my personal Gmail account. I don't have the special account protection thing enabled. I tried using different scripts, even an empty script.
What could be the problem here? I have used scripts and add-ons in the past, but haven't needed triggers yet. Is there another way to run a script daily or monthly, without this trigger functionality?

A: There is currently a bug
I recommend oyu to "star" it to increase visibility, so it hopefully gets fixed soon.

A: Try this:
Unable to open Google xlsx spreadsheet / Also Google Drive permission Blocked
The same solution logic can solve this problem.
[ ]


Q: How to call method on a child React.Component from a parent React.FunctionalComponent? How can I call a method on a child component from a parent component? I'm not sure it matters but my parent component is a functional component and the child is a class component. I'm hoping that the switch to function components doesn't mean that all class-based components need to be upgraded?
The parent component looks like this:
const Home: React.FC = () => {
    const grid = useRef();
    const buttonClick = () => {
        // I want to be able to call a method on <MyGrid> here to
        // tell it to reload the grid (for example)
        grid.current!.reconfigure();
    };

    return (
        <React.Fragment>
            <JqxButton onClick={buttonClick}>Refresh Grid</JqxButton>
            <MyGrid ref={grid} />
        </React.Fragment>
    );
};

This actually works, though not without errors (which don't seem to crash the app in code sandbox, but it won't compile in VS Code offline). The 'ref' property on MyGrid shows this error:
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: MyGrid | null) => void) | RefObject<MyGrid> | null | undefined'.
  Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<MyGrid>'.
    Types of property 'current' are incompatible.
      Type 'undefined' is not assignable to type 'MyGrid | null'.ts(2322)

My call to grid.current!.reconfigure() results in this error:
Property 'reconfigure' does not exist on type 'never'.

I've created a code sandbox with the full setup of the parent and child components here: https://codesandbox.io/s/react-fc-call-child-component-14rr3


Q: How to access a variable from another script in another gameobject through GetComponent? I've searched around and I just can't get this to work. I think I just don't know the proper syntax, or just doesn't quite grasp the context.
I have a BombDrop script that holds a public int. I got this to work with public static, but Someone said that that is a really bad programming habit and that I should learn encapsulation. Here is what I wrote:
BombDrop script:
 <!-- language: c# -->

 public class BombDrop : MonoBehaviour {

 public GameObject BombPrefab;

 //Bombs that the player can drop
 public int maxBombs = 1;

 // Update is called once per frame
 void Update () {

 if (Input.GetKeyDown(KeyCode.Space)){

         if(maxBombs > 0){
         DropBomb();

         //telling in console current bombs
         Debug.Log("maxBombs = " + maxBombs);
         }
   }

 }

 void DropBomb(){

     // remove one bomb from the current maxBombs
     maxBombs -= 1;

     // spawn bomb prefab
     Vector2 pos = transform.position;
     pos.x = Mathf.Round(pos.x);
     pos.y = Mathf.Round(pos.y);
     Instantiate(BombPrefab, pos, Quaternion.identity);

 }
}

So I want the Bomb script that's attached to the prefabgameobject Bombprefab to access the maxBombs integer in BombDrop, so that when the bomb is destroyed it adds + one to maxBombs in BombDrop.
And this is the Bomb script that needs the reference.
 public class Bomb : MonoBehaviour {
 // Time after which the bomb explodes
 float time = 3.0f;

 // Explosion Prefab
 public GameObject explosion;

 BoxCollider2D collider;

 private BombDrop BombDropScript;

 void Awake (){

     BombDropScript = GetComponent<BombDrop> ();
 }

 void Start () {

     collider = gameObject.GetComponent<BoxCollider2D> ();

     // Call the Explode function after a few seconds
     Invoke("Explode", time);

 }

 void OnTriggerExit2D(Collider2D other){

     collider.isTrigger = false;
 }

 void Explode() {
     // Remove Bomb from game
     Destroy(gameObject);

     // When bomb is destroyed add 1 to the max
     // number of bombs you can drop simultaneously .
     BombDropScript.maxBombs += 1;

     // Spawn Explosion
     Instantiate(explosion,
                 transform.position,
                 Quaternion.identity);

In the documentation it says that it should be something like
BombDropScript = otherGameObject.GetComponent<BombDrop>();

But that doesn't work. Maybe I just don't understand the syntax here. Is it suppose to say otherGameObject? Cause that doesn't do anything. I still get the error : "Object reference not set do an instance of an object" on my BombDropScript.maxBombs down in the explode()

A: You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null.
 GameObject g = GameObject.Find("GameObject Name");

Then you can grab the script:
 BombDrop bScript = g.GetComponent<BombDrop>();

Then you can access the variables and functions of the Script.
 bScript.foo();

I just realized that I answered a very similar question the other day, check here:
Don't know how to get enemy's health

I'll expand a bit on your question since I already answered it.
What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject.
Also use a setter and getter for maxBombs.
public class BombDrop : MonoBehaviour
{
    public void setMaxBombs(int amount)
    {
        maxBombs += amount;
    }

    public int getMaxBombs()
    {
        return maxBombs;
    }
}

A: use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it
void Start () {
     BombDropScript =gameObject.GetComponent<BombDrop> ();
     collider = gameObject.GetComponent<BoxCollider2D> ();

     // Call the Explode function after a few seconds
     Invoke("Explode", time);

 }

void Explode() {
//..
  //..
//at last
Destroy(gameObject);
 }

if you want to access a script in another gameObject you should assign the game object via inspector and access it like that
 public gameObject another;
void Start () {
     BombDropScript =another.GetComponent<BombDrop> ();
}

A: Can Use this :
entBombDropScript.maxBombs += 1;

Before :
Destroy(gameObject);

I just want to say that you can increase the maxBombs value before Destroying the game object. it is necessary because, if you destroy game object first and then increases the value so at that time the reference of your script BombDropScript will be gone and you can not modify the value's in it.


Q: C# Access to the path is denied... Client.Download(filelink, path) I've a problem with my code:
when I try to download a file from dropbox, and put it in my Roaming folder something goes wrong, here's the error Log:
System.Net.WebException: An exception occurred during a WebClient request. --->              System.UnauthorizedAccessException: Access to the path'C:\Users\Marco\AppData\Roaming\.maycraft' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)
   --- End of inner exception stack trace ---
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)
   at System.Net.WebClient.DownloadFile(String address, String fileName)
   at MayCraftLauncher.Program.downloadExist() in c:\Users\Marco\Desktop\MayCraftLauncher\C# SourceCode\MayCraftLauncher\MayCraftLauncher\Program.cs:line 71

Obviously I tried to run Visual Studio with administator rights, but nothing...
And here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Security.Principal;
using System.IO;
using System.IO.Compression;
using Ionic.Zip;

namespace MayCraftLauncher
{
    class Program
    {

        public static System.Threading.Thread existDownloading = new System.Threading.Thread(downloadExist);

        public static string userName = Environment.UserName;
        public static string path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\Exist";
        public static string maypath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft";

        static void Main(string[] args)
        {
            folderExist();
        }

        static void check1()
        {
            while (!Directory.Exists(maypath))
            {
                System.Threading.Thread.Sleep(5000);
            }

                existDownloading.Start();
        }

        static void folderExist()
        {
            if (!Directory.Exists(maypath))
            {
                System.Diagnostics.Process.Start(@"C:\Users\Marco\Desktop\MayCraftLauncher.jar");
                check1();
            }
            else
            {
                fileExist();
            }
        }

        static void fileExist()
        {
            if (File.Exists(path)) //Determina se è la prima volta che l'applicazione viene eseguita
            {
                Console.WriteLine("Exist");
                Console.ReadLine();
            }
            else
            {
                existDownloading.Start();
                Console.WriteLine("Downloading...");
            }
        }

        static void downloadExist()
        {
            WebClient Client = new WebClient();
            DateTime btime = DateTime.Now;
            path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\";
            string publicLinkExist = @"https://dl.dropbox.com/u/35356155/minecraft/download/Exist";
            //string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mods.7z";
            string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mcp.7z";
            try
            {
                //----------------File downloading-------------------
                Client.DownloadFile(publicLinkExist, path);
                DirectoryInfo dev = Directory.CreateDirectory(path);
                string devpath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft";
                Client.DownloadFile(publicLinkMods, devpath);
                DateTime atime = DateTime.Now;
                Console.WriteLine("Downloading time: " + atime.Subtract(btime).TotalSeconds + " sec.");

                //---------------Files Extracion-------------------
                using (ZipFile zip = ZipFile.Read(devpath))
                {
                    zip.ExtractAll(path);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                System.IO.File.WriteAllText(@"C:\Users\Marco\Desktop\log.txt", e.ToString());
                Console.ReadKey();
            }
            existDownloading.Abort();
        }

    }
}


Q: NSMutableArray not responding to removeObjectAtIndex: I think i've run into a confused state where i'm doing something fundamentally wrong, but i cannot understand what and why this is happening.
Picture 1: A property of a My class. A NSMutableArray.

Picture2: The code block i want to execute, i want to remove the eleventh object.

Picture3: The debug console shows me that i have 30 objects within my array.

And now, here i was, thinking that this would be an easy task. Since, i've removed and replaced objects at indexes in other NSMutableArrays within my source-code.
Here comes Picture4:

I believe this is telling me that NSMutableArray doesn't respond to removeObjectAtIndex.
Does anyone know what in the heck i'm doing wrong? I'm totally confused.
And no, this is not homework...even if one could believe so. I do.

EDIT:
The error was made during parsing of the objects that went into the dagArray.
Instead of [tempPeriod.dagArray addObject:object] i was doing something completely different.
I was working with a different array and added objects to that array, and when the parser was finished i used tempPeriod.dagArray = [theOtherArray copy] which resulted in this error. theOtherArray was still a NSMutableArray which still confused me. But my best guess is that copy does something with the NSMutableArray rendering it unable to perform those selectors. But i could be completely wrong.
Thanks for shining some thoughts into this.

A: actually it says that NSArray doesn't respond to removeObjectAtIndex. Which would be true.
Could it be that you define it as NSMutableArray, but initialise it in a wrong way?
Where do you init the array, is it possible that the current array is actually a NSArray?
because:
NSMutableArray *anArray = [[NSArray alloc] initWithObject:anObject];

is possible, but would result in runtime errors when you select the wrong selectors.

A: You need to use -mutableCopy if you want a mutable copy of an array. Using -copy, even on a mutable array, will give you an immutable array.


Q: Sqlite Database Error: The FMDatabase  is not open. I'm getting this Error "The FMDatabase  is not open". Even after i open my database first before executing query. Here's the code of instance of database which i'm using to open database.
var instance = ModelManager()

class ModelManager: NSObject {

var database: FMDatabase? = nil
var database2: FMDatabase? = nil
var resultSet: FMResultSet!

class func getInstance(sqllite:String) -> ModelManager {
    if(instance.database == nil){
        instance.database = FMDatabase(path: Util.getPath(sqllite))
    }
    return instance
}
class func getInstance2(sqllite:String) -> ModelManager {
    if(instance.database2 == nil){
        instance.database2 = FMDatabase(path: Util.getPath(sqllite))
    }
    return instance
}

}
and this is the the code where i am getting error.
   func saveImageAudio(audioFile:String?,imageFile:String?,isImage:Bool){

    guard (instance.database?.open())! else {
        return
    }

    let fileName = isImage == true ? imageFile : audioFile
    var paramName = isImage == true ? "imageList" : "audioList"
    let countParam = isImage == true ? "imageCount" : "audioCount"
    let time = Util.DateTime()

    guard increaseLastNo(isImage: isImage) else {
        return
    }

    do {

        let FileArray = getImageAudiolist(isImagelist: isImage)

        var query = ""
        var values:[Any] = []

        if FileArray.count == 0 {
            query = "update RoomSectionDetails set \(paramName) = ?, \(countParam) = 1 ,modified_dtm = ? where  pda_guid = ? and roomName = ? and sectionID = ? and dead = ?"
            values = [fileName!,time,pda_guid,roomName,sectionId,0]
        }else{
            query = "update RoomSectionDetails set \(paramName) = \(paramName) || ?, \(countParam) = \(countParam) + 1, modified_dtm = ? where  pda_guid = ? and roomName = ? and sectionID = ? and dead = ?"
            values = [",\(fileName!)",time,pda_guid,roomName,sectionId,0]
        }

        try instance.database?.executeUpdate(query, values: values)

        paramName = isImage == true ? "lastImageNo" : "lastAudioNo"

        if !isImage {
            self.updateAudioDuration()
        }
    } catch  {
        print("Error while Saving Image Audio in DB")
    }
     instance.database?.close()
   }

Please give the solution for this problem. I wasn't closing database ever time after firing queries. that causes cpu usages more then 200. So now i'm closing database. but i am getting this error. Thanks for Help.

A: I found the Solution for this problem. I am having method inside method which closing the database. Because of that error coming. Thanks for help.


Q: Scrolling divs not scrolling to bottom of content I have 2 scrolling divs (outlined in red) that will not scroll to the their respective bottoms. I can't seem to seem to figure out what to tweak to fix it.
The thick outlined box is a simulated browser window.
http://jsfiddle.net/jsk55rfb/4/

HTML

CSS
.container {
    height: 500px;
    width: 500px;
    border: solid 3px black;
    overflow: hidden;
}

.header {
    height: 25px;
    background-color: #333;
    right: 0;
    left: 0;
}

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 75px;
    margin-top: 35px;
    border: solid 1px grey;
}

.main {
    height: 100%;
    padding-left: 75px;
}

.main-container {
    width: 65%;
    height: 100%;
}

.main-content {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.main-header {
    height: 20px;
    border: 1px solid black;
}

.detail-container {
    float: right;
    width: 35%;
    height: 100%;
    border: solid 1px grey;
}

.top-info {
    padding: 75px 0;
}

.items-container {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.item {
    padding: 100px 0;
}

.blue { background-color: blue; }
.orange { background-color: orange; }
.grey { background-color: grey; }
.purple { background-color: purple; }

.content {
    width: 65%;
    height: 100%;
}

A: You have a fixed height for the container and overflow set to hidden. Since the divs exceed that height, the overflow can't be seen.
Try this:

.container {
    height: 500px;
    width: 500px;
    border: solid 3px black;
    overflow: scroll;
}

.header {
    height: 25px;
    background-color: #333;
    right: 0;
    left: 0;
}

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 75px;
    margin-top: 35px;
    border: solid 1px grey;
}

.main {
    height: 100%;
    padding-left: 75px;
}

.main-container {
    width: 65%;
    height: 100%;
}

.main-content {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.main-header {
    height: 20px;
    border: 1px solid black;
}

.detail-container {
    float: right;
    width: 35%;
    height: 100%;
    border: solid 1px grey;
}

.top-info {
    padding: 75px 0;
}

.items-container {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.item {
    padding: 100px 0;
}

.blue { background-color: blue; }
.orange { background-color: orange; }
.grey { background-color: grey; }
.purple { background-color: purple; }

.content {
    width: 65%;
    height: 100%;
}

A: I could solve this with some javascript. This should addapt to any content size of your other blocks as long as the markup structure doesn't change.
Good luck!
$(function(){
//creating vars based on jquery objects
$itemsContainer = $('.items-container');
$mainContent = $('.main-content');

$container = $('.container');
$header = $('.header');
$mainHeader = $('.main-header');

//calculating heights
var containerH = $container.height();
var headerH = $header.height();
var mainHeaderH = $mainHeader.height();

//assigning new height to main-content class
$mainContent.css("height", (containerH - headerH - mainHeaderH) + "px");

//similar operation for items-container
//creating vars based on jquery objects
$topInfo = $('.top-info');

//calculating heights
var topInforH = $topInfo.outerHeight(); //since in your example top-info has no content only padding, you will need to use the method outerHeight instead of height

//assigning new height to main-content class
$itemsContainer.css("height", (containerH - headerH - topInforH) + "px"); });

By the way, I updated your jsfiddle with my solution, so you can test it.

A: When you use a height of 100% it sets it to the full height regardless of other sibling elements. So they are at 100% of the parent element but then the headers are pushing them down. You will have to use fixed heights on all elements. Or set one to 20% and other to 80% etc.
.main-content { width: 452px; }
.items-container {width: 352px; }


Q: how to remove space between numbers in ASP.Net using RegEx I need to remove the space between the numbers using RegEx means I want to make a formated number from the input like {lhs: \"1000 U.S. dollars\",rhs: \"58 740.6015 Indian rupees\",error: \"\",icc: true} I tried the following expression Regex regex = new Regex("rhs: \\\"(\\d+.\\d*)"); but its give me a error "Input format not correct"  so how can I remove the space between the numbers
P.S The currency name will change each time it called

A: use the following expression
string value = Regex.Replace(response.Split(',')[1], "[^.0-9]", "");


Q: Error using Play Framework debug command I try to launch my play project in debug mode with the play debug command, and it display me an error I can't resolve, despite of Google research... I found many topics about it, but no solution worked for me. Tried to change debug port, run as administrator, disable firewall..
Error message :
ERROR: transport error 202: bind failed: Permission denied
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

NOTE : On my computer, Windows Kernel is using port 9999
Have you got the same error and found a fix for it ?

A: You could try

*

*Deactivating any antivirus or firewall;

*Check ports in use by netstat command

*Changing play.bat debug port (at play's folder root) and save it

Hope it helps


Q: Deploy WAR to TomEE server I built my JavaEE project & got my-service.war file. I want to deploy it to TomEE server.
I have successfully installed TomEE (I can start & stop TomEE server successfully).
I copy my-service.war to
<TomEE_Home>/webapps/

Then, I start TomeEE server.
I open my browser, and put URL http://localhost:8080/my-service
But I get HTTP Status 404 page.
(Then, I checked under /webapps/ that, my-server.war has been unzipped by server, because I see my-server folder there.)
What do I miss for deploying my WAR to TomEE server?
=====server logs =====
I got checked /logs/catalina.2016-08-16.log , I see these errors:
webapps/my-service/WEB-INF/classes/ looking all classes to find CDI beans, maybe think to add a beans.xml if not there or add the jar to exclusions.list
...
org.apache.catalina.core.StandardContext.startInternal Context [/my-service] startup failed due to previous errors
16-Aug-2016 13:51:46.311 INFO [localhost-startStop-1] org.apache.openejb.assembler.classic.Assembler.destroyApplication Undeploying app: /Users/xichen/Dev-tools/apache-tomee-webprofile-7.0.1/webapps/my-service

A: You should check logs/catalina.date.log and logs/localhost..log files.
If you are under unix execute:
grep SEVERE logs/*

to get the errors.
The real error associated with
Context [/my-service] startup failed due to previous errors

Is before in the logs


Q: Saving activity into pdf file I need to save Activity content into .pdf file. Something like a screenshot. I can save individual views of a activity into file using this code:
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(600,300, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
View content = findViewById(R.id.editText1);
content.draw(page.getCanvas());
document.finishPage(page);

But how to save (printscreen) whole activity, not just a views?
Thank you.

A: You can take a screenshot of the current activity using the given code
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
    fos = new FileOutputStream(imagePath);
    bitmap.compress(CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
    Log.e("GREC", e.getMessage(), e);
}

}
and make sure give write permissions of the storage in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


Q: Java Web Start return value - workaround I know that returning a value from a JWSapp to the "calling" page cannot be done.
However, I use this JWSapp to get user ID from its biometric information.
The idea is that when you try to login, a button allows to launch the JWSapp that will deal with the biometric tasks and then return the user's idea.
Still, as I said, from a JWSapp I cannot send back the id to auto-complete the field. I found this post: Returning a value from a java web start application but I really need to keep the JWS (external constraints)...
So there's my question: is there any workaround to get the id back?
Thank you in advance :)


Q: Storyboard vs. iOS Simulator WYSIWYG This is my problem:

        Left side: iOS Simulator      Right side: Storyboard / Interface Builder

Any ideas? Thanks
... UI Elements placed in IB appears shifted up in Simulator
Maybe a better solution than this ... I have two xibs with the exact same look, one is shifted up, the other one works fine.

A: OK, however. My workaround is to change the view hierarchy and set the UIImageView behind the UINavigationItem. Seems to work.


Q: Missing MySQL DLL? I've recreated the Northwind Spring/NHibernate example that comes with Spring.NET, but with MySQL rather than SQLServer. I've almost got it working I think, but I'm getting this when I try to use Hibernate to load something from the database
A first chance exception of type 'System.IO.FileNotFoundException'
occurred in mscorlib.dll NHibernate.Util.ReflectHelper:
ERROR lambda_method - Could not load type
MySql.Data.MySqlClient.MySqlCommand, MySql.Data.
System.IO.FileNotFoundException: Could not load file or assembly
'MySql.Data' or one of its dependencies.
The system cannot find the file specified.
File name: 'MySql.Data'

Every project (DAO, Service, Web) has a reference to the MySQL.Data DLL so I'm a bit unsure what's going on.
Can anyone help me please?

A: Make sure that MySQL.Data.dll actually got copied to the output folder. And that you are using right platform (x32 vs x64 bit) and right version of .NET (2,3,3.5 vs 4). If everyhing seems fine, enable Fusion Logging and take a look at this article:

For FileNotFoundException:  At the bottom of the log will be the paths
  that Fusion tried probing for this assembly. If this was a load by
  path (as in Assembly.LoadFrom()), there will be just one path, and
  your assembly will need to be there to be found. Otherwise, your
  assembly will need to be on one of the probing paths listed or in the
  GAC if it's to be found.
You may also get this exception if an unmanaged dependency or internal
  module of the assembly failed to load. Try running depends.exe on the
  file to verify that unmanaged dependencies can be loaded. Note that if
  you re using ASP.NET, the PATH environment variable it's using may
  differ from the one the command line uses. If all of them could be
  loaded, try ildasm.exe on the file, double-click on "MANIFEST" and
  look for ".file" entries. Each of those files will need to be in the
  same directory as the manifest-containing file.


Q: How can I set a System.env variable in Android Studio? In my build.gradle file in Android Studio using NDK, I have the following code. The app builds if I run it from the terminal with "./gradlew --assembleDebug" since I have set the path for ANDROID_NDK_HOME to /Users/chenige/Desktop/android-ndk-r9, but it will not build from inside Android Studio. From inside Android Studio, System.env.ANDROID_NDK_HOME is "null". Does anybody know why/how I can fix this?
    task buildNative(type: Exec) {
    if (System.env.ANDROID_NDK_HOME != null) {
        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
        commandLine ndkBuild

    } else {
        doLast {
            println '##################'
            println 'Skipping NDK build'
            println 'Reason: ANDROID_NDK_HOME not set.'
            println '##################'
        }
    }
}

}

A: Android Studio doesn't read environment variables, so this approach won't work. Also, using the projectDir scheme in settings.gradle will probably cause problems. Android Studio has a limitation that all of its modules need to be located underneath the project root. If you have libraries that are used in multiple projects and they can't be placed under a single project root, the best advice is to have them publish JARs or AARs to a local Maven repository that individual projects can pick up.
read more Environment variable in settings.gradle not working with Android Studio

A: It works for me with the follwoing steps:

*

*Set your variable in Windows

*Reboot

*reach it in gradle build: "$System.env.MYVARIABLE"


Q: Programmatic Views how to set unique id's? I am creating in my app bunch of programmatic Views. As it appeared to be they all by default have the same id=-1. In order to work with them I need to generate unique id's.
I have tried several approaches - random number generation and based on current time, but anyway there's no 100% guarantee that different Views will have different id's
Just wondering is there any more reliable way to generate unique ones? Probably there's special method/class?

A: Just want to add to Kaj's answer, from API level 17, you can call
View.generateViewId()
then use the View.setId(int) method.
In case you need it for targets lower than level 17, here is its internal implementation in View.java you can use directly in your project:
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

/**
 * Generate a value suitable for use in {@link #setId(int)}.
 * This value will not collide with ID values generated at build time by aapt for R.id.
 *
 * @return a generated ID value
 */
public static int generateViewId() {
    for (;;) {
        final int result = sNextGeneratedId.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
        if (sNextGeneratedId.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files. (Most likely 0x7f****** from the R.java in my projects.)
From the code, somehow Android doesn't want you to use 0 as a view's id, and it needs to be flipped before 0x01000000 to avoid the conflits with static resource IDs.

A: Just an addition to the answer of @phantomlimb,
while View.generateViewId() require API Level >= 17,
this tool is compatibe with all API.
according to current API Level,
it decide weather using system API or not.
so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the
same time and don't worry about getting same id
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

/**
 * {@link View#generateViewId()}要求API Level >= 17,而本工具类可兼容所有API Level
 *

 * 自动判断当前API Level,并优先调用{@link View#generateViewId()},即使本工具类与{@link View#generateViewId()}
 * 混用,也能保证生成的Id唯一
 *

 * =============
 *

 * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
 *

 * according to current API Level, it decide weather using system API or not.

 * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
 * same time and don't worry about getting same id
 *
 * @author fantouchx@gmail.com
 */
public class ViewIdGenerator {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @SuppressLint("NewApi")
    public static int generateViewId() {

        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }

    }
}

A: Regarding the fallback solution for API<17, I see that suggested solutions start generating IDs starting from 0 or 1. The View class has another instance of generator, and also starts counting from number one, which will result in both your and View's generator generating the same IDs, and you will end up having different Views with same IDs in your View hierarchy. Unfortunately there is no a good solution for this but it's a hack that should be well documented:
public class AndroidUtils {

/**
 *  Unique view id generator, like the one used in {@link View} class for view id generation.
 *  Since we can't access the generator within the {@link View} class before API 17, we create
 *  the same generator here. This creates a problem of two generator instances not knowing about
 *  each other, and we need to take care that one does not generate the id already generated by other one.
 *
 *  We know that all integers higher than 16 777 215 are reserved for aapt-generated identifiers
 *  (source: {@link View#generateViewId()}, so we make sure to never generate a value that big.
 *  We also know that generator within the {@link View} class starts at 1.
 *  We set our generator to start counting at 15 000 000. This gives us enough space
 *  (15 000 000 - 16 777 215), while making sure that generated IDs are unique, unless View generates
 *  more than 15M IDs, which should never happen.
 */
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);

/**
 * Generate a value suitable for use in {@link View#setId(int)}.
 * This value will not collide with ID values generated at build time by aapt for R.id.
 *
 * @return a generated ID value
 */
public static int generateViewId() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return generateUniqueViewId();
    } else {
        return View.generateViewId();
    }
}

private static int generateUniqueViewId() {
    while (true) {
        final int result = viewIdGenerator.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
        if (viewIdGenerator.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

}

A: Since support library 27.1.0 there's generateViewId() in ViewCompat
ViewCompat.generateViewId()

A: Create a singleton class, that has an atomic Integer. Bump the integer, and return the value when you need a view id.
The id will be unique during the execution of your process, but wil reset when your process is restarted.
public class ViewId {

    private static ViewId INSTANCE = new ViewId();

    private AtomicInteger seq;

    private ViewId() {
        seq = new AtomicInteger(0);
    }

    public int getUniqueId() {
        return seq.incrementAndGet();
    }

    public static ViewId getInstance() {
        return INSTANCE;
    }
}

Note that the id might not be unique, if there already are views that have ids in the view 'graph'. You could try to start with a number that is Integer.MAX_VALUE, and decrease it instead of going from 1 -> MAX_VALUE


Q: Php, Symfony 1.4,doctrine I want to convert this mysql syntax into a doctrine 1.2 syntax. I want to show dates with zero values and print some errors on it. Also, is PHP foreach loop relevant for this for the templates/views?
SELECT calendar.datefield AS DATE,
       IFNULL(SUM(orders.quantity),0) AS total_sales
FROM orders RIGHT JOIN calendar ON (DATE(orders.order_date) = calendar.datefield)
WHERE (calendar.datefield BETWEEN (SELECT MIN(DATE(order_date)) FROM orders) AND (SELECT MAX(DATE(order_date)) FROM orders))
GROUP BY DATE..


Q: Getting InvalidOperationException: Incorrect Content-Type: text/plain exception when processing file through Web API Core I am having an API.Net Core Web API app that has a POST method that accepts and processes a PDF file.
However, when I try to test in POSTMAN (Selecting POST, selecting Binary, choosing a file) I get a following error

InvalidOperationException: Incorrect Content-Type: text/plain

At the following line

var file = Request.Form.Files[0];

Please let me know if there is anything I need to fix
Thank you in advance
Here is the entire method
[HttpPost]
[Route("SubmitForm")]
public async Task<IActionResult> SubmitForm()
{

    var file = Request.Form.Files[0];
    HttpClient client = GetClient();
    try
    {

        byte[] docAsBytes;
        using (var ms = new MemoryStream())
        {
            file.CopyTo(ms);
            docAsBytes = ms.ToArray();
            string s = Convert.ToBase64String(docAsBytes);
            // act on the Base64 data
        }

        PdfReader pdfReader = new PdfReader(docAsBytes);
        MemoryStream m = new MemoryStream();
        PdfStamper outStamper = new PdfStamper(pdfReader, m);
        string formName = outStamper.AcroFields.GetField("FormSeqNo");

        string endpointUrl = "https://myproject.sharepoint.com/sites/project" + String.Format(
           "/_api/web/GetFolderByServerRelativeUrl('{0}')/Files/Add(url='{1}', overwrite=true)",
           this.Config["TemplateLibrary"].Replace(" ", "%20"),
           formName + ".pdf");

        ByteArrayContent imageBytes = new ByteArrayContent(docAsBytes);
        var result = await client.PostAsync(endpointUrl, imageBytes);

        //return result.Content.ToString();
    }
    catch (Exception ex)
    {
        //return ex.ToString();
    }

    return Ok();
}


Q: Creating a running total grouped by a statement evaluation Using this article I have implemented a query that determines packing intervals for user events:
http://www.itprotoday.com/microsoft-sql-server/new-solution-packing-intervals-problem
I've ended up with following output:

However, the bit I can't fathom out is how to group the packed intervals by userId for each date.  Basically, I need a group column on the end which increments for each row when isStart is 1, but is output the same as the previous row's when isStart is null.
Thus it should go:
Row 1: 1
Row 2: 2
Row 3: 2
Row 4: 3
Row 5: 4
Row 6: 5
Row 7: 6
Row 8: 7
Row 9: 8
Row 10: 9
Row 11: 9
Row 12: 9
Row 13: 10

... etc
This then allows me to retrieve the min start and max end for each group.  I'm sure this is really obvious but I can't seem to spot it!

A: Just use a cumulative sum:
select t.*,
       sum(isStart) over (order by start) as grp
from t;


Q: iOS - UILocalNotification - can schedule only up to 64 slots at a given time Overview

*

*I have an iOS app which sends local notifications at specific dates.

*I just learned that I can only schedule 64 notifications at a given time.

*There are cases when I can't schedule notifications as the 64 slots are filled.

*So I store them in the database and when the user responds to a notification I check if there are any available slots and schedule the remaining notifications.

Problem

*

*When the user doesn't  respond to a notification my code is not executed so I am not able to schedule the remaining notifications.

Question

*

*Is there a solution for this problem ?

*can I execute a piece of code (house keeping) at certain times ?

*is there any work around for this ?

A: You may not want to signal to the user there is a problem, but rather just do it in the background. If a user has 64 notifications for one app and hasn't opened the app, then they probably aren't using the app. Once a notification has fired it isn't in the array anymore. So you will have room every time a notification is fired off. They do however remain in notification centre, which you have to clear out yourself.
Its usually better to not present possible problems to the user, but rather handle them in a way that makes sense internally if that is an option. Look up the delegate methods for the appDelegate and you will most likely find ways you can handle what you are trying to do.
Thought I would make a post in case you wanted to accept the answer.
Best of luck.


Q: Sampling and removing random elements from a list I have written a method which randomly samples a part of a list. The code is as follows:
private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    return copy.subList(0, num);
}

The method takes as input the original list, the random number generator and the number of items to sample.
Now I would like to remove the selected elements from the original list (called images). How can this be done?

A: Using removeAll in the old list with the argument being your sub sample.
private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    List<String> sample = copy.subList(0, num);
    images.removeAll(sample);
    return sample;
}


Q: to compare two text files and output the difference in other file .txt I want to compare two text files and output the difference in other result.txt.
I use this command in command prompt:
findstr /vixg:Z:\misc\test1.txt Z:\misc\misc\test2.txt > Z:\misc\misc\result.txt

But I have the file result.txt is the same of test2.txt.


Q: db connection deadlock We have a web application that has been running well for several years. The web application was using mysql, spring-1.2.6, and ibatis.
After replacing spring-1.2.6 with spring-3.2.0, we started to notice a problem that multiple concurrent requests to a particular page always hang for some reason.
jConsole shows the following for each concurrent thread:
   java.lang.Thread.State: WAITING on
   org.apache.commons.pool.impl.GenericObjectPool$Latch@b6b09e
   at java.lang.Object.wait(Native Method)
   at java.lang.Object.wait(Object.java:485)
   at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1104)

After investigation, we found that this problem has something to do with a resultMap that looks like the following. With spring-1.2.6, only one connection was needed for each thread regardless of the number of rows in the result set. However, with spring-3.2.0, N+1 connections (depending on the number of rows returned) are needed for each thread. Hence the deadlock. (We are using the default value (8) of maxActive property in our configuration.)
How can I fix it so that connections are reused in this case? Thanks.
<resultMap id="resultBlog" type="Blog">
    <id property="id" column="idBlog" />
    <result property="name" column="blogname" />
    <result property="url" column="blogurl" />
    <result property="author" column="idBlog" select="selectAuthor" />
</resultMap>


Q: How to type cast a literal in C I have a small sample function:
#define VALUE 0

int test(unsigned char x) {
  if (x>=VALUE)
    return 0;
  else
    return 1;
}

My compiler warns me that the comparison (x>=VALUE) is true in all cases, which is right, because x is an unsigned character and VALUE is defined with the value 0. So I changed my code to:
if ( ((signed int) x ) >= ((signed int) VALUE ))

But the warning comes again. I tested it with three GCC versions (all versions > 4.0, sometimes you have to enable -Wextra).
In the changed case, I have this explicit cast and it should be an signed int comparison. Why is it claiming, that the comparison is always true?

A: x is an unsigned char, meaning it is between 0 and 256. Since an int is bigger than a char, casting unsigned char to signed int still retains the chars original value. Since this value is always >= 0, your if is always true.

A: All the values of an unsigned char can fir perfectly in your int, so even with the cast you will never get a negative value. The cast you need is to signed char - however, in that case you should declare x as signed in the function signature. There is no point lying to the clients that you need an unsigned value while in fact you need a signed one.

A: Even with the cast, the comparison is still true in all cases of defined behavior. The compiler still determines that (signed int)0 has the value 0, and still determines that (signed int)x) is non-negative if your program has defined behavior (casting from unsigned to signed is undefined if the value is out of range for the signed type).
So the compiler continues warning because it continues to eliminate the else case altogether.
Edit: To silence the warning, write your code as
#define VALUE 0

int test(unsigned char x) {
#if VALUE==0
  return 1;
#else
  return x>=VALUE;
#endif
}

A: The #define of VALUE to 0 means that your function is reduced to this:
int test(unsigned char x) {
  if (x>=0)
    return 0;
  else
    return 1;
}

Since x is always passed in as an unsigned char, then it will always have a value between 0 and 255 inclusive, regardless of whether you cast x or 0 to a signed int in the if statement.  The compiler therefore warns you that x will always be greater than or equal to 0, and that the else clause can never be reached.


Q: How to remove the word "Data" at the top of Excel Pivot Table generated by C# with Interop.Excel? I have the following example raw data table:

And hope to make the following Pivot Table using C# and the Microsoft.Office.Interop.Excel library:

I have written the following code to generate both the original table and the pivot table:
            string fileTest = "test.xlsx";

            Excel.Application app;
            Excel.Worksheet sheet;
            Excel.Workbook book;

            app = new Excel.Application();
            book = app.Workbooks.Add();
            sheet = (Excel.Worksheet)book.Worksheets.get_Item(1);

            sheet.Cells[1, 1] = "Name";
            sheet.Cells[1, 2] = "Salary";
            sheet.Cells[1, 3] = "Hours";
            sheet.Cells[1, 4] = "Department";

            sheet.Cells[2, 1] = "Bill";
            sheet.Cells[2, 2] = 140000;
            sheet.Cells[2, 3] = 40;
            sheet.Cells[2, 4] = "IT";

            sheet.Cells[3, 1] = "Ann";
            sheet.Cells[3, 2] = 310000;
            sheet.Cells[3, 3] = 60;
            sheet.Cells[3, 4] = "Payroll";

            sheet.Cells[4, 1] = "Bob";
            sheet.Cells[4, 2] = 200000;
            sheet.Cells[4, 3] = 50;
            sheet.Cells[4, 4] = "IT";

            sheet.Cells[5, 1] = "Sam";
            sheet.Cells[5, 2] = 50000;
            sheet.Cells[5, 3] = 20;
            sheet.Cells[5, 4] = "Payroll";

            Excel.Range range = sheet.Range["A1", "D5"];

            Excel.Worksheet pivotSheet = (Excel.Worksheet)book.Worksheets.Add();

            pivotSheet.Name = "Pivot Table";

            Excel.Range range2 = pivotSheet.Cells[1, 1];

            Excel.PivotCache pivotCache = (Excel.PivotCache)book.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, range);
            Excel.PivotTable pivotTable = (Excel.PivotTable)pivotSheet.PivotTables().Add(PivotCache: pivotCache, TableDestination: range2, TableName: "Summary");

            Excel.PivotField pivotField = (Excel.PivotField)pivotTable.PivotFields("Salary");
            pivotField.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
            pivotField.Function = Excel.XlConsolidationFunction.xlSum;

            Excel.PivotField pivotField3 = (Excel.PivotField)pivotTable.PivotFields("Hours");
            pivotField3.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
            pivotField3.Function = Excel.XlConsolidationFunction.xlSum;

            Excel.PivotField pivotField2 = (Excel.PivotField)pivotTable.PivotFields("Department");
            pivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;

            Excel.PivotField dataField = pivotTable.DataPivotField;
            dataField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;

            pivotTable.TableStyle2 = "PivotStyleLight16";

            book.SaveAs(fileTest);
            book.Close();
            app.Quit();

However, my Pivot Table has an extra row in the Pivot Table Header with the word "Data" in it:

Is there a way I can remove this extra header? Thanks for any advice.


Q: Formik component changing an uncontrolled input of type text to be controlled I am using Formik with an array, where the items are being passed from a parent and retrieved like this:
updateState (){
    this.state.choices = this.props.choices
    this.state.questionId = this.props.questionId
  }
  render() {
    this.updateState()
    var choices = this.state.choices
    console.log(choices)
    return ( ...

I am originally initializing the values as empty or 0:
  constructor(props){
    super(props);
    this.state = {
      choices : [],
      questionId: 0
    };
  }

While this seems like it should work, I am getting the error that a component is changing an uncontrolled input of type text to be controlled.  understand this is due to my use of this.state but I'm unsure how to actually fix this.
What I have done so far, since I am using Formik, is change my export to look like this:
  export default withFormik({
  mapPropsToValues: (props) => ({
    choices: [{
    id: '',
    value: '',
    weight: '',
    impact: ''}]
  }),
})(Choices)

It's unclear if I should be mapping props at all, or if I should be using something more like:
export default withFormik({
  mapPropsToValues: (props) => ({

    id: '',
    value: '',
    weight: '',
    impact: ''
  }),
})(Choices)

All I know is that I am unable to click to push a new object onto the array that I am working with, so the functionality is basically frozen until I can figure out the state of the un/controlled input element.
Any idea where I am going wrong?

A: Fixing the HTML and the {choices[index].id} bits cleared this error.
E.g.:

                        {choices[index].id}
                        <Field name={choices[index].id} placeholder={choices[index].value} type="text"/>
                        <ErrorMessage name={choices[index].id} component="div" className="field-error" />


Q: can't see properties of viewcontoller I want to change the value of a label in my default view controller from a different class.

*

*So I start a simple 'Single View Application' iOS project (Xcode5)

*This automatically generates a ViewController for me (which I
understand is the root view controller)

*I now add a label in my View and connect it to the ViewController (via IBOutlet mechanism)

*I call this outlet 'gameStateLabel', so it looks like this in the ViewController.h file
@property (weak, nonatomic) IBOutlet UILabel *gameStateLabel;

Next, I have a completely separate class which has the logic for my code, and based on a condition in the logic I want to change the UIlabel.
So I try to do this from my other class:

*

*Get an instance of the root view controller like this:
UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

I think I now have an instance of the rootviewcontroller in uvc and should be able to reach in and change gameStateLabel.
BUT: I CANNOT do this uvc.gameStateLabel simply does not show up as a property even though it is clearly declared as a property and I've added the @synthesize for it also.
Any help will be greatly appreciated - I've been going nuts over this.
(For ref. I'm used to doing something similar on the Mac side where I'd declare a label as a property of the AppDelegate, get the instance of the Appdelegate and simply refer to the label property and change its text]
Here's the ViewController. Note that gameStateLable is a property
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *gameStateLabel;

@end

@implementation ViewController
@synthesize gameStateLabel;
- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

And here is my class cls1 (which inherits from NSObject)
#import "cls1.h"
#import "ViewController.h"

@implementation cls1

-(void) dummy{

UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

// uvc does NOT show gameStateLabel in intellisense, i.e. uvc.gameStateLabel does NOT work

}

A: Add #import "mainRootVC.h" in you CustomClass.m file
And create object of mainRootVC such like,
mainRootVC *obj = [[mainRootVC alloc] init];
// Now you can access your label by
obj.gameStateLabel...

A: Do like this...
YourViewController *rootController =[(YourViewController*)[(YourAppDelegate*)
        [[UIApplication sharedApplication]delegate] window] rootViewController];

A: Try the following too:
ViewController *controller = (ViewController*)self.window.rootViewController;

It will return the initial view controller of the main storyboard.

A: For sending information from a viewController to other viewController you have:

*

*Delegates:Definiton and examples

*NSNotificationCenter:  Apple Documentation
NSString *label = @"label text";
[[NSNotificationCenter defaultCenter] postNotificationName:NAVIGATETO object:label userInfo:nil];
You can found tons of examples about those two. I recommend you use one of those.
Hope this helps a bit.

A: OK. I found two issues.

*

*I had copied the code over from my Mac project and modified it. Something seems to have gone wrong.

I retyped the entire function and it solved most of the problem

*

*uvc should be of the type ViewController* - not UIViewController* as I was doing

Thanks everyone for your replies - much appreciated.


Q: C# Newbie: Change Entity Framework DataBound DataGrid created with WPF drag-and-drop I'm new to C# and I created a WPF GUI using Visual Studio 2010 Ultimate (Windows 7 x64).
I used drag-and-drop technology to databind a datagrid to an SQL Server 2008 database table using Entity Framework technology.
This all works very well, despite my lack of C# skills.
I was able to hide columns using statements like:
dataGridInputEmails.Columns[0].Visibility = Visibility.Hidden;

And I cleared the datagrid using:
dataGridInputEmails.Columns.Clear();

Now I want to populate the datagrid with a string that I created by reading in a text file and using:
string[] parts = slurp.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);

But, I cannot figure out how to populate the datagrid.
TIA

A: Try this:
dataGridInputEmails.ItemsSource = parts;

You shouldn't have to do dataGridInputEmails.Columns.Clear(); first.


Q: Pandas maximum difference of values with day-to-day intervals Continuation of previous previous question
df

                    Timestamp  Spot DK1  Spot DK2  Ubalance DK1  Ubalance DK2
0   2020-01-01T00:00:00+01:00     33.42     33.42         34.00         34.00
1   2020-01-01T01:00:00+01:00     31.77     31.77         34.00         34.00
2   2020-01-01T02:00:00+01:00     31.57     31.57         34.00         34.00
3   2020-01-01T03:00:00+01:00     31.28     31.28         34.00         34.00
4   2020-01-01T04:00:00+01:00     30.85     30.85         26.00         26.00
5   2020-01-01T05:00:00+01:00     30.14     30.14         25.00         25.00
6   2020-01-01T06:00:00+01:00     30.17     30.17         24.00         24.00
7   2020-01-01T07:00:00+01:00     30.00     30.00         24.00         24.00
8   2020-01-01T08:00:00+01:00     30.63     30.63         24.00         24.00
9   2020-01-01T09:00:00+01:00     30.59     30.59         25.00         25.00
10  2020-01-01T10:00:00+01:00     30.27     30.27         25.00         25.00
11  2020-01-01T11:00:00+01:00     30.34     30.34         25.00         25.00
12  2020-01-01T12:00:00+01:00     30.59     30.59         30.59         30.59
13  2020-01-01T13:00:00+01:00     30.04     30.04         30.04         30.04
14  2020-01-01T14:00:00+01:00     30.60     30.60         30.60         30.60
15  2020-01-01T15:00:00+01:00     31.09     31.09         31.09         31.09
16  2020-01-01T16:00:00+01:00     31.53     31.53         31.53         31.53
17  2020-01-01T17:00:00+01:00     31.78     31.78         33.50         33.50
18  2020-01-01T18:00:00+01:00     31.64     31.64         33.50         33.50
19  2020-01-01T19:00:00+01:00     31.44     31.44         31.44         31.44
20  2020-01-01T20:00:00+01:00     31.35     31.35         31.35         31.35
21  2020-01-01T21:00:00+01:00     31.07     31.07         31.07         31.07
22  2020-01-01T22:00:00+01:00     30.96     30.96         25.00         25.00
23  2020-01-01T23:00:00+01:00     30.61     30.61         21.00         21.00
24  2020-01-02T00:00:00+01:00     30.78     30.78         20.00         20.00
25  2020-01-02T01:00:00+01:00     30.64     30.64         20.00         20.00
26  2020-01-02T02:00:00+01:00     30.43     30.43         20.00         20.00
27  2020-01-02T03:00:00+01:00     28.79     28.79         23.00         23.00
28  2020-01-02T04:00:00+01:00     28.42     28.42         22.73         22.73
29  2020-01-02T05:00:00+01:00     28.75     28.75         23.00         23.00
30  2020-01-02T06:00:00+01:00     33.38     34.16         22.50         22.50
31  2020-01-02T07:00:00+01:00     31.79     42.07         22.28         22.28
32  2020-01-02T08:00:00+01:00     31.83     44.89         22.50         22.50
33  2020-01-02T09:00:00+01:00     31.74     45.26         23.00         23.00
34  2020-01-02T10:00:00+01:00     31.63     45.57         24.00         24.00
35  2020-01-02T11:00:00+01:00     31.32     45.09         25.00         25.00
36  2020-01-02T12:00:00+01:00     31.07     45.16         25.00         25.00
37  2020-01-02T13:00:00+01:00     31.06     44.90         25.00         25.00
38  2020-01-02T14:00:00+01:00     31.07     44.06         26.00         26.00
39  2020-01-02T15:00:00+01:00     31.26     44.84         26.00         26.00
40  2020-01-02T16:00:00+01:00     31.41     44.40         27.50         27.50
41  2020-01-02T17:00:00+01:00     31.40     46.05         26.00         46.05
42  2020-01-02T18:00:00+01:00     31.10     46.72         26.00         26.00
43  2020-01-02T19:00:00+01:00     30.75     45.26         25.32         25.32
44  2020-01-02T20:00:00+01:00     30.47     39.32         20.25         20.25
45  2020-01-02T21:00:00+01:00     30.10     30.10         16.50         16.50
46  2020-01-02T22:00:00+01:00     29.71     29.71         16.50         16.50
47  2020-01-02T23:00:00+01:00     24.99     24.99         15.00         15.00
48  2020-01-03T00:00:00+01:00     18.93     18.93         15.00         15.00
49  2020-01-03T01:00:00+01:00      9.98      9.98          9.98          9.98

I want to generate a separate series of values in which the maximum difference of each day's values are in. Preferably able to choose of which columns to include.
Therefore, the first value in the series should be 12.5, since the largest and lowest values of the first day are 33.5 and 21.00, respectively.
Expected outcome:
       Day          Max diff
0   2020-01-01       12.50
1   2020-01-02       31.72

So far, I've tried this - but this gives me a rolling, 24-hour interval, crossing days, which is what I try to avoid:
cols = ['Spot DK1','Spot DK2','Ubalance DK1','Ubalance DK2']
N = 24

battery['dif'] = (battery[cols].stack(dropna=False)
                     .rolling(len(cols) * N)
                     .agg(lambda x: x.max() - x.min())
                     .groupby(level=0)
                     .max())

A: Idea is aggregate minimal and maximal values per days, so possible get max and min by max and min levels in df1 and last subtract to new df2:
df['Timestamp'] = pd.to_datetime(df['Timestamp'])

cols = ['Spot DK1','Spot DK2','Ubalance DK1','Ubalance DK2']

df1 = (df.set_index('Timestamp')[cols]
         .groupby(pd.Grouper(freq='D', level='Timestamp'))
         .agg(['min','max']))

s1 = df1.xs('max', level=1, axis=1).max(axis=1)
s2 = df1.xs('min', level=1, axis=1).min(axis=1)

df2 = s1.sub(s2).rename_axis('Day').reset_index(name='Max diff')
print (df2)
                        Day  Max diff
0 2020-01-01 00:00:00+01:00     13.00
1 2020-01-02 00:00:00+01:00     31.72
2 2020-01-03 00:00:00+01:00      8.95

Details:
print (df1)
                          Spot DK1        Spot DK2        Ubalance DK1        \
                               min    max      min    max          min   max
Timestamp
2020-01-01 00:00:00+01:00    30.00  33.42    30.00  33.42        21.00  34.0
2020-01-02 00:00:00+01:00    24.99  33.38    24.99  46.72        15.00  27.5
2020-01-03 00:00:00+01:00     9.98  18.93     9.98  18.93         9.98  15.0

                          Ubalance DK2
                                   min    max
Timestamp
2020-01-01 00:00:00+01:00        21.00  34.00
2020-01-02 00:00:00+01:00        15.00  46.05
2020-01-03 00:00:00+01:00         9.98  15.00


Q: Generic JQuery Function? I'm using Jeditable to edit dozens of fields such as first_name, last_name, birthday, etc.
My problem is that I'm drowning in detail: I keep having to create a new selector such as $('#edit_first_name').editable or $('#edit_birthday').editable to making the field editable as well as create a bunch of SQL commands specific to each field to insert them once they're edited.
My question is: Is there a way I can create something generic or OO in JQuery so that I don't don't have to endlessly create code that essentially does the same thing?
My guess is I can create some "generic" function that will create $('#edit_someField').editable on the fly by feeding some JSON array, which was created by doing a SELECT on all field names I'm interested in. I imagine that's exactly what JQuery plugins do.
Any direction on how I can accomplish this would be much appreciated.
EDIT
One solution I have come up with is to put the table, column name and id in the id value of whatever I want to edit.
For example, if I want to edit the first_name of id=6 on table Person, then in the id I will put myFirstName. When I send the id to my save.php file, I use a preg_split to insert my data into the table.

A: Mark all your editable input fields with the class "editable". (Change to suit.)
$('.editable').each(function() {
  $(this).editable('mysaveurl.php');
});

That's all you need for the basic functionality. Obvious improvements can be made, depending on what else you need. For example, if you are using tooltips, stick them in the title attribute in your HTML, and use them when you call editable().
Your actual PHP/Ruby/whatever code on the server is just going to look at the id parameter coming in, and use that to save to the appropriate field in the database.

A: Just use a class to make them all editable, and using their id (or a attribute that you have attached to the tag) you can specify the field you are updating.
Then just pass the field and the value to your DB.
i don't know the plugin you are using
but, assuming it has some sort of event handling in it...
something like this maybe?
$(".editable").editable({
      complete : function() {
            var _what = $(this).attr("id");
            var _with = $(this).val();
            $.post("yourPostPage.php",{what:_what, where:_where});
       }
});

Without knowing more about your environment I wouldn't be able to help further.

A: The jQuery way of assigning some common code to a bunch of objects is to either give all the objects the same class so you can just do this:
$(".myEditableFields").editable("enable");

This will call the editable add-on method for all objects in your page with class="myEditableFields".
If you just have a list of IDs, you can just put them all in the single selector like this and they will each get called for the editable jQuery method:
$("#edit_first_name, #edit_birthday, #edit_last_name, #edit_address").editable("enable");

Sometimes, the easy way it to create a select that just identifies all editable fields within a parent div:
$("#editForm input").editable("enable");

This would automatically get all input tags inside the container div with id=editForm.
You can of course, collect common code into your own function in a traditional procedural programming pattern and just call that when needed like this:
function initEditables(sel) {
    $(sel).editable("enable");
    // any other initialization code you want here or event handlers you want to assign
}

And, then just call it like this as needed:
initEditables("#edit_first_name");

To help further, we would need to know more about what you're trying to do in your code and what your HTML looks like.


Q: jQuery - Exclude an li from this function? I have a ul list of 8 li's on the last li it has the id #search - I don't want the dropdown applid to this, how can I exclude it? here's my code..
$(document).ready(function () {
  $('#navigation li').hover(function () {
    // Show the sub menu
    $('ul', this).stop(true,true).slideDown(300);
  },
  function () {
  //hide its submenu
   $('ul', this).stop(true,true).slideUp(200);
  });
});

Thanks

A: Use jQuery's .not()
$('#navigation li').not("#search").hover(function () {
   // Show the sub menu
   $('ul', this).stop(true,true).slideDown(300);
},
function () {
  //hide its submenu
  $('ul', this).stop(true,true).slideUp(200);
});


Q: Shift a column in R Suppose that I have a dataframe like the following:
library(tidyverse)

df <- tibble(x = c(1,2,3), y = c(4,5,6))

# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1     1     4
2     2     5
3     3     6

And I would like to shift a column, adding a column like:
# A tibble: 3 x 3
      x     y shifted_x
  <dbl> <dbl>     <dbl>
1     1     4        NA
2     2     5         1
3     3     6         2

Basically, I want to work with timeseries, so I would like to get previous values and use them as feature. In python I know I can do:
for i in range(1,11):
    df[f'feature_{i}']=df['sepal_length'].shift(i)

Where df is a pandas Dataframe.
Any equivalent code for doing this in R?

A: An equivalent in R tidyverse is dplyr::lag.  Create the column in mutate and update the object by assigning (<-) back to the same object 'df'
library(dplyr)
df <- df %>%
    mutate(shifted_x = lag(x))

or if we need to use the shift, there is shift in data.table
library(data.table)
setDT(df)[, shifted_x := shift(x)]

Also, if we need to create more than one column, shift can take a vector of values in n
setDT(df)[, paste0('shifted', 1:3) := shift(x, n = 1:3)]

A: We can also use the flag function from the collapse package.
library(collapse)

df %>%
  ftransform(shifted_x = flag(x))
# # A tibble: 3 x 3
#       x     y shifted_x
# * <dbl> <dbl>     <dbl>
# 1     1     4        NA
# 2     2     5         1
# 3     3     6         2


Q: BCP error "Unable to open BCP host data-file" I've just create a new table in my sqlserver name exporttable
 now I'm trying to push out using cmd bcp but om getting this following error:

SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13
  for SQL Server]Unable to open BCP host data-file

Here is my path:
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T

anyone can help ?
After trying Shnugos suggestion to add a filename I got this error:

SQLState = S0002, NativeError = 208 Error = [Microsoft][ODBC Driver 13
  for SQL Server][SQL Server]Invalid object name
  'Testing.bdo.ExportTable'. SQLState = 37000, NativeError = 11529 Error
  = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The metadata could not be determined because every code path results in an error;
  see previous errors for some of these. –

A: From the error I take, that the data file cannot be opened:
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop\MyFile.txt" -C -T

I think, you have to add a filename behind the \Desktop. Desktop is an existing directory and cannot be opened as file ...
And - btw - it might be necessary to add -S Servername...
UPDATE
Found this here

Whenever I get this message, it's because of one of three things:
1) The path/filename is incorrect (check your typing / spelling)
2) The file does not exist. (make sure the file is where you expect it
  to be)
3) The file is already open by some other app. (close the other app to
  release the file)
For 1) and 2) - remember that paths are relative to where bcp is
  executing. Make sure that bcp.exe can access the file/path from it's
  context.
/Kenneth

A: If you are running BCP through xp_cmdshell, run the following-->
xp_cmdshell 'whoami';
GO
--Make sure whatever user value you get back has full access to the file in question

A: Run: EXEC master..xp_cmdshell 'DIR C:\Users\Serge\Desktop', this will show if you have access to the path.
Remember if you are accessing SQL remotely or over a network, the output ie. "C:\Users\Serge\Desktop" will be the C drive on the SQL Server, not your remote PC you are working on.

A: I know this is old, but you also appear to have the schema spelled wrong.
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T
s/b
C:\Users\Serge>BCP Testing.dbo.Exporttable out "C:\Users\Serge\Desktop" -C -T


Q: Logtalk : Load a file with camelcase naming on Windows With logtalk 3.1.2, under OS X and Linux, no problem to load a file with a camelcase name, but an exception is thrown on Windows (ERROR : file does not exist).
logtalk_load(mypath(myFileNameInCameCase))

What's wrong ?

A: Some backend Prolog compilers, such as SWI-Prolog when running on Windows, down-case file names when expanding file paths into absolute file paths. This caused a failure in the Logtalk compiler when going from the file argument in the compilation and loading predicates to an absolute file path and its components (directory, name, and extension). A workaround have been found and committed to the current git version. Thanks for the bug report.


Q: Appending javascript value to gridview hyperlink. Any ideas why my code doesn't work? We have a javascript that takes start date and end date, calculates the difference between them and stores the value in a variable called hourDiff.
Here is relevant part of the js.
To avoid a scope issue, a gobal variable called hourDiff is defined at top of the javascript outside any function"
var hourDiff = 0;

//Calulate the time difference and store the value in hourDiff
hourDiff = endDate - startDate;

The idea is to eventually appendd hourDiff to the gridview hyperlink control below and pass the name-value pairs as querystring to another page called Reseve.aspx
<asp:HyperLink ID="siteId" class="js_siteid" style="color:#111" runat="server" navigateurl='<%# String.Format("Reserve.aspx?id={0}&groupsize={1}&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}&keydeptAmt={6}", Eval("siteId"), Eval("capacity"),Eval("RentalFeeAmount"),Eval("ExtraHourAmount"),Eval("DepositAmount"),Eval("CancellationAmount"),Eval("KeyDepositAmount")) %>' Text='Select' />

Since the hyperlink is not exposed to the javascript until after search button is clicked, I have another javascript below that is used to apend hourdiff to the hyperlink and passed to another page.
This javascript is placed at the bottom of the html page:

Each time I compile my code and clic the Select link, hourDiff always displays the value of 0 rather than the difference between start date and end date.
Any ideas what I am doing wrong?
Protected Sub ValidateDuration(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
  Dim validator As Control = DirectCast(sender, Control)
  Dim row As Control = validator.NamingContainer

  Dim startHour As Integer = Integer.Parse(DirectCast(row.FindControl("startHour"), DropDownList).SelectedValue)
  Dim startMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("startMinutes"), DropDownList).SelectedValue)
  Dim startAmPm As String = DirectCast(row.FindControl("startAmPm"), DropDownList).SelectedValue

  Select Case startAmPm
    Case "AM"
        If startHour = 12 Then
            startHour = 0
        End If

    Case "PM"
        If startHour <> 12 Then
            startHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim endHour As Integer = Integer.Parse(DirectCast(row.FindControl("endHour"), DropDownList).SelectedValue)
  Dim endMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("endMinutes"), DropDownList).SelectedValue)
  Dim endAmPm As String = DirectCast(row.FindControl("endAmPm"), DropDownList).SelectedValue

  Select Case endAmPm
    Case "AM"
        If endHour = 12 Then
            endHour = 0
        End If

    Case "PM"
        If endHour <> 12 Then
            endHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim hoursDiff As Integer = endHour - startHour
  If endMinutes < startMinutes Then
    hoursDiff -= 1
  End If

  args.IsValid = hoursDiff >= 2

End Sub

A: Update 2015-02-27 ~13:40 EDT: Appending hiddenfield to hyperlink serverside
I'm using GridView1 as I do not know the name of your gridview.
In the GridView1 RowDatabound Event (note the addition of "&hourDiff={7}" to the end of the format string and the addiition of the hiddenfield value in the parameter list):
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = String.Format("Reserve.aspx?id={0}&groupsize={1}" & _
          "&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}" & _
          "&keydeptAmt={6}&hourDiff={7}",
          DataBinder.Eval("siteId"),
          DataBinder.Eval("capacity"),
          DataBinder.Eval("RentalFeeAmount"),
          DataBinder.Eval("ExtraHourAmount"),
          DataBinder.Eval("DepositAmount"),
          DataBinder.Eval("CancellationAmount"),
          DataBinder.Eval("KeyDepositAmount"),
          hf1.Value )
    End If
  End If
End Sub

Problem 1: Each time I compile my code and click the Select link
the Select link in a Gridview is going to cause a postback and therefore hourDiff is going to be 0 everytime since a postback is going to force all js to be re-evaluated
Problem 2:
Be aware that every control that causes a postback is going to reset your page javascript.  One way to get around that is to save to and restore from hidden field controls (<asp:HiddenField ID="hf1" runat="server" ClientIDMode="Static"...>). then you can access like this: $('#hf1').val(3.14); and the value is preserved between postbacks.
Cookies or local storage are other options
Also, is there any reason that the calculation must occur clientside?  because you have another problem once you redirect to a new page.  Be aware that redirecting, even to the same page, is not a postback.
Update 2015-02-26 14:30 EDT
I cannot see your search code so I'm going to make an assumption that no matter how the user picks a start/end date/time there is a Search button that causes a postback with four fields (assuming asp:TextBox's) of Search data, I'll call them: StartDate, StartTime, EndDate, EndTime.
The Search Button is going to cause a postback which should make the search fields available for use in the code behind.
Build 2 DateTime variables (S, E) and use the DataDiff() function to determine the difference you need.
In your case it would be something like this:
' At class level define the variable:
Dim hourDiff as DateTime = nothing

' In the gridview databinding event do your calculation
Private Sub GridView1_DataBinding(sender As Object, e As System.EventArgs) Handles GridView1.DataBinding
  Dim S as New DateTime( <replace with relevant parameters> )
  Dim E as New DateTime( <replace with relevant parameters> )

  hourDiff = DataDiff(DateInterval.Hour, S, E)
End Sub

' Then in the row databound event append the difference to the hyperlink
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = <build your Hyperlink and Append hourDiff>
    End If
  End If
End Sub

Amended 2015-02-26 18:06EDT

i would have preferred the option of using hiddenField if you could
  explain how to tie hf1 to hourdiff.

Add a hidden field to your page like this:
<asp:HiddenField ID="hf1" runat="server" ClientIDMode="Static">

to js add this:
// define hourDiff
var hourDiff;

// Using jquery place an object reference to the hidden field into hourDiff
hourDiff = $("#hf1");

// Do your time calculations and assign results to hourDiff
hourDiff.val( time_calc_results );

// The above places the results in the hidden field Value property
// which will be available in the code behind as as `hf1.Value` after postback

I am spending more time trying to fix errors on the code you just posted.

Well that's to be expected as it's mostly from memory and is partially pseudo code.

With regards to your latest code, does that mean that I try the javascript
  I posted at the top or use both?

The intent was that the search criteria could be selected Clientside or Serverside, the choice is yours.  But you have to be careful of problem 1. you need a way to preserve the calculation between posts.  Hence my suggestion for the Hidden Field.
Worst case Scenario: 5+ postbacks
In the worst case scenario you post back every time a user selects a time and date so at minimum you have 5 postbacks, one for each start and end date and time and then clicking search.  Posting back like this makes it pointless to do the calculations client side.  I hope you understand why.  Ideally, in this situation the user has made all the selections prior to selecting Search and then you calculation once server side.
Scenarios 2: 1 Postback
In this scenario you have js or jQ code picker that allow the user to select times and dates WITHOUT posting back to the server.  This is a great way to collect data.

*

*If Clientside, you need to make sure the calculation is complete and stored in the Hidden Field before you post back

*If Serverside you need to grab the four field and do the calculation in the Search button click event or in the Gridview DataBinding event.

In either case you need to modify the Hyperlink href.  This could be done client side...maybe.  It depends, if you cause a postback before getting a chance to update the href of the select link.
To me it looks like you added your own hyperlink to each row.  If that is so then you should be able to modify all the hyperlinks with a bit jquery code after you calc hourDiff
// Assuming hourDiff is defined as
var hourDiff = $('#hf1');

... (other stuff)

// and you calc and assign to hourDiff as this:
hourDiff.val( endDate - startDate);

... (maybe more other stuff)

// then you modify your hyperlinks like this
$( "#GridView1 a.js_siteid" ).each( function( i, e ) {
    this.href += "&diff=" + hourDiff.val();
} );

Also, I don't understand:
  Dim E as New DateTime( <replace with relevant parameters> )

It's the VB equivalent of what you are doing in the js code with the Date objects.  There are over a dozen ways to instantiate one so I just left it up to you to pick one that works for you.


Q: Custom legend text on ASP.NET Chart bound by DataBindCrossTable I'm binding an ASP.NET Chart control with DatabindCrossTable and everything works well, except the legend text that is applied.
My table looks like this:
Year     Week     Value
2015     1        530
2015     2        680
...
2016     1        887
2016     2        991
...
2017     1        990
2017     2        1021
...

I'm binding my Chart control this way:
chrtValuesByWeekByYear.DataBindCrossTable(myTable.Rows, "Year", "Week", "Value", "")

My problem is that the legend text is displaying "Year - YYYY", like the image below. How can I just display "YYYY" in the legend?

A: There's plenty of opportunity to configure your Legend and Series, but when you call DataBindCrossTable, you're delegating everything to this method. The only thing you're left with is to overwrite whatever you want after the fact.
So, right after you call DataBindCrossTable, you can for instance, simply do:
foreach (Series s in chrtValuesByWeekByYear.Series)
    s.Name = s.Name.Remove(0, 7);