text:
Q: Parsing a difficult sentence I'm having trouble understanding this sentence from a book on system theory, which reads like a modern version of Euclid's Elements:

Intuitively, we would expect the concept of a system to involve some
  kind of inter-relation between the percepts it generates, and which
  then become identified with corresponding relationships between the
  external qualities which generated them.

The idiomatic construction would be "inter-relation between x and y" but the meaning of "inter-relation between the percepts" seems to be "a set of relations among a set of percepts" because there is no noun y to follow. Here is my attempt at a paraphrase, with parentheses to identify nouns:
The concept of a system involves
(a set S of
  (relations among
    (a set of
      (percepts generated by the system))))
such that S becomes "identified with"
(a set of
  (relations among
    (a set of
      (external qualities generated the percepts)))).
Does this seem right?

A:
The idiomatic construction would be "inter-relation between x and y"
  but the meaning of "inter-relation between the percepts" seems to be
  "a set of relations among a set of percepts" because there is no noun
  y to follow.

X and Y are, in this case, combined into a single plural term (since there's no natural way to distinguish between percepts in this kind of general statement).
This is a very awkwardly constructed sentence.


text:
Q: Chmod: Execute only if the file is a directory I understand that chmod -R u=rwX,g=rwX,o=r will set directory, subdirectories and files with the caveat:

The capital X permission option tells chmod to grant execute access only if it makes sense -- if the item is a directory, or already has at least one execute access enabled (i.e. if it appears to be an executable file).

But is there a way to force chmod (in a similar fashion) to only affect directories, leaving all files as-is?
— Source

A: find my/path -type d -exec chmod u=rwX,g=rwX,o=r {} \;
        +          +   +     +   +------+------+ +   +
        |          |   |     |          |        |   +-> semicolon needed by -exec and escaped to avoid shell expansion
        |          |   |     |          |        +-----> current directory entry returned by find
        |          |   |     |          +--------------> your chmod options
        |          |   |     +-------------------------> the shell command you want to execute on each directory entry
        |          |   +-------------------------------> need to execute a command for each entry returned by find
        |          +-----------------------------------> look for directories only (not files/symlinks/etc)
        +----------------------------------------------> the path to look for entries in

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse Youtube XML I'm using a basic method to parse some Youtube XML data:
This is a sample XML file from Youtube: http://jimpix.co.uk/youtube.xml
I saved it as XML as the XML file is a lot easier to see than the standard Youtube version from Youtube (see here)
This is the basic code I'm using to extract the video ID and Title:
Dim vurl = "http://jimpix.co.uk/youtube.xml"
Set http = Server.CreateObject("msxml2.ServerXMLHTTP")
http.Open "GET", vurl, False
http.Send

Set dom = http.responseXML
Set items = dom.getElementsByTagName("entry")

For Each item In items

Set id = item.getElementsByTagName("name")
If NOT (id IS Nothing) Then
    var_id = id(0).Text
End If

response.write "
var_id: "&var_id&"
"

Set title = item.getElementsByTagName("title")
If NOT (title IS Nothing) Then
    var_title = title(0).Text
End If

response.write "
var_title: "&var_title&"
"
Next

I'm stuck trying to get at the video duration, thumbnail and number of plays, as they are not held in simple tags like the ID and title.
For example, ID and title go like this:
<entry...>
    <id>http://gdata.youtube.com/feeds/api/videos/9TN3VtWwks4</id>
    ...
    <title type="text">
    Sign Language - Multi-Award Winning short film - Director's Cut
    </title>
</entry>

But the duration, thumbnail and number of plays are harder to get at:
<entry...>
    <media:group>
        <media:thumbnail url="http://i.ytimg.com/vi/9TN3VtWwks4/0.jpg" height="360" width="480" time="00:02:28.500"/>
        <yt:duration seconds="297"/>
        <yt:statistics favoriteCount="0" viewCount="198826"/>
    </media:group>
</entry>

I wondered if I could ask for advice please about how to extract these 3 variables from the XML?

A: you can get the thumbnails like :
<%
    set thumbnails = dom.getElementsByTagName("entry/media:group/media:thumbnail")

    if not(thumbnails is Nothing) then
    for each pic in thumbnails
        Response.write "
thumbnail: "&pic.getAttribute("url")&"
"
    next
    end if
%>


text:
Q: uibutton is not getting displayed I am trying to add uibutton inside the imageview.
But it was not displayed the button.
Even i tried adding it to the uiscrollview and also for self.view.
But nothing were displayed the uibutton
Pls let me know what is the problem
const CGFloat HEIGHT = 1024.0;
    const CGFloat WIDTH = 768.0;
    #define myViewPortrait CGRectMake(0.0f, 0.0f, 768.0f,1024.0f)
    #define myViewLandSacpe CGRectMake(0.0f, 0.0f, 1024.0f,768.0f)

    #define kAnimationKey @"animationKey"

    -(void)layoutScrollImages
    {
      UIImageView *view = nil;
      NSArray *subviews = [myScrollView subviews];

      CGFloat curXLoc = 0;
      for (view in subviews)
      {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
          CGRect frame = view.frame;
          frame.origin = CGPointMake(curXLoc, 0);
          view.frame = frame;

          curXLoc += (self.view.frame.size.width);
        }
      }

      [myScrollView setContentSize:CGSizeMake((myImagesCount * self.view.frame.size.width), [myScrollView bounds].size.height)];
    }

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {

      self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
      myScrollView = [[UIScrollView alloc] initWithFrame:
      CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

      [self.view addSubview:myScrollView];

      UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
      rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
      rightRecognizer.numberOfTouchesRequired = 1;
      [rightRecognizer setDelegate:self];
      [myScrollView addGestureRecognizer:rightRecognizer];
      [rightRecognizer release];

      UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeHandle:)];
      leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
      leftRecognizer.numberOfTouchesRequired = 1;
      [leftRecognizer setDelegate:self];
      [myScrollView addGestureRecognizer:leftRecognizer];
      [leftRecognizer release];

      [myScrollView setBackgroundColor:[UIColor blackColor]];
      [myScrollView setCanCancelContentTouches:NO];
      myScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
      myScrollView.clipsToBounds = YES;
      myScrollView.scrollEnabled = YES;
      myScrollView.pagingEnabled = YES;
      myScrollView.delegate = self;
      myImagesCount = 5;
      myScrollView.showsHorizontalScrollIndicator=NO;
      myScrollView.showsVerticalScrollIndicator=NO;

      for (int i = 1; i <= myImagesCount; i++)
      {
        NSString *imageName = [NSString stringWithFormat:@"screen-%d.jpg", i];
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        CGRect rect = imageView.frame;
        rect.size.height = myScrollView.frame.size.height;
          NSLog(@"%d -----",self.view.frame.size.width);
        rect.size.width = myScrollView.frame.size.width;
        imageView.frame = rect;
        imageView.tag = i;
        [myScrollView addSubview:imageView];
        [imageView release];
      }
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
    [button setTitle:@"point" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.0, 0.0, 100.0, 40.0);
    button.backgroundColor = [UIColor blackColor];
    [self.view addSubview:button];
      [self layoutScrollImages];

      [super viewDidLoad];

    }

A: Try this
Declare button globally and set
[self layoutScrollImages];

[self.view bringSubViewToFront:button];

A: Based off your question, you'd like to add the UIButton as a subview to the UIImageView - I'm guessing in the for loop? Immediate problem I see is that the actual button is being generated outside of the for loop. I think your for loop is intended to look like this:
for (int i = 1; i <= myImagesCount; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"screen-%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(buttonHandler)  forControlEvents:UIControlEventAllEvents];
    [button setTitle:@"point" forState:UIControlStateNormal];
    button.frame = CGRectMake(0.0, 0.0, 100.0, 40.0);
    button.backgroundColor = [UIColor blackColor];

    CGRect rect = imageView.frame;
    rect.size.height = myScrollView.frame.size.height;
    NSLog(@"%d -----",self.view.frame.size.width);
    rect.size.width = myScrollView.frame.size.width;
    imageView.frame = rect;
    imageView.tag = i;

    [imageView addSubview:button];
    [myScrollView addSubview:imageView];
    [imageView release];
}


text:
Q: Jest SyntaxError: Cannot use import statement outside a module I am getting the error above when trying to require a file that has import statements. I tried the answers on simular questers to resolve it. It can now read almost all the imports, except for two.
To resolve the first import errors I have made the following files:
babel.config.js:
module.exports = {presets: ['@babel/preset-env']}

jest.config.js:
module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    "^.+\\.(js|jsx)$": "babel-jest",
  }
};

.babelrc:
{
  "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript",[
    "next/babel",
    {
      "preset-env": {
        "modules": "commonjs"
      }
    }
  ]
]
}

Does anyone have any idea what I can change so it can succesfully read the last two import modules as well?
Edit: devdependencies:
"devDependencies": {
    "@babel/plugin-transform-runtime": "^7.16.0",
    "@babel/preset-env": "^7.16.0",
    "@babel/preset-react": "^7.16.0",
    "@rescripts/cli": "0.0.16",
    "@types/deep-equal": "^1.0.1",
    "@types/history": "^4.7.9",
    "@types/jest": "^27.0.2",
    "@types/node": "^12.20.19",
    "@types/react": "^16.14.11",
    "@types/react-dom": "^16.9.14",
    "@types/react-redux": "^7.1.18",
    "@types/react-router": "^5.1.16",
    "@types/react-router-dom": "^5.1.8",
    "@types/reactstrap": "^8.7.2",
    "@types/redux": "^3.6.0",
    "@types/redux-logger": "^3.0.9",
    "@types/underscore": "^1.11.3",
    "babel-jest": "^27.3.1",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "bootstrap-scss": "^4.6.0",
    "env-cmd": "^10.1.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "enzyme-to-json": "^3.6.2",
    "jest": "^27.3.1",
    "node-sass": "^4.14.1",
    "react-dev-utils": "^10.2.1",
    "redux-logger": "^3.0.6",
    "rollup": "^1.32.1",
    "sass": "^1.37.5",
    "ts-jest": "^27.0.7",
    "typescript": "^3.9.10"
},

Edit: updates the types/jest package


text:
Q: Use blocks from included files for parent in jinja2 I'm not sure if what I want to do is possible: I'm trying to get a block in a parent template to be filled out by a file included in a child template of the parent.
The best way to explain this is a test case:
File t1.djhtml:
<root>
    <block t3_container>
        {% block t3 %}This should be 'CONTENT'{% endblock %}
    </block t3_container>

    <block t2_container>
    {% block t2 %}{% endblock %}
    </block t2_container>
</root>

File t2.djhtml:
{% extends 't1.djhtml' %}

{% block t2 %}
        <block t2>
            {%- include 't3.djhtml' with context %}
        </block t2>
{% endblock %}

File t3.djhtml:
{% block t3 %}
        <block t3>
            CONTENT
        </block t3>
{% endblock %}

File test.py:
from jinja2 import Environment, FileSystemLoader
env  = Environment(loader=FileSystemLoader(''))
t=env.get_template('t2.djhtml')
print t.render()

The output is:
<root>
    <block t3_container>
        This should be 'CONTENT'
    </block t3_container>

    <block t2_container>

        <block t2>
        <block t3>
            CONTENT
        </block t3>

        </block t2>

    </block t2_container>
</root>

The t2 block should be empty, and t3_container should have block t3's content inside. How do I accomplish this?

A: You can use macros in the included file, but instead of including it, you import the macros with context.

T1.html
<root>
  <block t3_container>
    {% block t3 %}{% endblock %}
  </block t3_container>

  <block t2_container>
  {% block t2 %}{% endblock %}
  </block t2_container>
</root>

T2.html
{% extends 'T1.html' %}
{%- from 'T3.html' import inner, inner2 with context %}

{% block t3 %}
    {{ inner2() }}
{% endblock %}

{% block t2 %}
    <block t2>
        {{ inner() }}
    </block t2>
{% endblock %}

T3.html
{% macro inner2() %}
    <block t3>
        CONTENT '{{ foo+1 }}'
    </block t3>
{% endmacro %}

{% macro inner() %}
  hello
{% endmacro %}

test.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader("."))
t = env.get_template("T2.html")

print(t.render({"foo": 122}))


text:
Q: Copy a file to absolute path How can I tell WiX to copy a file to a specific path that is outside my applications installation path during installation?
I need to copy a file from my applications installation directory into the directory of another application, and so far I'm not able to figure out the syntax.  I know the syntax below is wrong, but this is pseudo code for what I want to do:
<CopyFile Id="MyCopyFile" SourceDirectory="..\Path\To\My\Source\File" SourceName="myfile.dat" DestinationDirectory="C:\Program Files (x86)\OtherProgram\TargetDir" DestinationName="myfile.dat"/>

This install will only run on specific machines so absolute paths are fine.


text:
Q: ios - different section with different cell.accessoryType I have table with two sections, I want first section cells to have indicator, and second section cells no indicator.
I tried this:
    if (indexPath.section==1){

             cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }else if(indexPath.section==2){

             cell.accessoryType = UITableViewCellAccessoryNone;
    }

and this:
   if(indexPath.section==1){

        switch(indexPath.row){

            default:
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

                break;

        }

    }else if(indexPath.section==2){

        switch(indexPath.row){

            default:
               cell.accessoryType = UITableViewCellAccessoryNone;

                break;

        }

    }

None worked with me, what did i do wrong?

A: The index of the first section should be 0, not 1.
The index of the second section should be 1, not 2.
Remember that in (most) programming languages we are indexing from zero.

A: do you use the same cell identifier? Did you try two different cell identifiers?
Try to use 2 different one.


text:
Q: Why does null keep coming back when getting nodeValue even though it displays properly? This is driving me nuts. I'm inserting code into a page via Ajax. After the code is inserted I am running a function to grab the text of one of the DIVs and display it in another location on the page.
Can someone tell me why I keep getting a JavaScript error saying that currentText is null, even though the text displays properly in the other location in the page??
var currentText = document.getElementById("current-text"),
updatedTextHere = document.getElementById("updated-text-here");

updatedTextHere.innerHTML = currentText.firstChild.nodeValue;

This is the code it's grabbing the text value from, which is inserted into the main page via Ajax:

January 1, 2011

UPDATE:
Here's how it looks:
getDate = function () {
    var currentText = document.getElementById("current-text"),
    updatedTextHere = document.getElementById("updated-text-here");

    updatedTextHere.innerHTML = currentText.firstChild.nodeValue;
},

htmlready = function () {
    myDiv.innerHTML = xmlRequest.responseText;
    getDate();
},

A: The issue you are having is that firstChild isn't a node of currentText. Your nodeValue doesn't have a value because it doesn't exist. You should use innerHTML or textContent instead.
Change to...
updatedTextHere.innerHTML = currentText.firstChild.textContent; // or innerHTML


text:
Q: Refreshing Android Views with Fragments is Problematic In my app, there are many views that contain a number of different fragments. For all the documentation about the vaunted lifecycle of Activities and how to hook into the various things that can happen to a view, I don't see any discussion in the documentation about views that can change based on events. So for instance, I have a view and at a certain time of day I want to hide one fragment and put another one in the view.
Getting this to work was pretty simple, however, now that I am trying to do tests of the activities, I keep getting the error:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
            at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1343)

For now, I am calling:
transaction.commitAllowingStateLoss();

but there has to be a better way. I should be able to reconfigure the fragments in the view and then refresh, having Android resave the state and thus not complain about this.. ?


text:
Q: Regex for Version number I want to select between two different types of version numbers:

*

*2014.4.5.6

*2014.4.5
(also revision part is optional)
I have a search pattern: (\d*)\.(\d*)\.(\d*)(\.(\d*))?
This finds for both 1. and 2. always five instances:

*

*2014.4.5.6 has 5 groups: 2014, 4, 5, .6, 6

*2014.4.5 has 5 groups: 2014, 4, 5, [empty], [empty]

My questions are:

*

*A) How to change my search pattern to get rid of the .6 group in 1.?

*B) How to change my search pattern to get rid of empty groups in 2.?

And all this in one regex. Is it possible? Actually, just solving question A would be enough with a search pattern that leaves 2. as it is now.

A: For (a), you can make a group (...) non-capturing by inserting ?: at the start: (?:...) or
For your example, this would give (\d*)\.(\d*)\.(\d*)(?:\.(\d*))?.
For (b), you can't get rid of the empty group, but you can check the Success property on the Group to see whether it succeeded or not.
(This should let you distinguish between e.g. ([A-Z]*) successfully matching zero letters, and ([A-Z]+)? not matching.)

A: This regex will work with any number of groups:
(\d+)(?:\.|$)

It is checking for a group of digits followed by a dot or at the end of the file.
It will return 4 matches on example 1 and 4 on example 2.
I.e. 2014.4.5.6 will capture
2014
4
5
6

A: Actually, playing around with a .NET test application, I see that this search pattern actually works for me: (\d*)\.(\d*)\.(\d*)(\.(\d*)?)?
I was previously playing in an online regex builder. I got those extra groups there. Should have maybe been using .NET test harness from the beginning.


text:
Q: Domain transfer (.com to .ca) via DNS issue The domain owner of tempotechcontrols.com updated DNS records for tempotechcontrols.com to redirect it to tempotechcontrols.ca however, it's not working for the past 2-3 days.

*

*tempotechcontrols.com is hosted on the local server of the domain owner.

*tempotechcontrols.ca is hosted on one.com hosting provider.

Any kind of help would be appreciated!
Thanks in advance!


text:
Q: MySQL ORDER BY result from sub select as INTEGER my ORDER BY (ORDER BY count_wall) ordered by as String, but i will order by as Integer:
(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (1,2,3,4)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (1,2,3,4)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall

I have tested count_wall * 1 and ABS(count_wall) or ABS() in ORDER BY clause ...nothing help, it orders by as String.
I cant understand this, because count_wall is definitive an Integer.
Perhaps someone can help me.
I have found some: ORDER BY with CASE dont work ...here the complete, dont work, code:
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_test_order_by`(p_order_by VARCHAR(20))
BEGIN
select
t.id as topic_id, t.title as topic_title, t.alias as topic_alias, t.time_create, t.is_public,
(SELECT COUNT(ec.id) FROM entry_contra ec WHERE ec.topic_id = t.id) as count_ec,
(SELECT COUNT(ep.id) FROM entry_pro ep WHERE ep.topic_id = t.id) as count_ep,
(SELECT IFNULL(count_ec,0) + IFNULL(count_ep,0)) as count_eall,

(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (SELECT ec.id FROM entry_contra ec WHERE ec.topic_id = t.id)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (SELECT ep.id FROM entry_pro ep WHERE ep.topic_id = t.id)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall
from topic t
WHERE t.is_public = 1
GROUP BY t.id
ORDER BY
    CASE p_order_by
    WHEN 'topic_alias' THEN topic_alias
    WHEN 'time_create' THEN time_create
    WHEN 'count_ec' THEN count_eall
    WHEN 'count_ep' THEN count_eall
    WHEN 'count_wc' THEN count_wall
    WHEN 'count_wp' THEN count_wall
    ELSE time_create
    END
DESC;
END

And now the code that work:
select
t.id, t.title,
(SELECT COUNT(ec.id) FROM entry_contra ec WHERE ec.topic_id = t.id) as count_ec,
(SELECT COUNT(ep.id) FROM entry_pro ep WHERE ep.topic_id = t.id) as count_ep,
(SELECT IFNULL(count_ec,0) + IFNULL(count_ep,0)) as count_eall,

(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (SELECT ec.id FROM entry_contra ec WHERE ec.topic_id = t.id)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (SELECT ep.id FROM entry_pro ep WHERE ep.topic_id = t.id)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall
from topic t
WHERE t.is_public = 1
GROUP BY t.id
ORDER BY count_wall
DESC;

...can someone explain that?


text:
Q: How to add emoji to a string then add to .ToList I'm currently trying to create a Poll command for my Discord BOT. I would like to edit the string answer and add an Emoji to the start of that answer based on the number the answer is given.
E.G the user will type ?poll "questionhere" "answer1" "answer2" - i would like to take "answer1" and change to ":one: answer1" and so on but i'm not sure how to go about doing that.
The second thing i would like some advise of if possible is how i am currently managing how many reactions get added to the message, there has got to be a better way of doing what i am doing but i am still fairly new to this and learning so any advise or recommendation on how to better structure the below would be appreciated .
//Take the string answer and split into separate strings based on text inside ""
var result = answer.Split('"').Where((x, i) => i % 2 == 1).ToList();

if (result.Count() == 2)
 {

 List<List<string>> listChunks = StaticObjects.SplitIntoChunks<string>(result, 50);

 for (int i = 0; i < listChunks.Count; i++)
  {
    listChunks = listChunks.OrderBy(x => x).ToList();
    string description = String.Join(Environment.NewLine, listChunks[i]);

  EmbedBuilder eb = new EmbedBuilder()
  {
    Title = $@":bar_chart:**{question.ToUpper()}**",
    Description = description,
    Color = new Color(0, 0, 127),
  };

var message = await ReplyAsync(embed: eb.Build());
var YourEmoji1 = new Emoji("1\u20e3");
var YourEmoji2 = new Emoji("2\u20e3");
await message.AddReactionAsync(YourEmoji1);
await message.AddReactionAsync(YourEmoji2);

currently then continues with if (result.Count() == 3)
Update
I've found a way to add the Emoji before the string however now i don't know how to pass it back to the original result
var one = "1\u20e3" + result.ElementAt(0);

Update 2
I've now managed to get this working :)
added this
if (result.Count() == 2)
  {
  var one = "1\u20e3" + " " + "-" + " " + result.ElementAt(0);
  var two = "2\u20e3" + " " + "-" + " " + result.ElementAt(1);

and changed result to one, two
string description = String.Join(Environment.NewLine, one, two);

Update 3
I've discovered you can change
var YourEmoji1 = new Emoji("1\u20e3");
var YourEmoji2 = new Emoji("2\u20e3");
await message.AddReactionAsync(YourEmoji1);
await message.AddReactionAsync(YourEmoji2);

to
await message.AddReactionAsync(new Emoji("1\u20e3"));
await message.AddReactionAsync(new Emoji("2\u20e3"));

I'm now just left with the problem of structuring this in a much more elegant way so the code isn't ridiculously long as i want to allow up to 10 answers

A: Since you've found your solution and now want to just clean up the code, I just have a suggestion for readability:
You don't need to use character codes when you declare your emojis (new Emoji("1\u20e3")). Instead, you can use the Discord emoji names, as long as you include the :s.
For example: new Emoji(":one:"), new Emoji(":two:") etc
Similarly, the following can be cleaned up
  var one = "1\u20e3" + " " + "-" + " " + result.ElementAt(0);

To this:
  var one = ":one: - " + result.ElementAt(0);

And so on.
This will not make your code work any better, however it will make it more readable.


text:
Q: Specified LocalDB instance name is invalid: Able to create migrations but not run them I created a new XAF Blazor solution and was able to run it to create the database.
I then added a database migration as per this question
However when I go to run the migration from within package manager I get
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SNI_PN11, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.
)
 ---> System.ComponentModel.Win32Exception (0x89C5011B): Unknown error (0x89c5011b)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:-1983577829,State:0,Class:20
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: SNI_PN11, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.
)

This question is not a duplicate of this question about connecting to SQL Server since the program could access the database before I created the migration.
[Update]
The code is
    using DevExpress.ExpressApp.EFCore.Updating;
    using Microsoft.EntityFrameworkCore;
    using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy;
    using DevExpress.Persistent.BaseImpl.EF;
    using DevExpress.ExpressApp.Design;
    using DevExpress.ExpressApp.EFCore.DesignTime;
    using DevExpress.Persistent.Base;
    using Microsoft.EntityFrameworkCore.Design;
    namespace ExamBuddy.Module.BusinessObjects {
        public class ExamBuddyContextInitializer : DbContextTypesInfoInitializerBase {
            protected override DbContext CreateDbContext() {
                var builder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>()
                    .UseSqlServer(@";");
                return new ExamBuddyEFCoreDbContext(builder.Options);
            }
        }
        public class ExamBuddyContextFactory : IDesignTimeDbContextFactory<ExamBuddyEFCoreDbContext>
        {
            public ExamBuddyEFCoreDbContext CreateDbContext(string[] args)
            {
                var optionsBuilder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>();
                optionsBuilder.UseSqlServer(@"Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=false;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ExamBuddy;ConnectRetryCount=0;");
                return new ExamBuddyEFCoreDbContext(optionsBuilder.Options);
            }
        }
        [TypesInfoInitializer(typeof(ExamBuddyContextInitializer))]
        public class ExamBuddyEFCoreDbContext : DbContext {
            public ExamBuddyEFCoreDbContext(DbContextOptions<ExamBuddyEFCoreDbContext> options) : base(options) {

            }
            public DbSet<ModuleInfo> ModulesInfo { get; set; }
            public DbSet<ModelDifference> ModelDifferences { get; set; }
            public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
            public DbSet<PermissionPolicyRole> Roles { get; set; }
            public DbSet<PermissionPolicyRoleBase> RolesBase { get; set; }
            public DbSet<PermissionPolicyUser> Users { get; set; }
        }

[Update]
I tried commenting out the Dev Express TypesInfoInitializer attribute
I tried adding in the following but it does not execute ( The error does not throw ) Whereas if I put an error in the IDesignTimeDbContextFactory method it will throw
public class MigrationsContextFactory : IDbContextFactory<ExamBuddyEFCoreDbContext>
{
    public ExamBuddyEFCoreDbContext CreateDbContext()
    {
        throw new Exception("In Migration Context");
        var optionsBuilder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>();
        optionsBuilder.UseSqlServer(@"Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=false;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ExamBuddy;ConnectRetryCount=0;");
        return new ExamBuddyEFCoreDbContext(optionsBuilder.Options);
    }
}

The ExamBuddyContextFactory method does execute
[Update]
When I edit the connection string to use only 1 backslash I see the following messages in Visual Studio 2019

So the migration will generate with the double backslash in the connecion string but it will not run.

A: The exception message is telling you the problem

Specified LocalDB instance name is invalid

The invalid part is double backslash in (localdb)\\mssqllocaldb inside the C# verbatim string literal
optionsBuilder.UseSqlServer(
    @"Data Source=(localdb)\\mssqllocaldb;Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=false;Initial Catalog=ExamBuddy;ConnectRetryCount=0;");
//  ^                       ^

The actual name is (localdb)\mssqllocaldb (single backslash), so either correct that, or remove verbatim string prefix @.
All these are just standard C# string rules, there is nothing special to be discussed. Then why

Able to create migrations but not run them?

It's because Add-Migration command does not try to connect to the database, and database connection is lazily initialized only when needed, hence the invalid connection string is not detected. The command still needs to create DbContext instance in order to access the model, and the context must be configured for a specific database provider type (because EF Core creates separate model for each database provider type), but other than that it has nothing to do with the actual database.
However Update-Database command apparently needs database connection, as well as the Remove-Migration command which needs to check whether the migration is already applied. That's why these commands fail while Add-Migration succeeds.
You can easily verify that by providing fake invalid connection string like
optionsBuilder.UseSqlServer("Blah")'

and observe the exact same behaviors as in the OP.


text:
Q: Existence of smooth function using Runge's theorem Let $\Omega$ be a domain in $\mathbb{C}$ and let $h\in C^{\infty}\left(\Omega\right)$. Show that there exist $u\in C^{\infty}\left(\Omega\right)$ such that $u_{z\bar z}=h$, and if $h\left(\Omega\right)\subset \mathbb{R}$ then we can choose $u:\Omega\rightarrow\mathbb{R}$.
Using Runge's theorem I can prove that there exist $f\in C^{\infty}\left(\Omega\right)$ such that $\frac{\partial f}{\partial \bar z}=g$. (If $g$ has compact support it is trivial consequence of Cauchy-Green theorem, and if $g$ is unrestricted then we can construct sets as in proof of Mittag-Leffler theorem and use Runge's theorem). $(\star)$
How construct $u$ ? Is it a good idea to use $(\star)$ ?

A: Yes, it is a good idea to use $(\star)$ !
a) Using $(\star)$, choose $H\in C^{\infty}(\Omega)$  such that $H_{\bar z}=h$ and then using $(\star)$ again choose $U\in C^{\infty}(\Omega)$ such that $U_{\bar z}=\bar H$.
Then $\bar U_{z}= H$ and thus $\bar U_{z\bar z }= H_{\bar z}=h$ , so that for the required function you may take  $u=\bar U$ which indeed satisfies $u_{z\bar z }= h$.
b) The above solution is of course completely valid if  $h$ is real valued ($h(\Omega)\subset \mathbb R$), but if you insist on  a real valued solution, just replace $u$ by $v=\frac {u+\bar u}{2}: \Omega \to \mathbb R$ which is $C^\infty$, real valued and still satisfies $v_{z\bar z }= h$.


text:
Q: Find and Replace formula and function needed In an Excelsheet I have tow Excel Sheet. First Sheet is Keywords and Second sheet is Original Text. keywords text is 6,000 and original text is 3,00,000. When I write VBA function, this function is not work. When I write Proper Formula it is work properly. But few keywords is upper case.
original text:
Bmw 325 / 328 Series / M3 L6 2.5/3.2L P/A M/T radiator
Nissan Maxima Radiator & condenser Cooling Fan assembly Tyc
Gmc, Chevy Truck Tail Light W/Connector plate Passenger Side

keywords text:
BMW
Radiator
Assembly
GMC
Plate
condenser

I need to result output:
**BMW** 325 / 328 Series / M3 L6 2.5/3.2L P/A M/T **Radiator**
Nissan Maxima Radiator & **Condenser** Cooling Fan **Assembly** Tyc
**GMC**, Chevy Truck Tail Light W/Connector **Plate** Passenger Side

I don't understand how can I solve this type problem. I need to solution quickly.

A: try this:
Sub ReplaceWords()
  Dim myarray As Variant
  myarray = Array("BMW", "Radiator", "Assembly", "GMC", "Plate", "Condenser")
  Dim r As Range
  Set r = Range("A1")
  For Each element In myarray
   r.Replace What:=element, Replacement:="**" & element & "**", MatchCase:=False
  Next
End Sub


text:
Q: How to characterize elements in the Bruhat open cell? This might be an elementary question. For simplicity, let's assume $G=GL(n,F)$, where $F$ is a local field. Let $U$ be the subgroup of upper triangular unipotents, $A$ the subgroup of diagonal matrices. $\omega_n$ the longest Weyl element. Then $\Omega=U\omega_nAU$ is the open Bruhat cell.
Now I want to ask how to determine if a given matrix $g=(g_{ij})\in \Omega$?
For example, an easy calculation shows that if $g=(g_{ij})\in \Omega$, then $g_{n1}\ne 0$. But I'm not sure if this is also sufficient.
Of course, other characterizations are also welcome.

A: The elements of the open Bruhat cell are precisely the matrices where the determinant of the $k\times k$ minor of the bottom left hand corner of the matrix is non-zero for all $k\leq n$.  You noted one of these conditions for $k=1$.  This condition is true for $\omega_nA$, and won't be changed by multiplication by upper triangular matrices.  You can check this is sufficient by solving for the upper triangular matrices.


text:
Q: finding reverse dependencies of package on `hackage` The website packdeps allows to search for reverse dependencies of libraries published on hackage.
However, not every package from hackage seem to be listed there, say algebraic-classes
Is there any alternative way to find the reverse dependencies of a generic hackage package ?


text:
Q: regex pandas with multiple potential patterns I have:
blah blah blah (3383-HK) - blah blah blah
blah blah blah (A-US) - blah blah blah
blah blah blah (blah) (3383-HK) - blah blah blah
blah blah blah (A.CC-US) - blah blah blah

I want to extract the stock ticker from each line.
(3383-HK
(A-US
(3383-HK
(A.CC-US

the stock ticker format is:

*

*enclosed in brackets

*has the format XXX-XXX, or XXX.XXX-XXX where XXX are alphanumeric characters ranging in length from 1 to 20 characters in each section

Currently, I use:
df['ticker_region']=df['filename'].str.extract(r"(\(\w{1,20}-\w{1,20})")

and it returns:
(3383-HK
(3383-HK
(A.CC-US

but NOT:
(A.CC-US
Is there a recommended way to extract the last one as well?
I tried:
df['ticker_region']=df['filename'].str.extract(r"(\(\w{1,20}\.?\w{1,10}?-\w{1,20})")

but it is not working, as it does not grab:
(A-US

my full script is:
df=pd.DataFrame({'filename':[    "blah blah blah (3383-HK) - blah blah blah",
    "blah blah blah (A-US) - blah blah blah",
    "blah blah blah (blah) (3383-HK) - blah blah blah",
    "blah blah blah (A.CC-US) - blah blah blah"]})
df['ticker_region']=df['filename'].str.extract(r"(\(\w{1,20}\.?\w{1,10}?-\w{1,20})") # search for (XXXXXXX-XXXXX
df['ticker_region2']=df['filename'].str.extract(r"(\(\w{1,20}.{1,20}?-\w{1,20})") # search for (XXXXXXX-XXXXX
df['ticker_region3']=df['filename'].str.extract(r"(\(\w{1,20}-\w{1,20})") # search for (XXXXXXX-XXXXX

df

A: You may use
\(((?=[\w.]{1,20}-)\w+(?:\.\w+)?-\w{1,20})\)

See the regex demo
Details

*

*\( - a ( char

*((?=[\w.]{1,20}-)\w+(?:\.\w+)?-\w{1,20}) - Group 1 (returned by Series.str.extract):

*

*(?=[\w.]{1,20}-) - there must be 1 to 20 word or . chars and then - immediately to the right of the current location

*\w+  - 1+ word chars

*(?:\.\w+)?  an optional sequence of . and 1+ word chars

*- - a - char

*\w{1,20} - 1 to 20 word chars

*\) - a ) char

A: df.A.str.extract(r'\(([\w\.?]+-.*)\)')

Output
          0
0   3383-HK
1   A-US
2   3383-HK
3   A.CC-US


text:
Q: DATA_ID always send the first row id to JQUERY I'm actually trying to create a modal(confirm box) for delete list and when I'm trying to delete it by using (commented code below)the "confirm box" it works very well, but when I pass it through the onclick to my jquery it will always delete the first row. Please someone help me.

 Adakah anda pasti untuk memadamkan item yang dipilih ?

      PADAM  < button class = "no" > KEMBALI < /button >

adminlist.js
  function functionAlert(element, msg, myYes) {

      var confirmBox = $("#confirm");

      var dataId = $("#elem").data("id");

      console.log(dataId);

      confirmBox.find(".message").text(msg);
      confirmBox.find(".no").unbind().click(function() {
          confirmBox.hide();

      });
      confirmBox.find(".no").click(myYes);
      confirmBox.show();
  }

I knew that it always carry the first row id, because whenever I console it, it will alwys show the first row id, can some help me to get the id by row based on the selected item


text:
Q: Arduino AC dimmer, with Wall switch control I'm building an AC dimmer with arduino, but I also want to have the ability to control the lamp from the wall switch (just on/off, with no dimming). What is the best way to achieve this? Do I also need to have a relay, so the two way from the circuit would be the relay's Normally Open (NO) and Normally Closed (NC) poles? Will the dimming circuit work with the relay, or will it cause any interference to it? Thanks!

A: There are two ways you can do this.
1 - Power the Arduino from the wall switch control.
This way when you turn the switch off, the Arduino turns off and so does the lamp. When you switch the power back on, Arduino boots and dimming will work as usual.
Pros: no power consumption when off, somewhat easier to wire.
Cons: have to wait to boot when you turn light on, Arduino may get unexpected power downs (if you are saving or transmitting data for example).
2 - Power the Arduino from another, permanent power socket, and read the Switch as an input.
This way the Arduino is always on and dimming, and whenever it detects a change of state in the wall switch it decides what to do (turn on/off, dimm, etc..)
Cons: a bit harder to wire (you either have to re-wire the switch for DC - thus removing original functionality - or optocouple your input to read if AC is connected)
Pros: Arduino is always on so no boot delays, you can add power up and down fade-in/outs, etc..


text:
Q: Rails 4 polymorphic has_many ignores table_name Short version: I'm building a new Rails 4 application that uses (read-only) some tables from a database used by a legacy Rails 2 application, which is still in use. The old application models/tables were very confusingly named, however (especially in the context of the new application), so I want to use different names for the models/tables using self.table_name. This all works perfectly until I tried to add in a polymorphic relationship. Rails ignores my defined table_name and does a query on the type using the new model name, which of course is different so it doesn't work. Is there any way to change this?
Long version: There are three models in this equation, and here they are:
class Exporter < MysqlBase
  has_many :lic_exporter_addresses, :as => :place

  self.table_name = 'excons'
  self.primary_key = 'id'
end

class LicBusiness < MysqlBase
  has_one :physical_address, -> { where(category: 'Physical') }, :class_name => 'LicExporterAddress', :as => :place
  has_one :mailing_address, -> { where(category: 'Mailing') }, :class_name => 'LicExporterAddress', :as => :place
  has_many :lic_exporter_addresses, :as => :place

  self.table_name = 'businesses'
  self.primary_key = 'id'
end

class LicExporterAddress < MysqlBase
  belongs_to :place, polymorphic: true

  self.table_name = 'addresses'
  self.primary_key = 'id'
end

We have a ton of different kinds of businesses, so the Business model is the most problematic. I really don't want to have that in the new app because it would be very confusing as to what a "business" actually is. With the current code if I go into the rails console and try to get lic_exporter_addresses for a LicBusiness or Exporter, it does:
 SELECT `addresses`.* FROM `addresses` WHERE `addresses`.`place_id` = '00044c693f6848f9b0978f873cf9999a' AND `addresses`.`place_type` = 'LicBusiness'

when what I need is place_type = 'Business'.
Is there any way to tell Rails what place_type to look for? I did see this question and the second answer looked promising, except that I'm already sort of doing that with Physical and Mailing addresses so I can't figure out how that'd work with both options at the same time... Thanks for any info or ideas.

A: In Rails 4.2, it looks like the exact string used for the query is defined as owner.class.base_class.name, where owner is the model declaring the association. So I don't think it's directly supported. But there are a few ways I can think of to hack around this. I think the most promising might be, in LicBusiness:
has_many :lic_exporter_addresses, ->{where place_type: "Business"}, foreign_key: "place_id"

That is, don't define the association as polymorphic, but define the type scope yourself. This will NOT correctly define place_type in the lic_exporter_addresses table if you ever use lic_exporter_address.place = some_lic_business_instance. However you said this table was read-only, so this may in fact not be an issue for you. If it is, there may be ways to override the behavior to get what you need.
Two other ideas both make me very nervous and I think they are probably quite dangerous for unintended side-effects. They are to override LicBusiness.base_class (this might actually be ok if you do not now and never will have STI set up on LicBusiness, but I'm still nervous), or to override LicBusiness.name (I'm pretty sure this would have unintended side-effects).


text:
Q: Outputting global variables I'm trying to use global variable across a class.
Basically, the function render($html, $pageTitle); is called.
Within that class, exists functions such as buildHeader($pageTitle) which looks like this:
private static function addHeader($pageTitle){
    global $pageTitle;
    $html = self::capture_output('header.inc');
    return $html;
}

within header.inc, I define the variable $pageTitle as global, however, it's not echoing the variable.
I'm also not getting errors that the variable has not been defined / initialised.
the render function calls the private methods, such as addHeader to build the page content.

A: You cover $pageTitle by function argument. Also you should rather use $_GLOBALS['pageTitle']; instead of using global which makes code more clear and helps avoid such conflicts you have. also, I quite believe you should rather move your global $pageTitle; to capture_output() function, where it seem to be used, instead of keeping it in addHeader() where it got no effect.


text:
Q: Characteristic variety of a D-module Let $X$ be an algebraic variety, $M \in Mod(\mathcal{D}_X)$. I am studying the characteristic variety associated to this module, and I am trying to understand why all the different definitions coincide. Fix $F$ a good filtration of $M$, we define:
$Ch(M) = supp \left( \widetilde{gr^{F}(M)} := \mathcal{O}_{T^{*}X} \otimes_{\pi^{-1}(\pi_{*}(\mathcal{O}_{T^{*}X}))} \pi^{-1}(gr^{F}M) \right)$
Being the $\mathcal{O}_{T^{*}X}$-module in the right-hand side coherent, we have: $Ch(M) = V(\mathcal{Ann}(\widetilde{gr^{F}(M)})$
I don't understand why for an affine open subset $U \subset X$ we have:
$Ch(M) \cap T^{*}U = V \left( \; Ann_{gr^FD_U(U)}(gr^{F}M(U)) \; \right)$
The problem that I face is that: $\Gamma(U, \mathcal{Ann}( \widetilde{gr^{F}(M)}) = Ann_{\mathcal{O}_{T^{*}U}(T^{*}U)}(\Gamma(U, \widetilde{gr^{F}(M)})$, which, even though $\mathcal{O}_{T^{*}U}(T^{*}U) = gr^{F}D_{U}(U)$, I don't see why should equal $Ann_{gr^FD_U(U)}(gr^{F}M(U))$. If the last equality were true than the conclusion would follow:
$Ch(M) \cap T^{*}U = V(\mathcal{Ann}(\widetilde{gr^{F}(M)} \rvert_{T^{*}U}) = V \left( \; Ann_{gr^FD_U(U)}(gr^{F}M(U)) \; \right)$
EDIT: To clarify, what I don't understand is why
$Ann_{\mathcal{O}_{T^{*}U}(T^{*}U)}(\Gamma(U, \widetilde{gr^{F}(M)}) = Ann_{gr^FD_U(U)}(gr^{F}M(U))$
It is easy to verify that the RHS is included in the LHS, but the reverse inclusion doesn't seem obvious to me because the sections of the tensor product are not the tensor product of the sections of the two sheaves.

A: Although your cautionary statement about tensor products is true sometimes, in this case it's not. This is because $\pi$ is affine, so over your affine open $U$,  everything commutes with taking global sections.


text:
Q: How to make a parallel connection between two components when each has its own voltage? I have a problem to determine whether or not it is safe to make a connection as picture below. Currently I have a H7EC counter connected to a switch and it has 2.7 V  across terminal 1 & 2 on the counter itself (it should be a battery inside the counter). I was planning to branch out the connection parallel to PC COM port and there's 5.8 V across pin 2 & 3 of the PC COM port.
My question is: Is it safe if I make the connection directly as the picture? If not, what do I need to add in between so it won't do any damage to the counter/COM port?

A: The amount of current that can be drawn from a COM port is not part of its specification.  You would need to look up your individual COM port's drivers and find out how much current they can provide.
Practically speaking, you can pull 10-20mA without trouble, as serial mice used power from these signal lines to power the mouse, and they operated in this range.  To be safe, I'd put resistance in the line to ensure you cannot exceed those currents with the voltages available.
From V=IR, R=V/I = 5.8V/10mA = 580ohm
So if you have 580 ohms of resistance between your power sources and your sinks, you will stay within the range that they are typically designed for.


text:
Q: How to create a popup window (PopupWindow) in Android To create a simple working PopupWindow, we need to do the following:
popup_example.xml:
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:padding="10dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:text="Test Pop-Up" />

    </LinearLayout>

Java code
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup_example, null, false),100,100, true);

pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);

My requirement is that I need a
<TEXTVIEW android:layout_height="wrap_content" android:layout_width="fill_parent" />

and a
<BUTTON android:id="@+id/end_data_send_button" android:text="Cancel"/>

in my popup_example.xml.  How can I handle these two components in my Java code?

A: are you done with the layout inflating? maybe you can try this!!
View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p

A: Here, I am giving you a demo example. See this and customize it according to your need.
public class ShowPopUp extends Activity {
    PopupWindow popUp;
    boolean click = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        popUp = new PopupWindow(this);
        LinearLayout layout = new LinearLayout(this);
        LinearLayout mainLayout = new LinearLayout(this);
        TextView tv = new TextView(this);
        Button but = new Button(this);
        but.setText("Click Me");
        but.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (click) {
                     popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
                     popUp.update(50, 50, 300, 80);
                     click = false;
                } else {
                     popUp.dismiss();
                     click = true;
                }
            }
        });

        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        tv.setText("Hi this is a sample text for popup window");
        layout.addView(tv, params);
        popUp.setContentView(layout);
        // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
        mainLayout.addView(but, params);
        setContentView(mainLayout);
   }
}

Hope this will solve your issue.

A: I construct my own class, and then call it from my activity, overriding small methods like showAtLocation. I've found its easier when I have 4 to 5 popups in my activity to do this.
public class ToggleValues implements OnClickListener{

    private View pView;
    private LayoutInflater inflater;
    private PopupWindow pop;
    private Button one, two, three, four, five, six, seven, eight, nine, blank;
    private ImageButton eraser;
    private int selected = 1;
    private Animation appear;

    public ToggleValues(int id, Context c, int screenHeight){
        inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        pop = new PopupWindow(inflater.inflate(id, null, false), 265, (int)(screenHeight * 0.45), true);
        pop.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.alpha_0));
        pView = pop.getContentView();

        appear = AnimationUtils.loadAnimation(c, R.anim.appear);

        one = (Button) pView.findViewById(R.id.one);
        one.setOnClickListener(this);
        two = (Button) pView.findViewById(R.id.two);
        two.setOnClickListener(this);
        three = (Button) pView.findViewById(R.id.three);
        three.setOnClickListener(this);
        four = (Button) pView.findViewById(R.id.four);
        four.setOnClickListener(this);
        five = (Button) pView.findViewById(R.id.five);
        five.setOnClickListener(this);
        six = (Button) pView.findViewById(R.id.six);
        six.setOnClickListener(this);
        seven = (Button) pView.findViewById(R.id.seven);
        seven.setOnClickListener(this);
        eight = (Button) pView.findViewById(R.id.eight);
        eight.setOnClickListener(this);
        nine = (Button) pView.findViewById(R.id.nine);
        nine.setOnClickListener(this);
        blank = (Button) pView.findViewById(R.id.blank_Selection);
        blank.setOnClickListener(this);
        eraser = (ImageButton) pView.findViewById(R.id.eraser);
        eraser.setOnClickListener(this);
    }

    public void showAtLocation(View v) {
        pop.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, 40, 40);
        pView.startAnimation(appear);
    }

    public void dismiss(){
        pop.dismiss();
    }

    public boolean isShowing() {
        if(pop.isShowing()){
            return true;
        }else{
            return false;
        }
    }

    public int getSelected(){
        return selected;
    }

    public void onClick(View arg0) {
        if(arg0 == one){
            Sudo.setToggleNum(1);
        }else if(arg0 == two){
            Sudo.setToggleNum(2);
        }else if(arg0 == three){
            Sudo.setToggleNum(3);
        }else if(arg0 == four){
            Sudo.setToggleNum(4);
        }else if(arg0 == five){
            Sudo.setToggleNum(5);
        }else if(arg0 == six){
            Sudo.setToggleNum(6);
        }else if(arg0 == seven){
            Sudo.setToggleNum(7);
        }else if(arg0 == eight){
            Sudo.setToggleNum(8);
        }else if(arg0 == nine){
            Sudo.setToggleNum(9);
        }else if(arg0 == blank){
            Sudo.setToggleNum(0);
        }else if(arg0 == eraser){
            Sudo.setToggleNum(-1);
        }
        this.dismiss();
    }

}

A: Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);

Similarly you can get the text view by adding a id to it.

A: LayoutInflater inflater = (LayoutInflater) SettingActivity.this.getSystemService(SettingActivity.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.gd_quick_action_slide_fontsize, null),LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, true);
pw.showAtLocation(SettingActivity.this.findViewById(R.id.setting_fontsize), Gravity.CENTER, 0, 0);
View v= pw.getContentView();
TextView tv=v.findViewById(R.id.....);

A: How to make a simple Android popup window
This is a fuller example. It is a supplemental answer that deals with creating a popup window in general and not necessarily the specific details of the OP's problem. (The OP asks for a cancel button, but this is not necessary because the user can click anywhere on the screen to cancel it.) It will look like the following image.

Make a layout for the popup window
Add a layout file to res/layout that defines what the popup window will look like.
popup_window.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#62def8">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="30dp"
        android:textSize="22sp"
        android:text="This is a popup window."/>

</RelativeLayout>

Inflate and show the popup window
Here is the code for the main activity of our example. Whenever the button is clicked, the popup window is inflated and shown over the activity. Touching anywhere on the screen dismisses the popup window.
MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onButtonShowPopupWindowClick(View view) {

        // inflate the layout of the popup window
        LayoutInflater inflater = (LayoutInflater)
                getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.popup_window, null);

        // create the popup window
        int width = LinearLayout.LayoutParams.WRAP_CONTENT;
        int height = LinearLayout.LayoutParams.WRAP_CONTENT;
        boolean focusable = true; // lets taps outside the popup also dismiss it
        final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

        // show the popup window
        // which view you pass in doesn't matter, it is only used for the window tolken
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

        // dismiss the popup window when touched
        popupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                popupWindow.dismiss();
                return true;
            }
        });
    }
}

That's it. You're finished.
Going on
Check out how gravity values effect PopupWindow.

You can also add a shadow.

Further study
These were also helpful in learning how to make a popup window:

*

*PopupWindow documentation

*How To Create Pop Up Window In Android (YouTube video)

*Android Popup Window Example

A: This an example from my code  how to address a widget(button) in popupwindow
View v=LayoutInflater.from(getContext()).inflate(R.layout.popupwindow, null, false);
    final PopupWindow pw = new PopupWindow(v,500,500, true);
    final Button button = rootView.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pw.showAtLocation(rootView.findViewById(R.id.constraintLayout), Gravity.CENTER, 0, 0);

        }
    });
    final Button popup_btn=v.findViewById(R.id.popupbutton);

    popup_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popup_btn.setBackgroundColor(Color.RED);
        }
    });

Hope this help you

A: Edit your style.xml with:
<style name="AppTheme" parent="Base.V21.Theme.AppCompat.Light.Dialog">

Base.V21.Theme.AppCompat.Light.Dialog provides a android poup-up theme


text:
Q: setHTTPMethod:@"POST" not working i try many solutions from stackoverflow to fix this trouble, but no luck.
My trouble is setHTTPMethod not works thats always use GET method.
My code is:
NSHTTPURLResponse *response;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverAPIUrl]];
NSMutableData *requestBody = [NSMutableData data];
NSString *boundary = @"ljlkjlkkljlk98jjmnj";

[request setHTTPMethod:@"POST"];
[request setCachePolicy: NSURLRequestReloadIgnoringCacheData];

[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField: @"Content-Type"];

[requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",@"file.gz"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[self gzipData:returnData]];

NSMutableArray *keys=[[NSMutableArray alloc] init];
NSMutableArray *vals=[[NSMutableArray alloc] init];
//post vars
[keys addObject:@"postvariable"];
[vals addObject:@"kjasdhfklsadjfhsajdkfhasdfjhsadfkjsadfhskdfjhjhf"];
//add post vars to body

for(i=0;i<[keys count];i++)
{
    [requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\nContent-Disposition: form-data; name=\"%@\"; \r\n\r\n%@",boundary,
                              [keys objectAtIndex:i],
                              [vals objectAtIndex:i]
                              ] dataUsingEncoding:NSUTF8StringEncoding]];
}
//add post vars to body
[requestBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:requestBody];

NSData *answer = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: nil ];

NSLog(@"server answer:%@",[[NSString alloc] initWithData:answer encoding:NSUTF8StringEncoding]);

PHP on server
if(isset($_REQUEST["getjob"]))
{

}
else
{
    foreach ($_SERVER as $name => $value) {
        echo "$name: $value\n";
    }

    var_dump($_FILES);
    var_dump($_POST);
    echo file_exists($_FILES["file"]["tmp_name"]);
    echo "ok";
}

What i have:
REMOTE_PORT: 57688
GATEWAY_INTERFACE: CGI/1.1
SERVER_PROTOCOL: HTTP/1.1
REQUEST_METHOD: GET
QUERY_STRING:
REQUEST_URI: /dcapi/

Thats server answer just returns $_SERVER variables. I always getting GET method. But i always use POST.
I tried many solutions from stackoverflow with no luck:

*

*http://kemal.co/index.php/2012/02/fetching-data-with-getpost-methods-by-using-nsurlconnection/ - i just download sources. With no result.

*HTTP Post Request in Objective-C Not Working
not works.

*Upload file not working vie HTTP Post
not works.

*POST from iPhone to PhP not working
not works.

A: Ok. I solve it.
Thats because i set end of url as folder/ but executing file is in folder/index.php.
And i getting 301 redirect for my post request and only get result from second request as GET.


text:
Q: XSLT: Howto exclude elements with a specific string I have this xml:

<Elements>
  <tag1>
    <ID>title</ID>
    <EventDescription>description</EventDescription>
    <ContentDuration>01:30:35:02</ContentDuration>
    <Format>format</Format>
    <Segment1>10:00:00:00-10:10:46:02</Segment1>
    <Segment2>10:10:46:08-10:22:31:13</Segment2>
    <Segment3>-</Segment3>
    <Segment4>-</Segment4>
    <Segment5>-</Segment5>
    <Segment6>-</Segment6>
  </tag1>
</Elements>

I would like to exclude element containing only the string "-"
the result should be like this

<Elements>
<tag1>
 <ID>title</ID>
 <EventDescription>description</EventDescription>
 <ContentDuration>01:30:35:02</ContentDuration>
 <Format>format</Format>
 <Segment1>10:00:00:00-10:10:46:02</Segment1>
 <Segment2>10:10:46:08-10:22:31:13</Segment2>
 </tag1>
 </Elements>

A: Start off with the identity template.
 <xsl:template match="@*|node()">
     <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
     </xsl:copy>
 </xsl:template>

Then add a template to match, and exclude, the elements that have text equals "-"
 <xsl:template match="*[text() = '-']" />

Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="*[text() = '-']" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

EDIT: In response to LarsH's comment, if you did have a node like <Segment3>-<a /></Segment3> that you didn't want removed, try changing the template to this:
<xsl:template match="*[not(*) and text() = '-']" />


text:
Q: Monitor disk activity programmatically (Windows) In Windows 2008R2, in Resource Monitor in the Disk Activity section I can see the number of bytes read from/written into files. How can I do this in a programmatic manner, preferably using C# (or Win32 API)? I have looked into WMI and various performance counters, however I cannot figure out if there is something which suits my needs.

A: The counters relating to file I/O are on the LogicalDisk and PhysicalDisk objects. Take a look in Perfmon to see what counters are available.
Use the PerformanceCounter class in C# or the PDH API in C/C++. In my experience these are much more efficient than WMI - though this may not matter in your application.


text:
Q: Using tuples as inputs in functions Suppose I define a function like so, where args should be a tuple that contains two elements, an example would be (1,2):
def func(some_matrix,*args):
        return some_multiplication = some_matrix[0,first element of args] * some_matrix[0,second element of args]

How do I access the first and second elements of the tuple passed by the user in the body of the function? I also suppose that an example of calling a function would look something like: func(A,(1,2)) ?

A: You could do that using list indexing or tuple indexing in this case
def acd(val, *vag):
    print '''Given Fixed value:\t{}
    Given Variable Tuple:\t{}
    First Var Value:\t{}
    Second Var value:\t{}
    Len of var:\t{}
    Len of first var element:\t{}
    '''.format(val, vag, vag[0][0], vag[0][1], len(vag), len(vag[0]))
acd(1, (3,4))

Output:
Given Fixed value:      1
Given Variable Tuple:   ((3, 4),)
First Var Value:        3
Second Var value:       4
Len of var:     1
Len of first var element:       2


text:
Q: Display static image from iOS filesystem I am currently trying to display a static image within my react native app. I am using the Image Component from React Native, so there is nothing custom.
Maybe important to mention is that i am opening the Main App with my Share Extension => Image Gallery, Select Image, Share with Main App.
On the Simulator it works just great, when i am using a real device nothing is displayed. Here is the Image path i am trying to display:
<Image
  style={styles.image}
  source={{
    uri: "/private/var/mobile/Containers/Data/PluginKitPlugin/156268E6-6BE0-4055-BF0E-0EDC546FC2F9/tmp/RNSE_TEMP_IMG.png",
    isStatic: true
  }}
/>

I have tried adding file:// + /private.... but this did not help at all.
Any ideas?


text:
Q: What is this component in the image? I am trying to know what is the black circular component stacked in front of the switch and adjacent to the large capacitor in this circuit board.
I am not talking  about the transistor with the heat sink. I am talking about the circular black component.
This thing has 4 pins in the bottom.

A: This element is a bridge rectifier. The two oposite pins are AC input (designated with ~ ) and the other two are DC output (designated with + and - ).

A: That is rectifier of 4M ohm. + and minus labels are DC output. ~ labeled pins are AC input. Keep + on top and - at bottom then right side ~ is Phase and left side is Neutral.


text:
Q: keep separate text on the same line as div tag I have am using CSS to sytle part of my text font to bold. But I don't want the whole line to be bold. Just part of the text. How can I achieve this? Here is my code:
HTML

Revision:
 1.0 draft A

CSS
#titleLabels
{
   font-weight: bold;
}

The output of this is this:

This is not what I want. I want the "1.0 draft A bit to be inline with the bit that says Revision".
How can I go about doing this?

A: Just add display:inline to #titleLabels:

#titleLabels {
    font-weight: bold;
    display:inline;
}

Revision:
1.0 draft A

Divs by default are block level elements and will take up the full width of their parent element unless you alter that.
A more logical solution would be to not use divs on the revision text and instead use either ,  or a  with the font-weight styled.

#titleLabels {
  font-weight: bold;
}

  Revision:1.0 draft A

  Revision:1.0 draft A

  Revision:1.0 draft A

A: Use display:inline-block

#titleLabels
{
   font-weight: bold;
    display:inline-block;
}

Revision:
 1.0 draft A

A: You can use a  tag to simply set a certain segment of text as bold

   Revision: 1.0 draft A


text:
Q: Divide pandas data frame into test and train based on unique ID I want to split it into two data frames,(train, and test) using the values in the id column. The split should be such that in the first data frame I have 70% of the (unique) ids and in the second data frame, I have 30% of the ids. The ids should be randomly split.
I have multiple values corresponding to one id.
The below script I was trying:
Training_data, Test_data = sklearn.model_selection.train_test_split(data, data['ID_sample'].unique(), train_size=0.30, test_size=0.70, random_state=5)

A: Sorted the issue in the following way
samplelist = data["ID_sample"].unique()
    training_samp, test_samp = sklearn.model_selection.train_test_split(samplelist, train_size=0.7, test_size=0.3, random_state=5, shuffle=True)

    training_data = data[data['ID_sample'].isin(training_samp)]
    test_data = data[data['ID_sample'].isin(test_samp)]

A: I am not sklearn expert, but I know little about it and since ages when this came into existence similar questions I see all new-comer's used to ask.
Anyway, here is how you can solve it, you can opt to import  import train_test_split from sklearn.model_selection and accomplish it. I have just created a random data and applied that same.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.randn(100, 2))
>>> df
           0         1
0  -1.214487  0.455726
1  -0.898623  0.268778
2   0.262315 -0.009964
3   0.612664  0.786531
4   1.249646 -1.020366
..       ...       ...
95 -0.171218  1.083018
96  0.122685 -2.214143
97 -1.420504  0.469372
98  0.061177  0.465881
99 -0.262667 -0.406031

[100 rows x 2 columns]
>>> from sklearn.model_selection import train_test_split
>>> train, test = train_test_split(df, test_size=0.3)

Here is your first dataframe train
>>> train
           0         1
26 -2.651343 -0.864565
17  0.106959 -0.763388
78 -0.398269 -0.501073
25  1.452795  1.290227
47  0.158705 -1.123697
..       ...       ...
29 -1.909144 -0.732514
7   0.641331 -1.336896
43  0.769139  2.816528
59 -0.683185  0.442875
11 -0.543988 -0.183677

[70 rows x 2 columns]

Here its second test dataframe:
>>> test
           0         1
30 -1.562427 -1.448936
24  0.638780  1.868500
70 -0.572035  1.615093
72  0.660455 -0.331350
82  0.295644 -0.403386
22  0.942676 -0.814718
15 -0.208757 -0.112564
45  1.069752 -1.894040
18  0.600265  0.599571
93 -0.853163  1.646843
91 -1.172471 -1.488513
10  0.728550  1.637609
36 -0.040357  2.050128
4   1.249646 -1.020366
60 -0.907925 -0.290945
34  0.029384  0.452658
38  1.566204 -1.171910
33 -1.009491  0.105400
62  0.930651 -0.124938
42  0.401900 -0.472175
80  1.266980 -0.221378
95 -0.171218  1.083018
74 -0.160058 -1.383118
28  1.257940  0.604513
87 -0.136468 -0.109718
27  1.909935 -0.712136
81 -1.449828 -1.823526
61  0.176301 -0.885127
53 -0.593061  1.547997
57 -0.527212  0.781028

In your case, it should ideally be working as below, however, you don't need to define train_size if you are defining test_size or vice versa.
>>> train, test = train_test_split(data['ID_sample'], test_size=0.3)

OR
>>> train, test = train_test_split(data['ID_sample'], test_size=0.3, random_state=5)

OR
This returns an arraylist ...
>>> train, test = train_test_split(data['ID_sample'].unique(), test_size=0.30, random_state=5)


text:
Q: How to put UISlider vertical? I want to put UISlider in vertically. I have no idea about this, so please help me for this.

A: Swift 3:
slider.transform = slider.transform.rotated(by: CGFloat(0.5 * Float.pi))

// Use 1.5 to invert the shadow of slider if you want

A: In case you work with auto layouts:
In your viewDidLoad, try:
UIView *superView = self.sizeSlider.superview;
[self.sizeSlider removeFromSuperview];
[self.sizeSlider removeConstraints:self.view.constraints];
self.sizeSlider.translatesAutoresizingMaskIntoConstraints = YES;
self.sizeSlider.transform = CGAffineTransformMakeRotation(M_PI_2);
[superView addSubview:self.sizeSlider];

It does not work with constraints, so the trick is to remove the constraints for your uislider.
You might have to resize it manually by setting its frame property.

A: As of Xcode 4.2, you can sort of do the same in Interface Builder.

*

*Create a slider

*Show the "Identity Inspector"

*Add a "User Defined Runtime Attribute"

*Set the key path to "layer.transform.rotation.z", the type as "String" ("Number" won't allow floating point values) (possible since Xcode 5) and the value to "-1.570795" (-π/2).

Unfortunately, it will still appear as horizontal in Interface Builder.
But you can position the center and don't need to create a custom class, so it might be useful enough in some cases. The effect is the same as ravinsp's code.

A: You have to do this programaticaly. Assuming your UISlider is bound to a variable called slider, add this code in your viewDidLoad method in ViewController.m:
- (void)viewDidLoad {

    [super viewDidLoad];

    CGAffineTransform trans = CGAffineTransformMakeRotation(M_PI * 0.5);
    slider.transform = trans;
}

Let me know if you need any more help on this..

A: Using an IBOutlet and setter observers.
If you want the max to be at the bottom, divide pi by positive 2
@IBOutlet weak var slider: UISlider! {
    didSet {
        slider.transform = CGAffineTransform(rotationAngle: .pi / -2)
    }
}


text:
Q: Why aren't votes on comments reflected in a person's Reputation Score?
Possible Duplicates:
Reputation for comments?
Should downvoting be allowed on comments?

Don't get me wrong, I have come to appreciate that the whole reputation concept that stackoverflow employs is a highly evolved process.  It is awesome!  It effectively separates the useful information from the just plain wrong information.  No doubt, this is what makes the whole concept work extremely well.
Why shouldn't the same criterion apply to comments?
It doesn't seem symmetric to me that comments allow only for up votes (with no reflection to the comment-er) and at the same time disallow the down voting of useless comments (which in a perfect world would be somehow reflected).
Comments are usually read along with proposed answers.  When someone posts anything, it only seems right for their text to be fairly judged by the existing community-of-trust.  This is why stackoverflow works so well.
Some comments are useless; some comments help in clarifying the proposed answer.  This distinction is a relevant factor for judging someone who participates in such a forum. Why the asymmetry?
I have tried to think of reasons to the contrary, and all I ever come up with is "They just asked for clarification, why should they be punished?"  In the real world, I don't think any comment asking for useful clarification would be down-voted, at least not for long.
I don't know what the metrics should be, but ignoring this information just seems wrong.
In my mind, we are all contributing something.  The faster we can separate the useful from the useless, the more effective this paradigm becomes.  What am I missing?

A: Comment is a relaxed discussion area. For this reason, you will surely notice many comments with jokes, sarcasms. And usually a lot of upvotes.
Those comments upvotes are not valuable as reputation since they are not technical expertise. On the contrary answers are.
Every comment which is clarifying an answer should be posted as an edit. I usually do in my answers.
We cannot say: "Oh from now, comments are for technical expertise discussion". The comments are needed because users are not the same level of knowledge, because they don't use the same vocabulary, because one can add a detail to a good answer. And we can't value that because it is subjective. Also, we cannot accept to penalise a user because he does not understand.

A:
It doesn't seem symmetric to me that comments allow only for up votes (with no reflection to the comment-er)

They don't support "upvotes" - they support "this is a great comment". However, most comments are (for example) requests for clarification. Essential, but not answers.

and at the same time disallow the down voting of useless comments (which in a perfect world would be somehow reflected).

You can flag comments - for example as "not constructive / off-topic".
Additionally, there are multiple badges related to good comments:

*

*commentator

*pundit

I am asking why comments are not reflected in the user's reputation

See the FAQ.


text:
Q: Display count results of requests with results of jobs horizontally and locations vertically 3 tables So I have a primary table of data which holds IDs against a job and location, so for example:
Requests Table dbo.Requests
RequestID    JobID    LocationID
1            3        5
2            4        8
3            3        2

Job Table dbo.Jobs
JobID    JobTitle
1        Job 1
2        Job 2
3        Job 3

Location Table dbo.Locations
LocationID   LocationName
1            Location 1
2            Location 2
3            Location 3

Now what I want to do is display a list of counts for jobs done and for locations, something like:
Job Title      Total Jobs    Location 1   Location 2  Location 3
Job 1          30            5            15          10
Job 2          10            2            2           6
Job 3          40            22           0           18

So I've got the first part fine for displaying the jobs and total count, but I'm stuck getting the locations to list to the right hand side?
SELECT
 job.JobTitle
,isnull(COUNT(req.JobID),0) AS 'Total Jobs'

FROM  Requests req

RIGHT OUTER JOIN Jobs job
ON req.JobID = job.JobID

GROUP BY job.JobTitle
ORDER BY JobTitle

Many thanks

A: You can use the following query
SELECT JobID,JobTitle,[1],[2],[3],[4],[5],[6],[7],[8]
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN([1],[2],[3],[4],[5],[6],[7],[8])) p

And if you want use dynamic number of columns you can generate script and execute it using EXEC
DECLARE @locationIDs varchar(200)=''

SELECT @locationIDs+=CONCAT(',[',LocationID,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')

--PRINT @locationIDs

DECLARE @query varchar(1000)=CONCAT('SELECT JobID,JobTitle,',@locationIDs,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)

The variant with location titles
DECLARE
  @locationIDs varchar(200)='',
  @locationTitles varchar(2000)=''

SELECT
  @locationIDs+=CONCAT(',[',LocationID,']'),
  @locationTitles+=CONCAT(',[',LocationID,'] [',LocationName,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')
SET @locationTitles=STUFF(@locationTitles,1,1,'')

--PRINT @locationIDs
--PRINT @locationTitles

DECLARE @query varchar(2000)=CONCAT('SELECT JobID,JobTitle,',@locationTitles,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)


text:
Q: Link to an external URL and also run controller method I'm trying to get my head around Rails routes/controllers and ajax and I'm in need of a bit of direction to help solve my current challenge...
I'm rendering a list of links from the database, each contains a 'last_visited' field.
As a user, I'd like to click a link and for it to open in a new tab (target = _blank). On doing so the link's 'last_visited' field will be updated with the current time and date.
Here's what I have so far:
View
%li.feed
  = link_to(visit_path(:id => feed.id), :method => :put, :target => '_blank') do
    .title=feed.title

Route
match "/feeds" => "pages#visit_feed", :as => :visit

Controller
def visit_feed
 @feed = Feed.find(params[:id])
 @feed.update_visit_date!

 respond_to do |format|
   format.html { redirect_to @feed.url }
   format.json { head :no_content }
 end
end

The 'last_visited' field update is handled in the model.
While this works, a new tab opens with the link and the last_visited date is updated. The anchor tag is rendered like this (note the href):
<a href="/feeds?id=7" data-method="put" rel="nofollow" target="_blank">
  // content
</a>

I'm using the controller format.html to redirect_to, which is causing (I assume) undesirable behaviour, in that when I "cmd + click" a new tab doesn't open in the background as I stay on the page (sounds trivial but it's a very common and crucial user behaviour for what I'm building).
So in short, I'm keen to hear about an alternative/recommended approach... I've been considering using ajax to update the last_visited field rather than controller/model, is this recommended? How would I go about this?
Any help/thoughts/direction is much appreciated. Thanks for your time.


text:
Q: NetSuite Sublist/child record does not update/refresh in edit mode If the form I am on is in edit mode, and I add items to the sublist (A child custom record) via my suitescript I can not get the list that is visible to the customer to refresh/update.
I have attempted to use the following command, but then found that it only works on a static / read only list.
// Refresh the package contents list
nlapiRefreshLineItems('recmachcustrecord_myCustomRecord');

Is there a way to force a sublist/child record to update its view when the parent transaction form is in edit mode?
On my form I have clicked my "Do Something" button which is to create child records. After the records are created the transaction form does not update the sublist. When I exit edit mode the form then realizes the new lines and displays them.
Thank you,

A: You may have other fields on the record that are not saved yet.
In order to do what you want you'd have to save the record and reopen it with your script.
Here is an example from Netsuite help of saving and reopening a record:
try
{
//committing the phone call record to the database
  var callId = nlapiSubmitRecord(call, true);
  nlapiLogExecution('DEBUG', 'call record created successfully', 'ID = ' + callId);

  //Redirect the user to the newly created phone call
  nlapiSetRedirectURL('RECORD', 'phonecall', callId, false, null);
}
catch (e)
{
  nlapiLogExecution('ERROR', e.getCode(), e.getDetails());
}


text:
Q: Calculations within a spotfire column My firm decided on spotfire and then appointed me spotfire guru (cos I was there) and now I am figuring it out. We work with really large data sets (the one i'm asking about a couple of million rows).  Anyway, the column is Z data and the difference between each sequential cell will show how far the machine it represents has moved.  Eg:
Name    Time Stamp         X      Y     Lat     Long      Z         Delta Z
Name    28.3.2018 10:59 0,02438 0,02888 60,49   26,96   0,037794693
Name    28.3.2018 10:59 0,02671 0,03768 60,49   26,96   0,046186649 0,00839
Name    28.3.2018 10:59 0,02409 0,0294  60,49   26,96   0,038009053 0,00818
Name    28.3.2018 11:00 0,02676 0,03768 60,49   26,96   0,046215582 0,00821
Name    28.3.2018 11:00 0,02393 0,02941 60,49   26,96   0,037915604 0,00830
Name    28.3.2018 11:00 0,02669 0,03761 60,49   26,96   0,046117981 0,00820
Name    28.3.2018 11:00 0,02341 0,02966 60,49   26,96   0,037785496 0,00833
Name    28.3.2018 11:00 0,02673 0,03758 60,49   26,96   0,046116692 0,00833
Name    28.3.2018 11:00 0,02329 0,0297  60,49   26,96   0,037742736 0,00837
Name    28.3.2018 11:00 0,02205 0,0306  60,49   26,96   0,037716873 0,00003

So, above is a dump of a few rows from the output that I have taken from excel.  I run a python script on the source data (which is JSON) and it outputs the above except for the last two columns which i need to calculate.  I can use spotfire to make the Z column (that's simple Pythagoras as X and Y are along and up from the reference point) but what I need is the change in Z (delta Z) through the day. In excel its easy as the formula is "=ABS(G3-G2)" and then paste it along the whole column it becomes "=ABS(G4-G3)", "=ABS(G5-G4)" and so on.  I can't make it in excel as the file is too big.
The formula doesn't take the very first Z as a fixed, anchor point, it uses each one along.  The data then lets me see how far the machine has moved in a certain period.
It is this that I can't solve in spotfire.  All help appreciated.

A: UPDATE: thanks for including the timestamp column and clarifications. I still needed to use the [Row] column I created because I wanted to make sure things go in the correct order, and the timestamp isn't granular enough to ensure that. if you have a timestamp with seconds or milliseconds in your actual dataset, I suggest to use that over a [Row].
that said, I don't see too big a difference from the original results, and I think my answer below still almost completely works. the biggest difference is that the blank row for [Delta Z] is at the top of the data set instead of the bottom. I've accounted for this by changing the expression to:
Abs([Z] - First([Z]) OVER Previous([Row]))

here's the resulting table. [Delta Z] is the results column you posted above and [DZ_1] is my new column:
DeltaZ    Z              Row  DZ_1
          0.037794693    1
0.00839   0.046186649    2    0.008391956
0.00818   0.038009053    3    0.008177596
0.00821   0.046215582    4    0.008206529
0.0083    0.037915604    5    0.008299978
0.0082    0.046117981    6    0.008202377
0.00833   0.037785496    7    0.008332485
0.00833   0.046116692    8    0.008331196
0.00837   0.037742736    9    0.008373956
0.00003   0.037716873    10   2.5863000000001E-05

as an aside, you can adjust the number of decimals shown to whatever you like by going to Edit»Column Properties, selecting the column in question, choosing the Formatting tab, and finally setting the Decimals dropdown as desired.

first, welcome to StackOverflow. please in the future be prepared to provide a complete Minimally Complete, Verifiable Example. in terms of Spotfire, that means a sample dataset (in text) that I can copy-paste into Spotfire, including a column showing your expected results. you can create this in Excel or Notepad. please understand that I'm taking time out of my day to help you with your problem, and request that you are compelled to make it as simple as possible for me to do so.
second, welcome to Spotfire! I learned the same way as you. I strongly recommend asking your employer to pay for the TIBCO Spotfire online courses as they will provide a great base of understanding for using the tool.
with that out of the way, I've made the following assumptions about your dataset since you've not fully answered my questions about your dataset. if my assumptions are incorrect, please answer my questions about your dataset.

*

*there is no column indicating some kind of order, such as a timestamp or row number

*you do not expect any result in the final row of the dataset

to satisfy your requirements, first I needed to create a column that removes assumption #1 above. I've called this column [Row] and its expression is simply:
RowId()

this will output the literal row number for that row (as opposed to the BaseRowId() function, which shows the visual row number, after any marking and filters are applied).
I created this because in order to compare rows against one another, Spotfire requires some kind of indicator as to which row comes before the next one.
then I created a second column, [Delta Z] with the following expression:
Abs([Z] - First([Z]) OVER Next([Row]))

in other words, "for each row, take the current value of [Z] for that row and subtract it from the first value of [Z] found over all of the following rows (i.e., the next row)."
this produces the following:
Z          Row     Delta Z
0.24157    1       0.03424
0.27581    2       0.03195
0.24386    3       0.000149999999999983
0.24371    4

you can hide [Row] in any table visualization through the Properties dialog for that visualization, but you cannot delete it completely.


text:
Q: How do I extend a Yii2 kartik-v grid DataColumn to a BooleanColumn? Currently:
Model: ProductSearch
<?php
    namespace frontend\models;

    use yii\base\Model;
    use yii\data\ActiveDataProvider;
    use frontend\models\Product;

    class ProductSearch extends Product
    {
      public function rules()
      {
        return [
        [['id','productcategory_id', 'productsubcategory_id'], 'integer'],
        [['name', 'surname','frequency','contactmobile', 'gc_number','specialrequest',
          'sellstartdate', 'sellenddate', 'discontinueddate', 'modifieddate'], 'safe'],
        [['listprice'], 'number'],
        [['isactive'],'boolean'],
        ];
      }

      public function scenarios()
      {
         return Model::scenarios();
      }

      public function search($params)
      {
         $query = Product::find();

         $dataProvider = new ActiveDataProvider([
          'pagination' => ['pageSize' => 10],
          'query' => $query,
          'db'=> \frontend\components\Utilities::userdb(),
         ]);

         $this->load($params);
         if (!$this->validate()) {
            return $dataProvider;
         }

         $dataProvider->sort->attributes['productcategory_id'] = [
         'asc' => ['productcategory_id' => SORT_ASC],
         'desc' => ['productcategory_id' => SORT_DESC],
         ];
         $dataProvider->sort->attributes['productsubcategory_id'] = [
         'asc' => ['productsubcategory_id' => SORT_ASC],
         'desc' => ['productsubcategory_id' => SORT_DESC],
         ];

         $query->andFilterWhere([
            'id' => $this->id,
            'listprice' => $this->listprice,
            'isactive'=>$this->isactive,
            'productcategory_id' => $this->productcategory_id,
            'productsubcategory_id' => $this->productsubcategory_id,
            'frequency'=>$this->frequency,
            'name'=>$this->name,
            'surname'=>$this->surname,
            'gc_number'=>$this->gc_number,
            'sellstartdate' => $this->sellstartdate,
            'sellenddate' => $this->sellenddate,
            'discontinueddate' => $this->discontinueddate,
            'modifieddate' => $this->modifieddate,
        ])
        ->all();
        return $dataProvider;
    }
}

Current Grid Picture and Code

[
 'class' => 'kartik\grid\DataColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],

<?php
    echo kartik\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'bootstrap'=>true,
    'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
    'containerOptions' => ['style'=>'overflow: auto'],
    'pjax' => true,
    'pjaxSettings' =>[
                      'neverTimeout'=>true,
                      'options'=>['id'=>'kv-unique-id-7'],
                     ],
    'responsiveWrap'=>true,
    'bordered' => true,
    'striped' => true,
    'condensed' => true,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => false,
    'showPageSummary' => true,
    'panel' => [
    'type' => GridView::TYPE_PRIMARY,
    'heading'=> $comptel,
    ],
    'exportConfig' => [
                   GridView::CSV => ['label' => Yii::t('app','Export as CSV'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::HTML => ['label' => Yii::t('app','Export as HTML'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::PDF => [ 'label' => Yii::t('app','Export as PDF'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::EXCEL=> ['label' => Yii::t('app','Export as EXCEL'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                   GridView::TEXT=> ['label' => Yii::t('app','Export as TEXT'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                 ],
]);
?>

If I change the format to 'boolean' I get yes's however I would prefer to see an image of a tick or a cross. A tick for the yes's and a cross for the no's.
How can I accomplish this given the above code? My data is filtering nicely so that if I check on the checkbox column under active, it either displays zero's or one's.

A: I have managed to sort this problem out by changing the classname to Boolean. The BooleanColumn extends from the DataColumn. I removed the:
'format' => 'boolean'

as well. Even though the filter in kartik\grid\BooleanColumn is auto-generated it is generating the following output for all my one's which is what I want:

Here is my final code:
[
 'class' => 'kartik\grid\BooleanColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],