Q:

c# Nested dictionary of different depths

Essentially what I need is the mapping of different int variables to a dictionary. Or at least that's the way that I was thinking of doing it. The easiest way that I can think to do it slash explain what I want is using switch statements.
string s = "";
int a = 1;
int b = 2;
int c = 0;

switch (a){
    case 0:
        s = "a0";
        break;
    case 1:
        switch (b){
            case 0:
                s = "b0";
                break
            case 1:
                switch (c){
                    case 0:
                        s = "c0";
                        break;
                    case 1:
                        s = "c1";
                        break;
                }
                break
            case 2:
                s = "b2";
                break;
        }
        break;
    case 2:
        s = "a2";
        break;
}

This being a simplified version for brevity's sake, where you would otherwise potentially have many nests and in more than one of the cases and whatnot. I was thinking that a good solution to this would be a dictionary to quickly select the correct value, but that wouldn't really nest well because most of the inner nests of a nested dictionary would not need to have values.
The reason that I thought of dictionaries first is because declaration syntax similar to the following would be nice (which is similar to what it would be for a dictionary of dictionaries).
thing = {
    {0, "a0"},
    {1, {
            {0, "b0"},
            {1, {
                    {0, "c0"},
                    {1, "c1"}
                }
            },
            {2, "b2"}
        }
    },
    {2, "a2"}
}
// Next line is sort of hopeful but potentially unrealistic syntax
s = thing[a][b][c]; // or  = thing(a,b,c);

EDIT: That is not a required declaration syntax, but its short and easy to understand, which is what I'm looking for.
EDIT: or LINQ, i've seen a lot of LINQ suggestions for similar questions, but I'm not particularly familiar with it.

A:

Given that you're looking for a partial match on the key, you're not going to be able to accomplish this with a single dictionary. Here's why:
Suppose you've got some sort of "rule" class. We'll call it "Key". You might instantiate it like this:
Key.Create(0) // this "rule" would match any query key starting with 0 (e.g., {0}, {0, 1}, or {0, 1, 9, 2, 23, 243})

Now suppose you want to query it using some sort of "fact" or "query key" class. Since you query a dictionary using the type of value that was used as the key during the Add operation, you would have to reuse the same type:
Key.Create(0, 2, 13) // this fact should be matched by rules {0}, {0,2} or {0, 2, 13}

Now you're going to attempt to get the value:
var value = map[Key.Create(0, 2, 13)]

The Key class could override Equals to allow partial-key matching. However, the dictionary is going to use the hashcode first, and the hashcode for Key.Create(0, 2, 13) is never going to match the hascode for Key.Create(0). You won't be able to get around this by using any sort of base/derived type either.
The best option would probably be to roll your own class. Something like this should do:
class ResultMap
{
    public void Add(int[] key, string value)
    {
        Debug.Assert(key != null);
        Debug.Assert(key.Length > 0);

        var currentMap = _root;
        foreach (var i in key.Take(key.Length - 1))
        {
            object levelValue;
            if (currentMap.TryGetValue(i, out levelValue))
            {
                currentMap = levelValue as Dictionary<int, object>;
                if (currentMap == null)
                    throw new Exception("A rule is already defined for this key.");
            }
            else
            {
                var newMap = new Dictionary<int, object>();
                currentMap.Add(i, newMap);
                currentMap = newMap;
            }
        }
        var leaf = key[key.Length - 1];
        if (currentMap.ContainsKey(leaf))
            throw new Exception("A rule is already defined for this key.");
        currentMap.Add(leaf, value);
    }

    public string TryGetValue(params int[] key)
    {
        Debug.Assert(key != null);
        Debug.Assert(key.Length > 0);

        var currentMap = _root;
        foreach (var i in key)
        {
            object levelValue;
            if (!currentMap.TryGetValue(i, out levelValue))
                return null;
            currentMap = levelValue as Dictionary<int, object>;
            if (currentMap == null)
                return (string) levelValue;
        }

        return null;
    }

    private readonly Dictionary<int, object> _root = new Dictionary<int, object>();
}

Here's a unit test:
    public void Test()
    {
        var resultMap = new ResultMap();
        resultMap.Add(new[] {0}, "a0");
        resultMap.Add(new[] {1, 0}, "b0");
        resultMap.Add(new[] {1, 1, 0}, "c0");
        resultMap.Add(new[] {1, 1, 1}, "c1");
        resultMap.Add(new[] {1, 2}, "b2");
        resultMap.Add(new[] {2}, "a2");

        Debug.Assert("a0" == resultMap.TryGetValue(0));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 0));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 1));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 2));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 0, 0));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 0, 1));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 0, 2));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 1, 0));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 1, 1));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 1, 2));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 2, 0));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 2, 1));
        Debug.Assert("a0" == resultMap.TryGetValue(0, 2, 2));
        Debug.Assert(null == resultMap.TryGetValue(1));
        Debug.Assert("b0" == resultMap.TryGetValue(1, 0));
        Debug.Assert(null == resultMap.TryGetValue(1, 1));
        Debug.Assert("b2" == resultMap.TryGetValue(1, 2));
        Debug.Assert("b0" == resultMap.TryGetValue(1, 0, 0));
        Debug.Assert("b0" == resultMap.TryGetValue(1, 0, 1));
        Debug.Assert("b0" == resultMap.TryGetValue(1, 0, 2));
        Debug.Assert("c0" == resultMap.TryGetValue(1, 1, 0));
        Debug.Assert("c1" == resultMap.TryGetValue(1, 1, 1));
        Debug.Assert(null == resultMap.TryGetValue(1, 1, 2));
        Debug.Assert("b2" == resultMap.TryGetValue(1, 2, 0));
        Debug.Assert("b2" == resultMap.TryGetValue(1, 2, 1));
        Debug.Assert("b2" == resultMap.TryGetValue(1, 2, 2));
        Debug.Assert("a2" == resultMap.TryGetValue(2));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 0));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 1));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 2));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 0, 0));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 0, 1));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 0, 2));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 1, 0));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 1, 1));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 1, 2));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 2, 0));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 2, 1));
        Debug.Assert("a2" == resultMap.TryGetValue(2, 2, 2));
    }


Q:

Function getting class of retrofit interface to be created causes wrong return type

I am working on an app that has 3 weather APIs and I want my user to be able to choose which one should be used. Each of those APIs has each own data format, so I wanted to create a function that creates proper interface and than wrapps it, so the result is something common, so that I could handle it the same way for each interface.
So my code looks like that:
fun create(api: Apis): ApiDataSource = retrofitBuilder
        .baseUrl(getBaseUrlFor(api))
        .build()
        .create(getInterfaceClassFor(api))
        .convertWith(interfaceConverter)
}

fun Api1.convertWith(interfaceConverter: InterfaceConverter): CommonWeatherDataEntity = ...

private fun getInterfaceClass(api: Apis): Class<*> = when (api) {
    Apis.Api1 -> Api1Interface::class.java
    Apis.Api2 -> Api2Interface::class.java
}

However line after .create(...) is highlighted red and error says "Unresolved reference". That's because create is returning Any!
What I don't understand (are generics obviously) is why the following code works fine:
fun Apis.createInterface(retrofitBuilder: Retrofit.Builder) =
    retrofitBuilder.baseUrl(getBaseUrlFor(this))
        .build()
        .create(
            when (this) {
                Apis.Api1 -> Api1Interface::class.java
                Apis.Api2 -> Api2Interface::class.java
            }
        ).convertWith(interfaceConverter)

A:

Because the type inferred for when(...) is not Class<*>, but Class<out X>, where X is the common supertype of Api1Interface and Api2Interface. So create returns X.
You should be able to see that by removing the return type for getInterfaceClass and checking what the IDE shows.


Q:

KendoUI TreeView binding issue

I am facing an issue , below code bind the tree for first time , but not working binding the tree on second time :(  but when i request third its bind again.
Means even request work .
please help me
Thanks in advance
Mobeen
// My Example Data
{"d":[{"_type":"ManageUPPRM.UserDocumentDTO","DocumentID":1804105651,"DocumentName":"Google Talk","hasChildren":true},{"_type":"ManageUPPRM.UserDocumentDTO","DocumentID":15854591701,"DocumentName":"desktop.ini","hasChildren":false},{"__type":"ManageUPPRM.UserDocumentDTO","DocumentID":15861429553,"DocumentName":"Jellyfish.jpg","hasChildren":false}]}
//Code
var datasource = new kendo.data.HierarchicalDataSource({
                transport: {
                    read: function (options) {
                        var id = options.data.DocumentID;

                        if (typeof id == "undefined") {
                            id = "0"
                        }

                        $.ajax({
                            type: "POST",
                            url: "../ManageUPWebService.asmx/GetAllDocuments",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            data: "{DocumentID:'" + id + "'}",
                            success: function (result) {
                                // notify the data source that the request succeeded
                                options.success(result.d);
                            },
                            error: function (result) {
                                // notify the data source that the request failed
                                options.error(result.d);
                            }
                        });
                    }
                },
                schema: {
               model: {
                        id: "DocumentID",
                        text: "DocumentName",
                        hasChildren: "hasChildren"
                    }
                }
            });

            $("#treeview").kendoTreeView({

                checkboxes: {
                    checkChildren: true,
                    template: "<input type='checkbox' name='#=item.id#' data-text='#=item.DocumentName#' value='true' />"
                },

                loadOnDemand: true,
                dataSource: datasource,
                dataTextField: "DocumentName"
            });

A:

try this,
add a div with some id as the parent div of treeview

and before binding the kendo tree
$("#treeview").remove();
$("
").appendTo("#parent").kendoTreeView({
            checkboxes: {
                checkChildren: true,
                template: "<input type='checkbox' name='#=item.id#' data-text='#=item.DocumentName#' value='true' />"
            },

            loadOnDemand: true,
            dataSource: datasource,
            dataTextField: "DocumentName"
        });


Q:

Use ARRAYFORMULA in a custom script function (Google Sheets + GAS)

Is there any way to adjust this function for use with ARRAYFORMULA in spreadsheets?
function SendTelegram(botSecret, chatId, body) {
  var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendMessage?text=" + encodeURIComponent(body) + "&chat_id=" + chatId + "&parse_mode=HTML");
}

Instead of using a formula for each line like this:
=SendTelegram($H$1,$I$1,F2)
=SendTelegram($H$1,$I$1,F3)
=SendTelegram($H$1,$I$1,F4)
=SendTelegram($H$1,$I$1,F5)

By using this way:
=ARRAYFORMULA(SendTelegram($H$1,$I$1,F2:F))

Returns the following message:
Limit Exceeded: URLFetch URL Length. (line 22).

A:

Something like this, you might have to adjust to the particular behavior you want.
function SendTelegram(botSecret, chatId, body) {
  if (body.map) { // is array?
  var response = body.map(function(b) {return SendTelegram(botSecret,chatId,b);});
   } else {
  var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendMessage?text=" + encodeURIComponent(body) + "&chat_id=" + chatId + "&parse_mode=HTML");
  }
}


Q:

Can you send a file larger that the SendBufferSize throuh a TcpClient?

I am experimenting with the Tcp connections in .NET and I would like to send some data that is larger than the SendBufferSize proporty of the TcpClient object. Is it possible to send the data by simply writing to the network stream or do I need to cut it in pices and send those and at the other end create it again?

A:

From MSDN:

If the network buffer is smaller than the amount of data you provide the Write method, several network send operations will be performed for every call you make to the Write method.

You only need to call Write once, the TcpClient will handle splitting it into multiple network operations.


Q:

Where does GCM data to be pushed get stored?

In GCM, there are three main components

GCM server
third party app server
client (mobile)

Which one of them stores the data that is to be pushed?
For example, if a mobile1 has to communicate with a mobile2 and it wants to send a message "HI" and an image, then where does this two pieces of data get stored, on the app server, or on the GCM server?

A:

Found out a solution the flow is like from
app server to ccs to gcm


Q:

count items up onclick by class name

I want to create an eshop basket.. so i want to count items up when i press a buy button. I tried to use getElementById and simple call the name of id in my basket.
--

somewhere in the top -----

items :<input type="text" id="tb" style="width: 20px; color:green; font-weight:bold; border:none; background: none; margin-left:20px;"/>

and when i press the buy button -------
<input  name="button" type="submit" value="add to basket" onClick="index = index + 1;document.getElementById('tb').value = index;" />

so this is worked .. but know i want to duplicate the basket and have it twice in the page ( in the top and in the end ) so if i tried to call again the same id it just don't work (cause the uniqueness of id). I suppose i should use classname istead but i don't know how ..
I'm more than new to js hoping for a solution.
Thanks

A:

You could duplicate document.getElementById('tb').value = index and use a second (unique) id. Or you iterate over documnet.getElementsByName('elementsname'), but your input would have to have a name attribute.


Q:

Why is it sufficient to show that $f:X\rightarrow Y$ is open iff every image of an openset contains some nonempty openset

I can't wrap my head around the concept that to prove that $f:X\rightarrow Y$ is open, it is sufficient to show that every image of an openset $U\subset X$, $f(U)$ contains some nonempty openset $V\subset Y$. How can this be implied from the definition of an open mapping. That is,  $f:X\rightarrow Y$ is open iff for every openset $U\subset X$, $f(U)$ is open.

A:

You are missing a crucial point! You need to quantify over the elements of $U$; that is $f$ is open if for all open $U$ and all $x\in U$ there exists some open neighborhood $V$ of $f(x)$ contained in $f(U)$.
Recall that a subset $U$ is open iff for all $x\in U$ there exists some open neighborhood $V_x\subseteq U$ of $x$. Indeed, in such a case
$$
U = \bigcup_{x\in U}V_x,
$$
and since every $V_x$ is open, so is $U$. Now, apply this knowledge to $f(U)$.

A:

Your statement is false as stated - it can't "sense" what happens at points, which allows for functions like
$$f(x)=x^2$$
where the image of every open set contains an open set, but might not be open.
You can salvage this statement by requiring that this condition somehow apply to all points equally:

A function $f$ is open if, for every $x$ and every open set $U$ containing $x$, there is some open set $V$ contained inside of $U$ which contains $f(x)$.

This is straightforwards to prove - this condition means that every point in $f(U)$ has an open neighborhood in $f(U)$, but then $f(U)$ has to be the union of these neighborhoods - hence must open.


Q:

Keeping track of branches on Git?

Possible Duplicates:
How do you annotate a branch?
Branch descriptions in git

I have a repo with lots of branches. Maybe 12 or so, and they won't be merged into master anytime soon.
Is there a way to document the purpose of each branch within git?
The thing I seek is to a branch what a commit message is to a commit.
I don't think tags are what I want, because tags don't follow the HEAD as I add more commits to a branch.
I could write a plaintext file listing the state of each branch with some notes, but its not obvious which branch the text file would go in.

To clarify, I do name my branches. But I would want to be able to have a description too. So for example I would want to write for branch RTPhase:

This branch has added features to support real-time analysis of curvature and phase. As a trade off it runs more slowly than other branches because it uses functions like calculate mean curvature that haven't been optimized for speed.

A:

The answer I'm coming to about this is to devise a convention that I can hew to rigidly.
My master "release" branch is called "master". My "hotfix" branch (for fixes live in production) is called "hotfix". My branch for development on the next release is called "dev".
Then I make any branches off of those branches carry the name. So a feature branch for something I'm working on here to do with maps is called "dev/maps". I have a survey feature I'm adding in a branch "dev/survey".
If I had a hotfix that was going to take any real time to do, I'd probably branch into "hotfix/short-description-of-branch".
The slash doesn't have any syntactic value in a branch name, it's just text, but I use it to imply "inside-ness".


Q:

Adding border-radius to TinyMCE textarea

Is it possible to add a border-radius to TinyMCE'd textareas? It's kinda killing me that I have rounded corners on my input fields etc, but I can't get it working on my textarea.. Probably because TinyMCE is turning it into an IFRAME? Is there any way around this? Thanks a lot!

A:

One solution is to use the editor_css setting.
This css gets applied after the default tinymce css is loaded thus overwrite the default one.
I created a file called editor.css containing the following
.defaultSkin table.mceLayout {border:1px solid black}

and set the tinymce parameter using editor_css
editor_css : 'path_to_css'.'/editor.css',

This creates a nice thin black line around the editor.


Q:

Time picker format changes ,When inserting into database

View:
<div class="col-sm-6">
  <input type="text" class="form-control timepicker" name="shiftStartTime" id="shiftStartTime" required parsley-maxlength="6" placeholder="Shift Start Time" />
</div>

Script
<script type="text/javascript">
$(document).ready(function(){

   $('.timepicker').wickedpicker();

    });

</script>

Controller code :
$shiftstarttime = $this->input->post('shiftStartTime');

But it is inserting into database as "00:00:12".How to change it to the H:m:s format (ie 12:05:10)

A:

First you need to confirm that in post you are getting correct value if yes then following would work for you
$input = $this->input->post('shiftStartTime');
$input = str_replace(" : ", ":", $input);
$shiftstarttime = date('H:i:s', strtotime($input));


Q:

Apache Proxy for Node.js and Wordpress on same "Domain" but different paths

Here is the case.
I have a Wordpress website running on my main domain say http://www.example.com.
.htaccess is enabled on server and I am using Wordpress permalinks to generate pretty URLs.
Now I have another application in Node.js (Express) which I have deployed on same server and is running on port number 3000. So if I put http://www.example.com:3000 it triggers my Expressjs app. and it is running flawlessly.
What I want is to run the Node.js application on a specific path from the same domain. For example, if I hit, http://www.example.com/node it should take user to my Node.js app which it is taking quite fine if I use Apache mod_proxy. But this works only for the / route of my Expressjs router.
But I also have several other routes e.g. /subscribe, /confirm but none of them work.
Following is my Apache config which I tried to make work by giving multiple ProxyPass directives but it doesn't work.
ProxyPass /node http://127.0.0.1:3000/
ProxyPassReverse /node http://127.0.0.1:3000/
ProxyPass /node/subscribe http://127.0.0.1:3000/subscribe
ProxyPassReverse /node/subscribe http://127.0.0.1:3000/subscribe

The Express router is pretty basic and uses following app configuration:
var router  = express.Router();
app.use("/",router);

router.get("/",function(req,res){
   res.sendFile(templatepath + "index.html");
});

router.get("/subscribe",function(req,res){
   res.sendFile(templatepath + "subscribe.html");
});

router.get("*",function(req,res){
   res.sendFile(templatepath + "404.html");
});

When I try to load http://www.example.com/node/subscribe it simply loads the * route and displays the 404.html template.

A:

Finally got it working by modifying the Apache configuration file as follows:
ProxyPreserveHost On
RewriteEngine On
ProxyPass ^/node/(.*) http://127.0.0.1:3000/$1 [P,L]
ProxyPassReverse /node/ http://127.0.0.1:3000/


Q:

iPhone settings: create dependent settings?

Is it possible to create "dependent settings"? e.g. you have hierarchical settings like this:
 - include animals
 -- include dogs
 -- include cats

where toggling animals would automatically toggle dogs and cats (I know I can cater for that in code, but can the settings screen that is provided by the OS be configured so the UISwitch for dogs is automatically set to off if include animals is set to off?)

A:

No. You'll either need to change your UI so this toggle is not required, display both options and hope it doesn't confuse your users or only include the settings inside your app where you can write the correct code yourself.
This is a really annoying limitation. It's probably worth raising a bug report with Apple.


Q:

Changed Typescript-Version

I have a project written in typescript v.1.4 "ECMA6" and i want to use 'async' only because of some calculations needed to be asynchronous.
But after I upgrade my typescript version to 1.8 in Visual Studio 2013, I got big problems with extended classes and I have no idea why?
The exception i get is:

Class constructor "XYZ"cannot be invoked without 'new'

The classes looks like a extend b, b extend c...
class XavObject {
    constructor() { }
}

class XavWidget extends XavObject {
    constructor(control: JQuery, name?: string, id?: number) {
        super();
    }
}

class Widget_ConstructionKitContainer extends XavWidget {
    constructor(control: JQuery, controlName: string) {
        super(control, controlName, 1); // ---> here throws the exception
    }
}

Why this exception occurs and what can i do to resolve it?
EDIT:
I try to give more information...
I have a webservice written in C# wich makes the .js-Files from the .ts-Files accessible. Something like "http://localhost:8080/DLLName/XavObject.js"
So that the HTML looks like:
 <script src="XavObject.js"></script>
 <script src="XavWidget.js"></script>
 <script src="Widget_ConstructionKitContainer.js"></script>

 <script>
        xavManager.jQuery(document).ready(function () {
          var constructionKitContainer =
          new Widget_ConstructionKitContainer(
          xavManager.jQuery('#ConstructionKitContainer'),
          "ConstructionKitContainer",

          xavManager.jQuery('#regionSelector'),
          xavManager.jQuery('#regionConfigurator'),
          xavManager.jQuery('#regionContainer'),
          xavManager.jQuery('#Preview'),
          xavManager.jQuery('#ThreeDContainer'),
          xavManager.jQuery('#MainThreeD'),
          xavManager.jQuery('#NavThreeD'),

          [xavManager.jQuery('#ModelTypAuswahl'),
          xavManager.jQuery('#ModelformAuswahl'),
          xavManager.jQuery('#WandArtikelAuswahl'),
          xavManager.jQuery('#EbeneAuswahl'),
          xavManager.jQuery('#ElementAuswahl'),
          xavManager.jQuery('#MaterialAuswahl'),
          xavManager.jQuery('#SetArtikelAuswahl'),
          xavManager.jQuery('#GriffArtikelAuswahl')],
           constanten
          );
        });
 </script>

After i call the page, the last script is executed and throws the exception.
The Structure of the Project looks like:
So the three Classes are in three Files and two of them in the same libori, the other one in another.
EDIT Part2:
After I have restarted my pc this error message disappears ...
But another Error in some js-File appears....

Syntax Error ONLY IN JS-FILE
  He can't compile one File

class SelectionRules extends ValidationRules {

   protected _getNewTimedOutObject():         ValidationRules_TimeoutItem_Calculate|SelectionRules_TimeoutItem_Calculate {
       return new SelectionRules_TimeoutItem_Calculate();
   }
}

class SelectionRules_TimeoutItem_Calculate extends     ValidationRules_TimeoutItem_Calculate {
   public liElement: HTMLElement;
}

class ValidationRules_TimeoutItem_Calculate {
   public Timeout: number;
   public Setting: Widget_ConfiguratorBase_Object_Setting;
   public SearchString: string;
   public ErrorText: string;
   public Value: string = "";
   public DataElement: Widget_Article_Setting;
   public ContainerEntryIndex: number;
}

Is it because these Part?
  ValidationRules_TimeoutItem_Calculate|SelectionRules_TimeoutItem_Calculate

But why does these lines work with TypeScript 1.4?

A:

After tons of hours i got it....

After you upgraded TypeScript, restart Visual-Studio!
  If you work with ECMA6 and you Double Typed like Parameter/Functions like ValidationRules_TimeoutItem_Calculate|SelectionRules_TimeoutItem_Calculate you need to Change the solution-options back to ECMA5
  same issue with new generated Classes! --> back to ECMA5 it will work
  after compile these everything work


Q:

Why is this function continuous? (Topology)

Consider a space $Y = (\mathbb R,\mathcal F)$, where $U$ is element of $\mathcal F$ iff $U$ is empty or $U$ contains the number $1$. (It can be proven that $Y$ is topological space).
Let $y_1,y_2$ be element of $Y$. Why is this function continuous?
$$ \begin{aligned}
f \colon [0,1] &\to Y \\
t &\mapsto \left\{
\begin{aligned}
y_1 \quad &\text{if}~ t = 0 \\
1 \quad &\text{if}~ 0 < t < 1 \\
y_2 \quad &\text{if}~ t = 1 \\
\end{aligned} \right.
\end{aligned}$$

A:

the pre-image of any nonempty open set in $Y$ must be one of $[0,1), (0,1)$ or $(0,1]$, since all of these are open in the usual topology for the closed unit interval $I$, the pre-image of any open set in $Y$ is open in $I$. but this is the condition for continuity.
(a few remarks added in response to comments and OP's request for clarification)
in reading math we frequently see confessions like: "this abuse of notation should cause no difficulties..." hmmm.
one of the most frequent abuses of notation is the use, for a mapping $f$ of the symbol $f^{-1}$. this has a clear meaning only when $f$ is both surjective and injective. otherwise the inverse function exponent $^{-1}$ conveniently avoids mentioning the fact, which might easily bewilder those new to the subject, that we are in fact dealing with a contravariant functor from the category of sets to its subcategory of powersets.
with the usual notation $\mathfrak{P}(A)$ for the operation of forming the powerset, then if we have a function $f:A \rightarrow B$ then under the action of the (more familiar) covariant powerset functor we have:
$$
\mathfrak{P}(f): \mathfrak{P}(A) \rightarrow \mathfrak{P}(B) \\
$$
defined by
$$
\forall \mathbb{a} \in \mathfrak{P}(\mathbb{a}),\; \mathfrak{P}(f)(\mathbb{a}) = \bigcup_{a \in \mathbb{a}} \{f(a)\}
$$
this is very natural for our minds to think about, so the categoric underpinning is left aside as excess baggage. this shows, for example, in refusing to use a notation which clearly distinguishes $f$ and $\mathfrak{P}(f)$ or in the way the set-forming operator $\{\dots\}$ would usually be omitted from the union on the right. the identification with an element $x$ of $A$ with the corresponding singleton set $\{a\}$ in  $\mathfrak{P}(A)$ is easy and does not cause much trouble at an elementary level.
the contravariant powerset functor, which we may denote here by $\mathfrak{P}^{-1}$ for emphasis, takes each set to its powerset as before, but its effect on functions is different. in fact we have:
$$\mathfrak{P}^{-1}(f):\mathfrak{P}(B) \rightarrow \mathfrak{P}(A)$$
a reversal of direction flagged by the prefix contra-. its action is defined by:
$$
\forall \mathbb{b} \in \mathfrak{P}(B),\; \mathfrak{P}^{-1}(f)(\mathbb{b}) = \bigcup_{b \in \mathbb{b}} \{a \in A \mid f(a)=b\}
$$
so typically we use the notation $f^{-1}$ as a convenient abbreviation for $\mathfrak{P}^{-1}(f)$.
as an example of the utility of this more precise way of looking at the matter, note that we may say $f:A \rightarrow B $ is surjective iff
$$ \forall \mathbb{b} \in \mathfrak{P}(B), \;f^{-1}(\mathbb{b}) = \emptyset \rightarrow \mathbb{b} = \emptyset  $$
also note that a topology on a set $A$ is actually just a single element of the set $\mathfrak{P}^2(A)$, as should be clear from its description as a family of subsets of $A$.


Q:

Best way to hide 10000 dropdown menus

Context -
I have a chat component and each individual chat message has a dropdown.

And the dropdown menu is opened by clicking the "More Options icon"(3 dots).
Each individual chat message is a "backbone item view"
One solution is to listen to click on "body", loop through all the menus and then close the dropdown by removing a class on it.
$("body").on("click", function() {
  $(".drop-down-menu").each(function(idx, item) {
      $(item).removeClass("open"); // open class indicated it is open via CSS
  });
});

The CSS -
.drop-down-menu {
    visibility: hidden;
    opacity: 0;
    &.open {
       opacity: 1;
       visibility: visible;
    }
}

Will there be any performance impact if there are 10,000 messages or more?
Hence, I am looking for the best solution to hide the drop down if user clicks anywhere on the screen.
Thanks.

A:

You can make some trivial changes that should improve the performance of your code. The first thing is that there's no reason to loop like you are doing. jQuery objects are collections and jQuery operations usually loop over the elements of a jQuery object. So:
$("body").on("click", function() {
  $(".drop-down-menu").removeClass("open");
});

This will automatically remove the class open from all elements matched by the selector ".drop-down-menu". jQuery will still go over a loop internally, but it is faster to let jQuery iterate by itself than to have .each call your own callback and then inside the callback create a new jQuery object on which to call .removeClass.
Furthermore, you logically know that removing the open class from elements that do not have this class is pointless. So you can narrow the operation to only those elements where removing open makes sense:
$("body").on("click", function() {
  $(".drop-down-menu.open").removeClass("open");
});

These are principles that are widely applicable and that have trivial cost to implement. Anything more than this runs into the realm of optimizations that may have downsides, and should be supported by actually profiling your code. You could replace the jQuery code with code that only uses stock DOM calls but then if you need support for old browsers the cost of dealing with this and that quirk may not be worth it. And if you are using stock DOM methods, there are different approaches that may yield different performance increases, at the cost of code complexity.


Q:

Has the WPS brute-force cracking issue been fixed?

I have heard a rumor that the WPS brute force attack doesn't work on newer devices. Is that true?

A:

The three major problems with WPS are: (1) it requires only an 8 digit pin (10^8 is a small keyspace), (2) one digit of that pin is a checksum (hence 7 independent digits and 10^7 pins to check), and (3) the first group of four digits is checked independently - that is you need to only check at most 10^4 ~ 10000 pins to break the first group of four digits; and then 1000 to check the second group (since you know one digit due to the checksum).  And really the expected number of attempts is half that; so on average only ~5500 attempts are needed.
WPS slightly mitigates this by mandating that you are locked out for 60 seconds after three consecutive bad attempts.  Originally, not all WPS routers enforced this timeout (very bad even without vulnerabilities 2 and 3; checking at a rate of 10 per second; means you can break your neighbor's router in a few months).  Some manufacturers will increase this timeout on subsequent failures, which is good.  Note the three attempts = 60s timeout is not a panacea; e.g., will take 3.82 days on average (and at most 7.64 days) to crack into your neighbors WPS enabled router.  Granted exponential timeouts could mitigate brute forcing; however how these timeouts are implemented is important.  (E.g., if the attacker changes their wifi mac address on each attempt will they continue to be blocked out?  Otherwise can you use this to DoS WPS connections?).
Now to answer your question: CERT (last updated May 2012)  is "currently unaware of a practical solution to this problem" and recommends disabling WPS.
Also while there are rumors of a new WPS 2.0 standard eventually coming out, especially in the responses to this vulnerability.  Hopefully, this fix would not let an attacker know if they've found a portion of the key and hopefully would require all digits to be independent instead of having a worthless checksum.  However, the wifi alliance page on WPS doesn't mention this at all (e.g., the last press-release on WPS is from Feb 2008) unless its in one of the standards that cost $100-$200 to purchase.  Standards tend to change slowly as it requires both the software and hardware end of the client and router to be fully compatible (and backward-compatible).
Granted, I'd expect nowadays more WPS enabled routers to implement the 60s + exponential timeout, but still would never recommend for anyone to use WPS.


Q:

-gc-sections discards used data

Using avr-gcc, avr-ld
I'm attempting to severely reduce the size of the output file by using fdata-sections -ffunction-sections and gc-sections. When compiled without these options I have an output of ~63KB, and with these options its ~30KB, so it seems great.
Unfortunately, after loading and testing the output I notice it doesn't work correctly. Garbage collection seems to have removed far more than I expected, and examining the .map I notice some key data is nonexistent.
Any idea on what at link time is causing these data/functions to be discarded? (I realize this may be too hopeful of a question with how little detail I provided, if any information is needed please ask and I'd do my best to provide it)
Is there a way to trace what symbols were tossed by garbage collection as they were "unused"?
Without using -fdata-sections -ffunction-sections -gc-sections, can I trace a symbol dependencies? (To verify gc-sections only collected what it should)
    - I noticed this this as an option, but it would be very painful for me to use the method suggested by Verax
EDIT: compiler and linker lines
avr-ld -mavrxmega6 -gc-sections -Tlinkerscript files libgcc.a -o firmware.elf
avr-gcc -Wall -Wstrict-prototypes -g -ffunction-sections -fdata-sections -Os -mmcu=atxmega256a3 -fno-jump-tables -std=gnu99 -fpack-struct -fno-common -mcall-prologues -c -o file.o file.c

A:

There was a pretty obvious ld option called -print-gc-sections to review what is being tossed out.
I never found a way to trace dependencies on a symbol, but ended up not needing to with reviewing -print-gc-sections.
I found this that described "magic sections" and I imagine this is similar to what I was seeing. There were many custom linker sections that were discared incorrectly, I used KEEP to prevent gc of these although I'm sure there is dead code not being removed now, but this may be the best I can do.


Q:

Showing branch hierarchy at the command line?

I'm curious if there is a way to show branch hierarchy on the command line? For instance if I use git branch, instead of seeing output like this:
* master
joes_work
refactoring
experiment

You see output like this:
* master
    joes_work
    refactoring
        experiment

That way it's easy to see which branch a particular branch.. branched off of. Even if there's no specific command that outputs a tree structure, is there a command that outputs information on which branch came from which branch? I can use a perl script to format the output.

A:

sehe's solution looks great, here is another one that seems to contain similar information, formatted differently, it uses git log, so it contains commit information as well (ignore the branch names, I kind of messed them up!):
git log --all --graph --decorate --oneline --simplify-by-decoration

* ae038ad (HEAD, branch2-1) add content to tmp1
| * f5a0029 (branch2-1-1) Add another
|/
* 3e56666 (branch1) Second wave of commits
| * 6c9af2a (branch1-2) add thing
|/
* bfcf30a (master) commit 1

A:

Try
git show-branch
git show-branch --all

Example output:
bash$ git show-branch --all
! [branchA] commitA only in branchA
 * [branchB] commitB
  ! [branchC] commitC only in branchC
---------------------
+   [branchA] commitA only in branchA
 *  [branchB] commitB
  + [branchC] commitC only in branchC
 *+ [branchC~1] commitB-1 also in branchC
 *+ [branchC~2] commitB-2 also in branchC
+++ [branchC~3] common ancestor
+++ [branchC~4] more common ancestors

A:

I want to complete the answer of @ctcherry.
I like when I can also see the user who did the commit and the date, so this is the following line to use :
git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

However this is a pretty long line and difficult to memorize so you can use an alias.
You just have to use this in your terminal :
git config --global alias.lg "HERE GOES MY BIG LOG COMMAND LINE"

To summarize copy and paste the line below on your terminal:
git config --global alias.lg "log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Then you will just have to use git lg to get your log history tree.
Example:

src


Q:

How do I disable mouse acceleration AND adjust tracking speed in High Sierra?

The obvious answer you can find everywhere is:
defaults write .GlobalPreferences com.apple.mouse.scaling -1
which disables mouse acceleration, but locks you at one sensitivity.
Old solutions:
SmoothMouse no longer works. Mouse Acceleration Preferences Pane and SteelSeries ExactMouse both behave the same as com.apple.mouse.scaling -1 at all tracking speed settings (but without restart required).
Is it possible to disable mouse acceleration while still being able to adjust the sensitivity?

A:

The built-in options are limited. To achieve your goal a combination of different software could be needed.
Sensitivity and mouse acceleration
Terminal
Like you have already mentioned, the following setting needs to be applied to disable mouse acceleration.
defaults write .GlobalPreferences com.apple.mouse.scaling -1

It can be a good idea to establish a script to automatically perform this action during login to ensure it is properly applied.
SteerMouse
SteerMouse can then be used to adjust your sensitivity. It does require a license, but it also resolves the issue.
Simply download and install the software, either from their homepage or by using e.g. Homebrew:
brew cask install steermouse

The Cursor settings can then be adjusted to your liking. Acceleration should be left at 0, while sensitivity can be tuned to your preference.

Speed = ON
Acceleration = 0
Sensitivity = 0-2000

If using e.g. BetterTouchTool, then remember to turn Buttons, Wheel and Chords off in SteerMouse. These are known to conflict and generate erratic mouse behavior, as they both utilize similar macOS API endpoints.

Scrolling
Semi-related are also modifications to scrolling which can improve the Mac mouse usage experience.
SmoothScroll
Scrolling with a mouse on macOS can feel unnatural. To improve this one can utilize applications such as SmoothScroll for a better flowing scroll. Further adjustments can be made to customize the speed and related settings to ones need.

It can be downloaded and installed directly from the homepage, or by using e.g. Homebrew:
brew cask install smoothscroll

Scroll direction
It can be preferential to have different scroll directions between the trackpad and mouse. This can be adjusted in System Preferences -> Mouse. Checking/unchecking Scroll direction: Natural modifies this behavior.

Notes

The recommended options have been tested to work on macOS Mojave 10.14.4.
Licenses might be required for the suggested software.
I am in no way affiliated with the software developers, just a satisfied user. These are workarounds I have found when attempting to resolve the issue(s).


Q:

Equation program - Error seems to point to the wrong line

I'm creating an app where a user enters between 7-10 numerical values across a few activities. Entries are then used in a fairly layered equation which returns a result to the user. Two values are giving me trouble and producing a NumberFormatException that I cannot figure out.
One entry, IHCValue is chosen from a spinner as there are only 4 possible choices:
<string-array name="ihc_choices">
    <item>0</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

This choice is not only used in the equation but determines if additional information is needed.
Obtaining IHCValue:
   private void directSpinner(){

        int spinnerPosition = scoreSelect.getSelectedItemPosition();
        String[] IHC_Values = getResources().getStringArray(R.array.ihc_choices);
        String IHCValue = String.valueOf(IHC_Values[spinnerPosition]);
        SharedPrefManager.write(IHC_VALUE, IHCValue);

        //The string to manage Intent defined separately as the intent did not recognize the value of 'String IHCValue'
        String IHCEntry = scoreSelect.getSelectedItem().toString();
        if (IHCEntry.equals("2")){
            //Status equivocal, must collect more information before calculation can be performed.
            Intent next = new Intent(getApplicationContext(), FishScoreActivity.class);
            startActivity(next);
        } else { //IHCValue of 0,1,3
            //Status is defined, we have enough info to perform calculation.
            Intent last = new Intent(getApplicationContext(), CancerDemographicActivity.class);
            startActivity(last);
        }
    }

If the user selects "2" from this dropdown the next activity asks for FISHEntry, also used in part of the equation:
Obtaining FISHEntry:
public boolean validateData(){
    boolean validData = false;

    String FISHEntry = enterFISH.getText().toString();

    if (!FISHEntry.equals("")){
        SharedPrefManager.write(FISH_RATIO, FISHEntry);
        validData = true;
    } else {
        Toast.makeText(getApplicationContext(), "Please enter FISH ratio from your report.", Toast.LENGTH_LONG).show();
        validData = false;
    }
    return validData;
}

Then, the user can press a button and run the equation. If the user selected an IHCValue of 0,1, or 3 the FISHEntry is not needed and the equation runs fine.
If (and only if) IHCValue = 2 then an additional calculation must be performed within the Equation class, and crashes the app.
Steps I performed from within the app:

From the spinner, IHCValue of 2 is selected.
Prompted to enter FISH score, FISHEntry = 2.3
Press "Calculate" button:

Then the app crashes:
Caused by: java.lang.NumberFormatException: Invalid int: "2.3"
    at java.lang.Integer.invalidInt(Integer.java:138)
    at java.lang.Integer.parse(Integer.java:410)
    at java.lang.Integer.parseInt(Integer.java:367)
    at java.lang.Integer.parseInt(Integer.java:334)
    at com.them.health.Equations.MasterEquation.<clinit>
(MasterEquation.java:42)

"2.3" is my FISHEntry while line 42 which declares IHCValue:
MasterEquation.java:42
private static int mIHCValue = Integer.parseInt(SharedPrefManager.read(IHC_VALUE, null));

FISHEntry is declared on MasterEquation.java:41:
private static double mFISHRatio = Double.valueOf(SharedPrefManager.read(FISH_RATIO, null));

To be consistent, all values are saved to SharedPrefs as string and I parse int or double as needed when the equation is performed. Also, I received a String-to-Integer error when saving the IHCValue directly as an int.
Method in MasterEquation.java which uses the variables:
private void calcRatioOne(){

    double innerRatio = mIHCValue/mFISHRatio;

    if (mIHCValue == 0 || mIHCValue == 1){
        mRatioOne = 0.0;

    } else if (mIHCValue == 3){
        mRatioOne = 12.75525;

    } else if (mIHCValue == 2){ //IHC = 2 takes FISHEntry into account.

        if (innerRatio >= 2.2){
            mRatioOne = 12.75525;
        }
        if (innerRatio >= 1.8){
            mRatioOne = 1.46495;

        }
        if (innerRatio < 1.8){
            mRatioOne = 0.0;

        }
    }
}

private double mRatioOne; is defined at the start.
I have tried the following:

Write values to SharedPrefs as int/float when the user enters them. Error converting to double when equation is run.
Created a method specifically to handle the innerRatio calculations. Same problem.
Declare and handle IHCValue as a double/float. Same problem.
Declared IHCValue as Integer instead of int. Same problem.

This is only a problem when IHCValue = 2
I am not opposed to changing the IHC Entry from a spinner to another entry method if that would help, but would like to avoid free text since this is the most important entry in the sequence.
My SharedPrefManager:
Key declared:
public static final String IHC_VALUE = null;

Read & Write Method:
public static String read(String key, String defValue){
    return userPrefs.getString(key, defValue);
}

public static void write(String key, String value) {
    SharedPreferences.Editor prefsEditor = userPrefs.edit();
    prefsEditor.putString(key, value);
    prefsEditor.commit();
}

A:

It is obvious from the error message what the problem is. You are trying to assign the value "2.3" to an integer-type variable.

The best solution would be to use a debugger tool, offered within most
  Integrated Development Environments (IDEs) like IntelliJ or
  Eclipse. With that debugger tool, discover why the wrong value is
  assigned to IHCValue in the first place, and act accordingly to fix
  the fault.

I don't agree with the fix proposed in the comments by @shark; assigning a Float to an int is an incompatible operation. My suggestion is to change the type of mIHCValue to double.
If mIHCValue has to be an integer, then convert it from a String, to a double and then cast as an integer. Like so:
private double originalIHC = Double.valueOf(SharedPrefManager.read(IHC_VALUE, null));
private static int mIHCValue = (int) originalIHC;

Let me explain why I did this in 2 lines. Since the value of the String is not an integer, but a floating point number, we have to parse it as a double first. But to convert a String to the primitive double is not possible, so we have to use the Wrapper class Double for this.
The Wrapper class Double (boxing) is not compatible with a primitive type other than double, so we assign the "wrapped" value to its primitive first.
After converting the initial value to a double primitive, we can cast it to an integer like I  displayed.
Note that this solution will help you get only the integer part of any floating point number. For example, if the mIHCValue is 2.8 or 2.0012 or 2.532 or 2.9999999, the resulting integer will always be 2. So, be careful and think about what it is that you want to achieve.
Hope this helps.


Q:

Find and sort 2d array elements like radar

I don't know relevant keywords about this algorithm.
I can show you visually

Any ideas are appreciated

A:

For each of your points in the field, calculate the red angle:

Then sort all the (point, angle)-tuples by the angle.


Q:

What is JavaSE-18 in eclipse vs. my installed jdk1.8.0_73

In eclipse, ./gradlew is generating JavaSE-1.8 instead of using my jdk1.8.0_73.  What jdk is this because I discovered lately that it seems like it is 'not' my jdk1.8.073 for the following reason.....
I installed alpn.jar from jetty in jre/classes (I unzipped the classes there since the sun.boot.class.path says that directory is in the bootclasspath AND then I don't have add -Xbootclasspath to every tool in the world on my computer).
When I ./gradlew eclipse, my projects using this jar break and then when I remove JavaSE-1.8, and then re-add jdk1.8.0_73, all is fine and it compiles in eclipse and intellisense works and everything.
Soooooo, what is JavaSE-8 and how to remove it so when ./gradlew eclipse runs, it uses whatever default my eclipse is pointing to which in my case is jdk1.8.0_73.
One last question, why is JavaSE-1.8 not even listed on Installed JREs?
This is all quite confusing.

A:

If you know there to find the "Installed JREs" in the Eclipse Preferences, just expand the "Installed JREs" node and select "Execution Environments", and things should become clear.
See https://wiki.eclipse.org/Execution_Environments for details of what they are.

Execution environments (EEs) are symbolic representations of JREs. For example, rather than talking about a specific JRE, with a specific name at a specific location on your disk, you can talk about the J2SE-1.4 execution environment. The system can then be configured to use a specific JRE to implement that execution environment.

Obviously that text was written some time ago, but your JavaSE-1.8 execution environment should automatically map to a Java 8 installed JRE. If you have more than one Java 8 installed JRE, you can choose which you prefer.


Q:

PHP get URL content

I have a URL
http://localhost/ifocus/v3/services.php#nav-section2

I want to get hashtags from URL, EX : if the URL contains "#" so capture it via PHP

nav-section2

When i do
echo $_SERVER['REQUEST_URI'];

// Output
/ifocus/v3/services.php

A:

You can't detect the hash parameter of the URL in PHP, you would need to use JavaScript.
You could make a jquery call to php which passes the hash data (window.location.hash) to a PHP script as a URL parameter and return TRUE/FALSE though.


Q:

Redux store: Element type is invalid: expected a string

I am getting an error setting up the store for redux using typescript for the first time.
The error message is as following:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  11 | // tslint:disable-next-line
  12 | const store = configureStore(undefined);
  13 |
> 14 | render(
  15 |   <Provider store={store}>
  16 |     <ConnectedRouter history={createHistory()}>
  17 |       <App />

 import * as React from 'react';
    import {render} from 'react-dom';
    import {ConnectedRouter} from 'react-router-redux';
    import {Provider} from 'react-redux';
    import configureStore from './store/configureStore';
    import createHistory from 'history/createBrowserHistory';

    import App from './App';
    import './styles/styles.css';

    // tslint:disable-next-line
    const store = configureStore(undefined);

    render(
      <Provider store={store}>
        <ConnectedRouter history={createHistory()}>
          <App />
        </ConnectedRouter>
      </Provider>,
      document.getElementById('root') as HTMLElement
    );

My configurestore:
import {createStore} from 'redux';
import rootReducer from '../reducers';

interface WindowModuleHot extends Window {
  module: {
    hot: {
      accept: (path: string, callback: () => void) => void;
    };
  };
}

export default function configureStore(initialState: any) {
  const store = createStore(rootReducer, initialState);
  const hotWindow = window as WindowModuleHot;

  if (hotWindow.module && hotWindow.module.hot) {
    // Enable Webpack hot module replacement for reducers
    hotWindow.module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers');
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}

A:

ConnectedRouter is for version 5.0 of react-router-redux. Npm currently points to v4.0.8 here.


Q:

Create polygon geometry from BBOX coordinates in PostGIS

I have a table mytable with coordinates representing Bounding BOX of an object as a text string in column geom_bbox like "548477,6591107,548493,6591121". Coordinates in EPSG3301 in meters. I want to create a polygon geometry, a rectangle geometry using those coordinates.
More example coordinates:
"548477,6591107,548493,6591121"
"545827,6587929,545864,6588021"
"539646,6586576,539694,6586621"
"549054,6594762,549101,6594811"
"547131,6589014,547182,6589046"
"547131,6589014,547182,6589046"

Is it possible with PostGIS?

A:

If you have only bounding boxes, use the function ST_MakeEnvelope. This function creates a rectangle from 4 coordinates (2 points). First split the text with string_to_array and the than use the result as coordinates:
SELECT ST_MakeEnvelope(arr[1]::double precision,
                       arr[2]::double precision,
                       arr[3]::double precision,
                       arr[4]::double precision,
                       3301)
FROM (SELECT string_to_array(geom_bbox,',') AS arr FROM mytable) as foo;


Q:

How can I get the two prices from these JComboBoxes?

I'm working on an assignment and it's been going fine but now I'm stuck. We have to make a GUI program that lets you choose 1 dorm plan and 1 meal plan. once you click the calculate button your cost per semester appears in a textfield. I'm having trouble with my ButtonListener. Here's some of what I've gotten done
private String[] dormList = { "Lincoln Suites Double: $" + LINCOLN_DOUBLE, "Washington Suites Single: $" + WASHINGTON_SINGLE,
                              "Washington Suites Double: $" + WASHINGTON_DOUBLE, "Washington Suites Triple: $" + WASHINGTON_TRIPLE,
                              "Roosevelt Suites Double: $" + ROOSEVELT_DOUBLE, "Kennedy Suites Single: $" + KENNEDY_SINGLE };

private String[] mealList = { "10 meals per week plus $200 flex dollars: $" + TEN_MEALS_200_FLEX,
                              "10 meals per week plus $350 flex dollars: $" + TEN_MEALS_350_FLEX,
                              "14 meals per week plus $400 flex dollars: $" + FOURTEEN_MEALS_400_FLEX };

I made these arrays into Combo Boxes. The all caps are my constants so I can change the price whenever I want.
private class ButtonLister implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        int total = 0;
        String dormSelection = (String) dormsComboBox.getSelectedItem();
        String mealSelection = (String) mealsComboBox.getSelectedItem();
        total =
        }
}

Would it make sense to tokenize with a delimiter of $ to get the price and add it to the total? Or might there be a way to identify which suite it is and use the constants to calculate the total?

A:

You can easily parse the money from a String as a number.
Number num = NumberFormat.getCurrencyInstance(Locale.US).parse(str);

Edit : So to format your number, retrieve the string using indexof
Number num = NumberFormat.getCurrencyInstance(Locale.US).parse(str.substring(str.indexOf("$")));


Q:

Laravel group by date in foreach not working

I have the following code:
$getDate = $messages->groupBy(function($date) {
    return Helper::ru_date('%d %b', strtotime($date->created_at->toDateString()));
});

This give me messages group by date. I get an array:
14 february => messages items
15 february => messages items
When I want do foreach and show date I get object of message. Why? I want see 14 february or 15.
My foreach:
@foreach($getDate as $date)
   {{ $date }} //I get collection of message, but not date
   @foreach($date as $message)
        //but this I need show messages of this date
   @endforeach
@endforeach

A:

If getDate is an array with the date in the keys and the messages in the values, you should adjust your loop head to:
@foreach($getDate as $date => $messages)


Q:

How the unix sed sort combine use with ruby format looks like?

*the purpose of using sed because i want to read it line by line streaming.
I have few questions about unix bash and ruby, I am really confused about the syntax of bash.If someone can offer me some examples, it really helps people to learn. Appreciate every responses.
1.let say I want to read in a server.txt on the command line, and then sort it by the server contents aplhabetically
here is how server.txt looks like

pacific
  asia
  northamerica
  america

Here what I typed
sed -e server.txt |sort| > done.txt

but it seems not working well, how to fix it?
2.And my second question is how to I combine the use of unix command and ruby script.
  like i want to stream in a file and then input line by line input to my ruby file. and then output to some files.
 I tried
sed -e server.txt ruby filter.rb > done.txt

this doesn't work too.
3.what is $stdin $stdout mean?
4.if server.txt is like 10gb which doesn't fit in memory, can we still use sort? or sort is like automatically doing the streaming and merging for us?

A:

If what you typed is precisely:
sed -e server.txt |sort| > done.txt

you should be getting a syntax error from sed complaining that the third 'e' is missing from 'server.txt' (because it will treat that as an attempt at formulating a substitute command with 'e' as the expression delimiter; the -e option means the following argument is a command expression, not a file name).
The second pipe should be omitted.  As written, you've invoked a null command that creates a file done.txt and then does nothing.  If you wanted the output written to the file, you'd need to put a cat or tee command in there.  Or, better, omit the second pipe so that sort writes to the file.

Can you give an example of how to use cat or tee to make first example work?

sed -e s/a/b/g server.txt | sort | cat > done.txt  # UUOC award
sed -e s/a/b/g server.txt | sort | tee   done.txt
sed -e s/a/b/g server.txt | sort       > done.txt  # No UUOC award
sed -e s/a/b/g server.txt | sort      -o done.txt  # No UUOC award

I've added an expression for sed so it will read the file server.txt.  UUOC is the 'Useless Use of Cat' award.  There's absolutely no need to use cat in the example.  Using tee might make sense if you're planning to read all 10 GiB of data as it scrolls past; otherwise, one of the last two options is more sensible; they're essentially equivalent in this context.
Your second command:
sed -e server.txt ruby filter.rb > done.txt

should be written as:
sed -e s/a/b/g server.txt | ruby filter.rb > done.txt

I've provided a silly action for the -e option to sed; the output of sed is piped to the ruby script, and the output is then written to done.txt.  This is a very standard sort of idiom.
Without more context, I can't tell you what $stdin and $stdout mean.  In different languages, it means slightly different things, but typically would be a reference to a variable of some sort.  I'm not sure whether any languages treat those two names as special; probably there are some, but neither Perl nor shell has a special meaning for those names.


Q:

Adding buttons for HTML elements to the Sitecore rich text editor

I would like to add a button to the Sitecore rich text editor toolbar, specifically one that inserts the H2 element.
I know the H2 element can be inserted using the paragraph styles pulldown menu, but all my editors are now using the bold button for their headings because they don't "see" the paragraph styles pulldown. So, I want to make the H2 easily available using a toolbar button. (And maybe even removing the bold buttons, since it's not semantic at all.)
But no matter how I go through the documentation, I cannot find a good explanation on how to do this.

A:

In addition to the guide Yan posted, here's another guide.


Q:

Search column of one sheet and return multiple matches from a separate sheet in CSV

I am trying to search Data!A2:A for multiple matches to Search!A2:A.  When a match is found, get the value(s) from Data!B2:B and place them in CSV format in Search!B2:B.
This QUERY works, but I would like to somehow only enter it one time at the top of the column rather than fill it down manually.  When I attempted to wrap it in ARRAYFORMULA, I simply replicated the first result down the column.
=JOIN(", ",QUERY(Data!$A$2:$B,"SELECT B WHERE A = '"&A2&"'",0))

Here is my sample spreadsheet

A:

=ARRAYFORMULA(REGEXREPLACE(TRIM(IFERROR(VLOOKUP(A2:A, {QUERY(QUERY(Data!A2:B,
 "select A,count(A) where A is not null group by A pivot B", 0), "select Col1 offset 1", 0),
 TRANSPOSE(QUERY(TRANSPOSE(IF(ISNUMBER(QUERY(QUERY(Data!A2:B,
 "select count(A) where A is not null group by A pivot B", 0), "offset 1", 0)),
 QUERY(QUERY(Data!A2:B,
 "select count(A) where A is not null group by A pivot B", 0), "limit 0", -1)&",", ))
 ,,999^99))}, 2, 0))), ",$", ))


Q:

How many combinations are possible when rolling all Platonic solid dice?

I bought a set of five platonic solid dice  and I'm wondering  how many combinations exist if you roll them all at once.  Thanks for your help
Platonic solid dice are:
4, 6, 8, 12, 20 sided

A:

$$4\times6\times8\times12\times20=46080$$
That's an application of the Rule of product.


Q:

Selenium firefox profile never ask not working

I am trying to save a csv file without the popup box. I followed the following link to figure out my mime:
http://watirmelon.com/2011/09/07/determining-file-mime-types-to-autosave-using-firefox-watir-webdriver/
I even added all the NC_values from the mimeTypes.rdf file. But, it does not seem to be working.
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'irc,ircs,webcal,application/csv,application/download,application/pdf')

mimeTypes.rdf
<RDF:RDF xmlns:NC="http://home.netscape.com/NC-rdf#"
         xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <RDF:Seq RDF:about="urn:schemes:root">
    <RDF:li RDF:resource="urn:scheme:webcal"/>
    <RDF:li RDF:resource="urn:scheme:ircs"/>
    <RDF:li RDF:resource="urn:scheme:mailto"/>
    <RDF:li RDF:resource="urn:scheme:irc"/>
  </RDF:Seq>
  <RDF:Description RDF:about="urn:scheme:mailto"
                   NC:value="mailto">
    <NC:handlerProp RDF:resource="urn:scheme:handler:mailto"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:handler:web:https://30boxes.com/external/widget?refer=ff&url=%s"
                   NC:prettyName="30 Boxes"
                   NC:uriTemplate="https://30boxes.com/external/widget?refer=ff&url=%s" />
  <RDF:Description RDF:about="urn:scheme:irc"
                   NC:value="irc">
    <NC:handlerProp RDF:resource="urn:scheme:handler:irc"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:scheme:handler:mailto"
                   NC:useSystemDefault="true"
                   NC:alwaysAsk="false">
    <NC:possibleApplication RDF:resource="urn:handler:web:https://compose.mail.yahoo.com/?To=%s"/>
    <NC:possibleApplication RDF:resource="urn:handler:web:https://mail.google.com/mail/?extsrc=mailto&url=%s"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:handler:web:https://mail.google.com/mail/?extsrc=mailto&url=%s"
                   NC:prettyName="Gmail"
                   NC:uriTemplate="https://mail.google.com/mail/?extsrc=mailto&url=%s" />
  <RDF:Description RDF:about="urn:scheme:handler:webcal"
                   NC:useSystemDefault="true"
                   NC:alwaysAsk="true">
    <NC:possibleApplication RDF:resource="urn:handler:web:https://30boxes.com/external/widget?refer=ff&url=%s"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:application/pdf"
                   NC:value="application/pdf">
    <NC:handlerProp RDF:resource="urn:mimetype:handler:application/pdf"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:scheme:ircs"
                   NC:value="ircs">
    <NC:handlerProp RDF:resource="urn:scheme:handler:ircs"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:scheme:handler:ircs"
                   NC:alwaysAsk="true">
    <NC:possibleApplication RDF:resource="urn:handler:web:https://www.mibbit.com/?url=%s"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:handler:application/download"
                   NC:alwaysAsk="true" />
  <RDF:Description RDF:about="urn:mimetype:application/csv"
                   NC:value="application/csv"
                   NC:editable="true"
                   NC:fileExtensions="csv"
                   NC:description="Microsoft Excel Comma Separated Values File">
    <NC:handlerProp RDF:resource="urn:mimetype:handler:application/csv"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:schemes">
    <NC:Protocol-Schemes RDF:resource="urn:schemes:root"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:handler:web:https://compose.mail.yahoo.com/?To=%s"
                   NC:prettyName="Yahoo! Mail"
                   NC:uriTemplate="https://compose.mail.yahoo.com/?To=%s" />
  <RDF:Description RDF:about="urn:handler:web:https://www.mibbit.com/?url=%s"
                   NC:prettyName="Mibbit"
                   NC:uriTemplate="https://www.mibbit.com/?url=%s" />
  <RDF:Seq RDF:about="urn:mimetypes:root">
    <RDF:li RDF:resource="urn:mimetype:application/pdf"/>
    <RDF:li RDF:resource="urn:mimetype:application/download"/>
    <RDF:li RDF:resource="urn:mimetype:application/csv"/>
  </RDF:Seq>
  <RDF:Description RDF:about="urn:scheme:handler:irc"
                   NC:alwaysAsk="true">
    <NC:possibleApplication RDF:resource="urn:handler:web:https://www.mibbit.com/?url=%s"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:handler:application/csv"
                   NC:alwaysAsk="true" />
  <RDF:Description RDF:about="urn:mimetypes">
    <NC:MIME-types RDF:resource="urn:mimetypes:root"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:application/download"
                   NC:value="application/download"
                   NC:editable="true"
                   NC:fileExtensions="csv"
                   NC:description="Microsoft Excel Comma Separated Values File">
    <NC:handlerProp RDF:resource="urn:mimetype:handler:application/download"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:scheme:webcal"
                   NC:value="webcal">
    <NC:handlerProp RDF:resource="urn:scheme:handler:webcal"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:handler:application/pdf"
                   NC:handleInternal="true"
                   NC:alwaysAsk="false" />
  <RDF:Description RDF:about="urn:root"
                   NC:en-US_defaultHandlersVersion="4" />
</RDF:RDF>

my full code:
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/csv,application/download')

driver = webdriver.Firefox(profile)
driver.get(url)

time.sleep(5)

driver.switch_to.frame("main")
elem = driver.find_element_by_name('username')
elem.send_keys(username)
elem = driver.find_element_by_name("password")
elem.send_keys(password)
elem.send_keys(Keys.RETURN)

driver.find_element_by_xpath(".//*[@id='wrap']/div/div/div/div/div/div/div/div/div/div/div[2]/div/div/div/div[1]/div/span/span[2]/div[2]/table/tbody/tr/td[2]").click()
time.sleep(10)
driver.find_element_by_xpath(".//*[@id='scrollable']/div/div/div[1]/ul/li[1]/ul/li[2]/a[2]").click()
time.sleep(10)

#download report
try:
    driver.switch_to.window(driver.window_handles[1])
    element = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,".//*[@id='datablock']/div[5]/div[1]/div[10]/div[12]/input")))
    driver.find_element_by_xpath(".//*[@id='datablock']/div[5]/div[1]/div[10]/div[12]/input").clear()
    driver.find_element_by_xpath(".//*[@id='datablock']/div[5]/div[1]/div[10]/div[12]/input").send_keys(fromDate)

    driver.find_element_by_xpath(".//*[@id='datablock']/div[5]/div[1]/div[10]/div[13]/input").clear()
    driver.find_element_by_xpath(".//*[@id='datablock']/div[5]/div[1]/div[10]/div[13]/input").send_keys(toDate)

    driver.find_element_by_xpath(".//*[@id='datablock']/div[1]/div[2]/a[2]").click()
    driver.find_element_by_xpath("html/body/div[8]/ul/li/span").click()
    driver.find_element_by_xpath(".//*[@id='datablock']/div[1]/div[2]/a[3]").click()
except:
        print 'error'

A:

magic Python module says it's text/plain:
>>> import magic
>>> mime = magic.Magic(mime=True)
>>> mime.from_file("report.csv")
'text/plain'

The final preference (also leaving application/csv and application/download and adding application/octet-stream and text/csv to be safe):
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/plain,text/csv,application/csv,application/download,application/octet-stream')


Q:

Trouble with quotes and optional wildcard in R, regex

Given this character vector
columnsToKeep <- c("W","L","Customer Rate", "Diff% from Base",
               "StoreOcc%", "COMPPS","Avail","Days in Unit",
               "DSRC","Rec New Price", "Rec Rate Chg",
               "intScheduledMoveOuts","TI30","BR1Yr",
               "RLMI","NM7D","Last Rate Change %", "Occ%",
               "Last Rate Change Amt", "BR", "MoveInRate",
               "newRate",
               "lengthOfStay", "mnyRentAtMoveIn",
               "rentPriorToRateChange","mnyRentAtMoveOut","status")

I attempt this code
d<-columnsToKeep[grepl(" ", columnsToKeep)]

cat(gsub("(\\%?\\w+\\s+\\w+\\s*\\w*)", '`\\1`+', d))

which produces
`Customer Rate`+ Diff% `from Base`+ `Days in Unit`+ `Rec New Price`+ `Rec Rate Chg`+ `Last Rate Change`+ % `Last Rate Change`+ Amt

but I want this
`Customer Rate`+ `Diff% from Base`+ `Days in Unit`+ `Rec New Price`+ `Rec Rate Chg`+ `Last Rate Change %` + `Last Rate Change Amt`

Clearly I am having a hard time providing the correct regex for the % sign.

A:

I am not so sure what you are trying to do with your regular expression, but it looks like you want to put backticks around each name in d and then join them with +.  Two ways to get that are:
cat(sapply(d, function(s) { paste0("`", s, "`") }), sep="+ ")

And
cat(gsub("$", "`", gsub("^", "`", d)), sep="+ ")


Q:

Is it possible to resize all images on a page to a specific size?

I am creating an email flyer and I have multiple images that I want at 140px by 140px but some are originally 300x300 or 400x400. I don't want to go resize each image as there can be quite a few and the flyer will be a weekly update so is it possible to use CSS to tell all images (or images that have classes) to resize to 140px?
I was going to post some code but it's quite a vague request so there no relevant code I can show to help my question.
maybe if I ... and then give the span a class, would it be possible this way?

A:

if your markup is for a newsletter you may force dimensions both with style attribute and with inline width and height attribute, e.g.

but, anyway, I strongly suggest to perform some kind of batch task for automatic resize of the images (e.g. using GruntJS), so you could save some precious bandwidth on the server in which you store your static assets. (conversely, if you embed images into the email, users will appreciate a lighter size)


Q:

How to insert multiple inputs from an ArrayList loop using a Servlet

In the below code I wish to ask the user to select at least 1 of the check boxes and then take that input along with the entered product_id and insert them into two different tables. so the problem am having is with passing multiple component_id's from the view/jsp page and the query statement in the servlet
<%
  List<Component> components = new ArrayList<Component>();
  components = ComponentDb.selectComponents();
  for (Component component : components) {
   %>

   <input type="checkbox" name="component_id" value="
   <%=component.getId()%>" required="required"><%=component.getName()%>
   //here i have the end of form and stuff i doubt its necessary

and my servlet is(as far as this is concerned)
String query = "insert into Product
(product_id,product_name,product_description,product_price) VALUES
('"+product_id+"','"+product_name+"','"+product_description+"','"+product_price+"');"+
            "insert into PC(product_id,component_id) VALUES
("+product_id+","+component_id+")";
  //kinda puzzled here on how to pass the values seperately
    try {
        ps = connection.prepareStatement(query);
        int a = ps.executeUpdate(query);

Thank you

A:

Create two statements to execute INSERT statement one after one.
String query = "insert into Product (product_id,product_name,product_description,product_price) VALUES (?,?,?,?)";
ps=connection.prepareStatement(query);
ps.setInt(1,product_id);
...
ps.executeUpdate();

query="insert into PC(product_id,component_id) VALUES (?,?)";
ps=connection.prepareStatement(query);
String []component_ids=request.getParameterValues("component_id");
for(String componentID: components_ids){
   ps.setString(1,product_id);
   ps.setString(2,componentID);
   ps.executeUpdate();
}


Q:

JSP session memory?

I need to confirm a theory.  I'm learning JSP/Java.
After looking at an existing application (I didn't write), I noticed something that I think is causing our performance problem.  Or at least some of it.
It works like this:
1) user opens search page.
2) search page (by default) brings down ALL ROWS. 329,000 of them.  Yes. 329K. Into an ArrayList.  Each item in the ArrayList is a custom JavaBean tied to the DB table.
3) The ArrayList is then passed to a PaginateResultSet.
4) PaginateResultSet (prs) (329k rows) is then stored in a session variable:
session.setAttribute("resultSet", prs);
5) Each additional "Next Page" then grabs 20 rows from the getAttribute("resultSet") and sends to Ext data grid.
OK, now, am I wrong in thinking that giant result set is stored in the SERVER's memory for each thread of each user?  So if that result set takes up 20 megs of ram, and we have 20 concurrent users, we now have 400 megs taken from the server?
Isn't it a bad idea to pass THAT much data in session attributes?
Thanks for any pointers.

A:

It is certainly a bad idea to duplicate the entire DB table contents into Java's memory, let alone in an user session in a multiuser environment.
You need to paginate at the DB level and store only the rows of interest in the request scope. How exactly to do this depends on the DB interface and the DB used. If you're using basic JDBC, you may find this answer useful. For core Hibernate or JPA, see this answer.


Q:

Oracle, trigger to control link between tables

I need to create a trigger to control a link between tables. I have the following table structure (image below). an item is linked to a budget and a structure, and this structure should be linked to the same budget.
Sometimes the item receive wrong structures, receive structures different from its own budget budget. I need that when you insert a budget item or edit a budget item to be validated if the id_budget are equal, the id_budget of dg_budget_item is equal to the id_budget dg_budget_structure to which it is being linked

I started building this trigger, but do not know how to continue
CREATE TRIGGER T_BUDGETO_STRUCTURE_ITEM_ID_STRUCTURE
  BEFORE INSERT OR UPDATE OF id_budget_structure ON dg_budget_structure_item
  select id_budget from dg_budget_structure where id_budget_structure = new.id_budget_structure
  FOR EACH ROW
     WHEN (new.id_budget <> ???(result of select?))
  pl/sql_block

A:

This should get you close to what you want
CREATE OR REPLACE TRIGGER T_BUDGET_STRUCTURE_ITEM_ID_STRUCTURE
   BEFORE INSERT OR UPDATE OF id_budget_structure ON dg_budget_item
   FOR EACH ROW
DECLARE
   v_id_budget_structure   NUMBER;
   Budgets_do_not_match    EXCEPTION;
   v_code                  NUMBER;
   v_errm                  VARCHAR2(64);
BEGIN
   SELECT id_budget INTO v_id_budget_structure FROM dg_budget_structure WHERE id_budget_structure = :new.id_budget_structure
   IF :new.id_budget <> v_id_budget_structure THEN
      RAISE Budgets_do_not_match;
   END IF;
EXCEPTION
   WHEN Budgets_do_not_match THEN
      Raise_application_error (-20001,
         'Budget '||TO_CHAR(:new.id_budget)||' for structure '
         || :new.id_budget_structure || 'does not match the budget trying to be linked';
   WHEN NO_DATA_FOUND THEN
      Raise_application_error(-20002,
         'Invalid budget structure ' ||:new.id_budget_structure);
   WHEN OTHERS THEN
      v_code := SQLCODE;
      v_errm := SUBSTR(SQLERRM, 1 , 64);
      Raise_application_error(-20000,
         'Unexpected error ' || v_code  ': ' || v_errm;
END;

You cannot ROLLBACK within a trigger so your application will need to deal with that.


Q:

DoCmd.TransferSpreadsheet Export: Let user choose save destination?

I successfully run TransferSpreadsheet to export an Access query to an Excel file at a specified location:
Private Sub cmdExportQuery_Click()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
"\\company.com\root\share\public\D2S\D2S\D2S_Scorecard\Trend OT.xls"
End Sub

Given that this is a shared file, I want a dialog to open that allows the user to select whatever save destination he chooses.  I found this link with a good solution that references this article.  When I plug this code into my window:
Private Sub cmdExportQuery_Click()
Dim strSaveAsFilter As String
Dim strSaveAsFileName As String
strFilter = ahtAddFilterItem(strSaveAsFilter, "Excel Files (*.xls)", "*.xls")
strSaveAsFileName = ahtCommonFileOpenSave( _
OpenFile:=False, _
Filter:=strSaveAsFilter, _
Flags:=ahtOFN_OVERWRITEPROMPT Or ahtOFN_READONLY)

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
strSaveAsFileName, , "-1", True
End Sub

I get the error Compile Error: Sub or Function not defined, it highlights ahtAddFilterItem in blue, and highlights Private Sub cmdExportQuery_Click() in yellow with a yellow arrow.  I tried making a Public Sub, but nothing happened when I clicked the button.  What must I do to allow the user to choose the save destination when exporting this query to Excel?

A:

There is additional code that should have also been included.  Check here:
http://access.mvps.org/access/api/api0001.htm
I also found this which may be helpful from someone else who had the same error:
"Did you also get the additional code mentioned in the NOTE
Note: This code still requires the GetOpenFileName routine provided by Ken
Getz. Make sure you copy the function from this article.
which sends you to
http://www.mvps.org/access/api/api0001.htm"


Q:

Making an efficient constant current source

I need help making an efficient constant current driver.
I want to power my home with LED light strips for lighting and decorative purposes. I need to be able to turn each strip on and off individually.
I need 31 small strips in total. Each strip will have 8 LEDs in series. I want to run each strip at 21.04 volts, 55mA.
The best idea I have so far is a 24v constant voltage power supply and having a simple constant current circuit before each light strip as follows:
https://drive.google.com/file/d/1tjypDpxaherSxHHoGxFWdlf8oasYxr5i/view?usp=drivesdk
Or a variation of the constant current circuit as follows:
How can I efficiently drive an LED?
https://www.instructables.com/id/Circuits-for-using-High-Power-LED-s/
https://www.radio-electronics.com/info/circuits/transistor/active-constant-current-source.php
https://www.electronics-notes.com/articles/analogue_circuits/transistor/active-constant-current-source.php
I don't quiet understand the advantage of adding a second transistor or using multiple zener diodes and I need your help to decide on a circuit. I know its got something to do with temperature stability and/or stabilising variation in current. I'll also need help picking out the transistors as I'm not quiet sure how to pick the most efficient one.
Unless there is an alternative way that you guys recommend that would be cheaper or more efficient?
Should I try to arrange my LEDs differently?
I need the constant current circuit to be on the cheap side as I'll need 31 of them so buck convertors/expensive ICs might be out of the question.
Thanks in advance

A:

I suspect you're overthinking your problem. Maybe not, but probably.
There are two questions you need to ask:
1) How stable is your 24 volt supply?
2) How precisely do you need to control your LED current?
You specify 21.04 volts and 55 mA for your LED string. First off, using 4 significant figures for LED voltage shows that you don't really understand the variability of LEDs. Second, since you are looking at using these LEDs for "illumination and decorative purposes", I suggest that controlling current to more than 10% is a big waste of time. You simply won't be able to see smaller differences. For some reason you seem to have settled on a forward voltage of 2.63 volts for your LEDs. This will change with, among other things, LED temperature, and you are assuming a stability which simply won't occur.
So, what I'd do is the simplest possible circuit:

simulate this circuit – Schematic created using CircuitLab
The resistor should be a 1/4 watt unit, with some airflow to cool it. Don't pack all 31 units into a tiny sealed box. If you do, since they dissipate a total of about 5 watts, they'll get hot and either fail or burn something.
You will encounter statements about how switching regulators are preferred for LED control due to their better efficiency. That's true in general, but it's not much of an issue here. A simple resistor in this case will have an efficiency of about 87% (21/24) and that is right up there with switchers. Plus, this circuit is the ultimate in simplicity and low cost, both of which I suspect are good things for a first project. So don't sweat it.
Look - you plan on doing this, right? So you'll need to buy the LEDs no matter what controller you use. Buy the LEDs and a few resistors, then make a preliminary, simple version. Try it. If that is satisfactory, there is no need to get more complicated.


Q:

Pandas: How to group (and sum) by category and retain information from subcategory

This is a follow-up question to Pandas: How to subset (and sum) top N observations within subcategories? There it was demonstrated how you could find the sum of the top 3 months for each year in this dataframe:
Example dataframe
    year      month   passengers
0    1949    January         112
1    1949   February         118
2    1949      March         132
3    1949      April         129
4    1949        May         121
5    1949       June         135
.
.
.
137  1960       June         535
138  1960       July         622
139  1960     August         606
140  1960  September         508
141  1960    October         461
142  1960   November         390
143  1960   December         432

So that you'd end up with this:
    year  passengers
0   1949         432
1   1950         498
2   1951         582
3   1952         690
4   1953         779
5   1954         859
6   1955        1026
7   1956        1192
8   1957        1354
9   1958        1431
10  1959        1579
11  1960         176

The number 432 for 1949 is the sum of 148+148+136 for the months July, August and September.
My question now is this:
Is it possible to do the same calculations, and at the same time keep the corresponding subcategories as a list in it's own column?
Desired output
(I've only checked the actual sum for 1949. 1950 is made up):
        year  passengers  months
    0   1949         432  July, August, September
    1   1950         498  August, September, December
    2   1951         582  .
    3   1952         690  .
    4   1953         779  .
    5   1954         859  .
    6   1955        1026  .
    7   1956        1192  .
    8   1957        1354  .
    9   1958        1431  .
    10  1959        1579  .
    11  1960         176  .

Reproducible code and data:
import pandas as pd
import seaborn as sns
df = sns.load_dataset('flights')
print(df.head())

df2 = df.groupby('year')['passengers'].apply(lambda x: x.nlargest(3).sum()).reset_index()
print(df2.head())

df:
   year     month  passengers
0  1949   January         112
1  1949  February         118
2  1949     March         132
3  1949     April         129
4  1949       May         121

df2:
   year  passengers
0  1949         432
1  1950         498
2  1951         582
3  1952         690
4  1953         779

Thank you for any suggestions!

A:

Use  custom function with GroupBy.apply, idea is sorting first by sort_values and then call head for top values per groups:
def f(x):
    x = x.head(3)
    names = ['passengers','months']
    return pd.Series([x['passengers'].sum(), ', '.join(x['month'])], index=names)

df2 = df.sort_values('passengers', ascending=False).groupby('year').apply(f).reset_index()
print(df2.head())
   year  passengers                   months
0  1949         432  July, August, September
1  1950         498  July, August, September
2  1951         582  July, August, September
3  1952         690       August, July, June
4  1953         779       August, July, June

A:

Alternatively - group, then apply using pd.DataFrame.nlargest instead of a custom function/lambda then regroup on the index and apply suitable aggs, eg:
new_df = (
    df.groupby('year').apply(pd.DataFrame.nlargest, 3, 'passengers')
    .groupby(level=0).agg({'passengers': 'sum', 'month': ', '.join})
    # optionally reset index
    # .reset_index()
)

That'll then give you:
      passengers                    month
year
1949         432  July, August, September
1950         498  July, August, September
1951         582  July, August, September
1952         690       August, July, June
1953         779       August, July, June
1954         859       July, August, June
...

Seems that year as an index makes sense in the resultant frame, but apply a .reset_index() if not.


Q:

GIMP: increase transparency with the distance from image's center

I want to apply a transformation on my image which will cause that:

Image will be at zero transparency in its center
With increasing horizontal distance from the center the image will smoothly become more and more transparent
In the edges the image will be fully transparent

Is there any function in GIMP which can do this?

A:

What you want is a gradient. Read more about Gradients in the GIMP User Manual. Below is how you can accomplish what you describe.

Add a layer mask

Do this by right-clicking the layer, then Add Layer Mask. Use "White (full opacity)"

Select the Gradient took (shortcut L)
In the tool options, change the shape to "Radial"
In the tool options, click the <-> button next to "Gradient". If you don't, you'll have a transparent center and gets more solid as you go out.
Click and drag from the center of the image to the edge.


Q:

Create a table with mysqli prepared statment

`I have the simple this very simple code below:
        $sql = "SELECT * FROM `alerte`";
    $result = $mysqli->query($sql);

if ($result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {
        echo "
";
        echo "" . $row['nom_alerte'] . "	";
        echo "" . $row['id_priorite'] . "	";
        echo "
";
    }

}

I would like to use a prepared statement but I am not sure how.
$stmt = $mysqli -> prepare("SELECT *
                                FROM `alerte`
                                WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

while ($row = $stmt->fetch()) {
    echo "
";
    echo "" . $row['nom_alerte'] . "	";
    echo "" . $row['id_priorite'] . "	";
    echo "
"; }

Can someone point me in the right direction?
solution, thanks for the comment! :
    $id_alerte = '5';
$stmt = $mysqli -> prepare("SELECT  `nom_alerte`,
                                `id_priorite`
                            FROM `alerte`
                            WHERE `id_alerte` < ?");
$stmt->bind_param('i', $id_alerte);
$stmt->execute();

$stmt->bind_result($nom_alerte, $date_debut_alerte, $date_fin_alerte,      $description_alerte, $status, $id_equipe, $id_priorite);

while ($stmt->fetch()) {
echo "
";
    echo "" . $nom_alerte . "	";
    echo "" . $id_priorite . "	";
echo "
";
}

A:

There are two ways, if mysqlnd is installed on your system, you could use ->get_result() method
Or use ->bind_result() if not available to fetch your results from the prepared statement:
->get_result() version:
$stmt = $mysqli->prepare("SELECT * FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

$results = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
    echo "
";
        echo "" . $row['nom_alerte'] . "	";
        echo "" . $row['id_priorite'] . "	";
    echo "
";
}

Or the bind_result() version:
$stmt = $mysqli->prepare("SELECT `nom_alerte`, `id_priorite` FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

$stmt->bind_result($nom_alerte, $id_priorite);
while ($stmt->fetch()) {
    echo "
";
        echo "" . $nom_alerte . "	";
        echo "" . $id_priorite . "	";
    echo "
";
}


Q:

CUPS print file segmentation fault

I am trying to make a CUPS print system. I want to get printer status, how many pages printed sofar etc.
To do that, I am executing example programs given in CUPS examples.
#include <cups/cups.h>
#include <stdio.h>

int main(){

int num_options;
cups_option_t *options;

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options);

cupsFreeDests(num_dests, dests);

return 0;
}

I compile it using    gcc myfile.c -o myout -lcups
When I try to execute ./myout
I am getting

Segmentation fault

I am using Raspberry-pi 3 board as my CUPS server.
Thanks in advance.

A:

dest is pointing to non-valid address.
cups_dest_t *dest; // declared but not initialized or assigned afterwards

So dereferencing it ( cupsPrintFile(dest->name... ) is UB and can cause SegFault.

This is how you should have used it (taken from here):
#include <cups/cups.h>

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);

/* do something with dest */

cupsFreeDests(num_dests, dests);

Update:
Your code doesn't handle some of the variables (i.e. leaves them uninitialized - bad). The first one I see is cups_option_t *options;. Take care of all of your variables, and if that's not working - debug.
int main(){

int num_options;
cups_option_t *options; // add a call to "cupsAddOption("first", "value", num_options, &options);"

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options); // options is used here but is uninitialized

cupsFreeDests(num_dests, dests);

return 0;
}


Q:

Why does this render an empty plot?

I would like to know why this python code:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.arange(-3,3,100)
y = -(np.arctan(-1/x))
plt.ylim((-1.5,1.5))
plt.plot(x,y)
plt.show()

renders an empty plot, with the axes having my desired limits. Wolfram Alpha assures me that the function should be visible within these limits.
I am completely lost here.

A:

Your range contains only a single point x = [-3], hence you won't plot much.
What you want is to create a linear space using
x = np.linspace(-3,3,100)

Then your function will be visible.
Edit: Explanation of the first sentence:
np.arange(start, stop, step)

This will create a range starting at start, stopping at stop (exclusive) and stepping by step. Thus you start with -3, the next value must be at stride -3 + 100 = 97, but this is not smaller than 3. Thus the range only contains the start number.
np.linspace(start, stop, number) instead will create a range in the interval [start,stop] divided equidistant in number partitions.


Q:

Trying to use CoffeeScript with JQuery, I get a "document is not defined" error

I start like I usually do in javascript, so:
$(document).ready ->

but when I save I get a document is not defined. So far I haven't been able to find how to make it work.
Edit: by save, I meant I was using coffee -w. The error was due to me forgetting to use the -c option.

A:

CoffeeScript is compiled into JavaScript. I'm not sure what you're trying, but in your exact case your CoffeeScript isn't going to look a whole lot different than your JavaScript. Try:
$(document).ready -> alert 'blah'

If that doesn't work, just do a test like
alert document.title

if that doesn't work, I'm going to suggest that you're not running this code inside a browser ;)


Q:

How to use CASE in SQL for different conditions

I am trying to use conditions with case in sql but not getting any proper solution,
Here is my Query :
select users.id
     , friends.user_id
     , friends.friend_id
     , CASE WHEN friends.accept IS NULL THEN  10
             WHEN friends.friend_id = 18 THEN friends.accept = 11
             else friends.accept = Same
END AS friend_status
from users
  left
  join friends
    on users.id = friends.friend_id
 where users.id != 18
 order
    by id asc

I just want that,

WHEN friends.accept IS NULL THEN  10
WHEN friends.friend_id = 18 THEN friends.accept = 11
else friends.accept = Same as in table

Is it possible, If possible Please help me out

A:

Is this what you are trying to do?
select users.id, friends.user_id, friends.friend_id,
CASE
WHEN friends.accept IS NULL THEN 10
WHEN friends.friend_id = 18 THEN 11
ELSE friends.accept
END AS friend_status
from users left join friends on users.id = friends.friend_id where users.id != 18 order by id asc


Q:

PowerShell Module Manifest - automatically loading a Required Module

I am creating a module that depends on several other modules that I need loaded into the global environment. I tried creating a script and using ScriptsToProcess to import the modules, but it looks like the check for RequiredModules happens before ScriptstoProcess runs.
Is there a nice, clean way in a Module Manifest to both Require a module and load it automatically if its not already loaded? If the module could not be loaded, then the RequiredModule would throw an error.

A:

PowerShell V3 works somewhat differently. Required modules are now loaded when you load a manifest with that key specified. Also, removing the module does not unload the required module, no matter how that module was loaded. Interestingly, -Force does not seem to show the autoloading of the required module(s).

Edit: If your module is not in one of the default locations, you will need to add the path to that module (or the parent folder under which the module resides) to the $env:PSModulePath variable.

Side note: since PSv3 there is support for the #Requires command in scripts. You can use this to (1) attempt to load a module dependency in your script and (2) terminate if the module is not/cannot be loaded.
#Requires -Modules ModuleName1,ModuleName2

This also needs the modules to be somewhere under $env:PSModulePath, which must be set before running the script.

about_Requires

A:

In PowerShell 3 and up, RequiredModules are automatically loaded
It's also the only way to make sure people using PowerShellGet (i.e. the PowerShell Gallery) install your dependencies, if you're going to distribute the module.
It would still fail if the required modules are missing, but otherwise works exactly the way you'd wish it to.
In PowerShell 2, there's no way to automatically load RequiredModules
In either case, users can manually load the requirements by typing Import-Module RequiredModule, YourModule -- they won't get a second instance if it's already imported ...
You can also specify the module in NestedModules instead. Even in PowerShell 2, those get loaded "inside" your module, but don't seem to negatively affect resources when they're already loaded. However, as @JasonMArcher reminded me, in PowerShell 2, NestedModules get unloaded along with your module if your module gets unloaded (via Remove-Module), and this happens even if they were pre-loaded separately by the user, which can end up producing really weird bug reports since your users won't expect that.
The other option, which works in all versions of PowerShell, is to call Import-Module at the top of your module (in a psm1 script, after checking to make sure the module's not already loaded) with the -ErrorAction Stop set so that the import of your module will fail if the import of the dependent module fails.
if (!(Get-Module Dependency)) { ## Or check for the cmdlets you need
    ## Load it nested, and we'll automatically remove it during clean up
    Import-Module Dependency -ErrorAction Stop
}

Actually, if you wanted to check for versions ...
if (!(Get-Module Dependency | Where { $_.Version -ge "2.5" )) {
    ## Load version 2.5 (or newer), or die
    Import-Module Dependency -Version 2.5 -ErrorAction Stop
}

Just remember that this doesn't serve as documentation, so if you distribute the module, your users will not know about the dependencies.