text:
Q: Combining Using Two Columns A very basic question about merging interchangable columns.
Say I have a table
  subject stim1 stim2 Chosen Tchosen
     <dbl> <int> <int>  <int>   <int>
 1       1     1     2      1       4
 2       1     1     2      2      15
 3       1     1     3      1       2
 4       1     1     3      3      13
 5       1     2     1      1       2
 6       1     2     1      2      13
 7       1     2     3      2       3

where stim1 and stim 2 are interchangable (Stim1=1,Stim2=2 is equivalent to Stim1=2, Stim2=1)
What is the simplest way to merge the data so that Tchosen is added from the two equivalent columns (though Chosen and by subject should be maintained distinctly)
Desired output
   subject stim1 stim2 Chosen Tchosen
     <dbl> <int> <int>  <int>   <int>
 1       1     1     2      1       6
 2       1     1     2      2      28
 3       1     1     3      1       4
 4       1     1     3      3      28
 5       1     2     3      2       3
 6       1     2     3      3      12...

Thank you

A: Here is a data.table approach.. could not reproduce your desired output, since it contains values that are not in your sample data?
library(data.table)
DT <- fread("  subject stim1 stim2 Chosen Tchosen
       1     1     2      1       4
       1     1     2      2      15
       1     1     3      1       2
       1     1     3      3      13
       1     2     1      1       2
       1     2     1      2      13
       1     2     3      2       3")

# Switch values of stim2 and stim1 if stim2 < stim1
DT[stim2 < stim1, `:=`(stim1 = stim2, stim2 = stim1)]
# Now summarise and sum
DT[, .(Tchosen = sum(Tchosen, na.rm = TRUE)), by = .(subject,stim1, stim2, Chosen)]
#    subject stim1 stim2 Chosen Tchosen
# 1:       1     1     2      1       6
# 2:       1     1     2      2      28
# 3:       1     1     3      1       2
# 4:       1     1     3      3      13
# 5:       1     2     3      2       3

A: A base R option using merge + rowSums
transform(
  merge(df,
    df,
    by.x = c("subject", "stim1", "stim2", "Chosen"),
    by.y = c("subject", "stim2", "stim1", "Chosen"),
    all.x = TRUE
  ),
  Tchosen = rowSums(cbind(Tchosen.x, Tchosen.y), na.rm = TRUE)
)

which gives
  subject stim1 stim2 Chosen Tchosen.x Tchosen.y Tchosen
1       1     1     2      1         4         2       6
2       1     1     2      2        15        13      28
3       1     1     3      1         2        NA       2
4       1     1     3      3        13        NA      13
5       1     2     1      1         2         4       6
6       1     2     1      2        13        15      28
7       1     2     3      2         3        NA       3

where NA exists probably due to the incomplete data in your post.
Data
> dput(df)
structure(list(subject = c(1L, 1L, 1L, 1L, 1L, 1L, 1L), stim1 = c(1L,
1L, 1L, 1L, 2L, 2L, 2L), stim2 = c(2L, 2L, 3L, 3L, 1L, 1L, 3L
), Chosen = c(1L, 2L, 1L, 3L, 1L, 2L, 2L), Tchosen = c(4L, 15L,
2L, 13L, 2L, 13L, 3L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))

A: You can use pmin/pmax to sort stim1 and stim2 columns and calculate sum for each group.
aggregate(Tchosen~., transform(df, stim1 = pmin(stim1, stim2),
                                   stim2 = pmax(stim1, stim2)), sum)

#  subject stim1 stim2 Chosen Tchosen
#1       1     1     2      1       6
#2       1     1     3      1       2
#3       1     1     2      2      28
#4       1     2     3      2       3
#5       1     1     3      3      13


text:
Q: getting data from mysql showing empty string I fetch data from mysql and convert it to JSON but receive an empty array as a result: []
I want to select all data where category=given variable:
$flu = $_POST['searchCode'];
$query = mysql_query("SELECT * From catalog_Master WHERE  category='%$flu%'");

$rows = array();
while($row = mysql_fetch_assoc($query)) {
    $rows[] = $row;
}
echo json_encode($rows);

A: For % to work in MySQL, you need LIKE:
$query=mysql_query("SELECT * From catalog_Master WHERE category LIKE '%$flu%'");

You can also match beginning or end:
$query=mysql_query("SELECT * From catalog_Master WHERE category LIKE '$flu%'");
$query=mysql_query("SELECT * From catalog_Master WHERE category LIKE '%$flu'");

If you want exact matches, lose the % and the LIKE:
$query=mysql_query("SELECT * From catalog_Master WHERE category='$flu'");

Also, you should validate your $_POST variables (at least use mysql_real_escape_string, better use mysqli or PDO).

A: try this
$query =mysql_query("SELECT * From catalog_Master WHERE  category like '".$flu."%'");

A: Try this :
$flu = $_POST['searchCode'];
$query = mysql_query("SELECT * From catalog_Master WHERE  category LIKE '%".$flu.%"'");

$rows = array();
while($row = mysql_fetch_assoc($query)) {
    $rows[] = $row;
}
echo json_encode($rows);

redpajama_set_name: RedPajamaStackExchange


text:
Q: git clone stuck in Debian 11 while handshaking using tlsv1.3 The following command works fine in Debian 9 but get stuck in Debian 11
git clone https://github.com/gravitystorm/openstreetmap-carto

Also same happens to Curl command below:
curl https://github.com/gravitystorm/openstreetmap-carto -v

curl output in Debian 11 (before stuck):
*   Trying 140.82.121.4:443...
* Connected to github.com (140.82.121.4) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/certs/ca-certificates.crt
*  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):

But after adding --tlsv1.3, the curl command works perfectly in Debian 11 like below:
curl --tlsv1.3 https://github.com/gravitystorm/openstreetmap-carto

But I can't find a way to do same for git command.


text:
Q: Get Part of Line By Streamreader I've got the following StreamReader:
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
    while (!sr.EndOfStream)
    {
        String line = sr.ReadLine();
        if (line != null && line.Contains(":"))
            Console.WriteLine(line.Split(':')[1]);
    }
}

What I'd like to know how to do is:
How can I extract a part of this line?

111033@@Item1@@21@@0@@37@@0@@0@@0@@0@@0@@0@@0@@1000

I want to get 111033,21,37,1000 and put it in a Textbox like this
textbox_1 = 111033 etc.

A: using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                while (!sr.EndOfStream)
                {
                    String line = sr.ReadLine();
                    if (line != null && line.Contains(":"))
                    {
                       line.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries)
                              .Where(x => !x.Any(c => char.IsLetter(c)))
                              .ToList()
                              .ForEach( (ln) => Console.WriteLine(ln) );

                    }
                }
            }

That will write all numbers to the console.Also you can make it shorter like this:
 line.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries)
     .Where(x => !x.Any(char.IsLetter))
     .ToList()
     .ForEach(Console.WriteLine);

A: I assume that the commercial at characters (@) are separators that separate the line into columns. If the parts you need are always in the same columns, you know their indexes. Therefore start by splitting the line at the separators and take the columns you are interested in:
string[] parts = line.Split('@');
textBox_1 = part[0]; // 111033
textBox_2 = part[4]; // 21
textbox_3 = part[8]; // 37
...

What do these lines represent? Since I don't know, I just take a person's address as an example (it is probably not the case here, but this is not important).
Create a class that can store your objects. (I did not include validity tests for the sake of simplicity.)
public class Address
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }

    public static Addess FromLine(string line)
    {
        var a = new Address();

        string[] parts = line.Split('@');

        a.ID = Int32.Parse(parts[0]);
        a.FirstName = parts[3];
        a.LastName = parts[4];
        a.City = parts[8];
        return a;
    }

    public override string ToString()
    {
        return String.Format("{0} {1}, {3}", FirstName, LastName, City);
    }
}

Now you can add these objects to the combo box. They will automatically be displayed according to the ToString method. You can get the selected item with
Address a = (Address)myComboBox.SelectedItem;

You can fill the combo box like this
var items = new List<Address>();
while (!sr.EndOfStream) {
    string line = sr.ReadLine();
    if (line != null && line.Contains("@")) {
        Address a = Address.FromLine(line);
        items.Add(a);
    }
}
myComboBox.DataSource = items;


text:
Q: Kinematics in polar coordinates Take a particle in polar coordinate system to follow the equations:
$$\theta=\omega t$$
and $$r=r_oe^{-\omega t}$$
Now, the radial acceleration will be-
$$a_r=\ddot{r}-r\dot \theta^2$$ which we get as $0$.
This means that the particle's radial speed is constant.
But we see that $\dot r$ is $-r_o\omega e^{-\omega t}$ which is time dependent? Then how is the radial acceleration zero? I am obviously missing something simple but I'm just not getting what.

A: It is indeed correct that the radial acceleration,
$a_r = 0.$ Your mistake is in thinking that $\dot{r}$ is the only contributing factor to $a_r$, whereas from the very formula you have cited for $a_r$, it is not: there is a $-r\dot{\theta}^2$ term as well.
In other words, looking at $\dot{r}$ is not sufficient to infer $a_r$. Use the correct formula for the radial acceleration, and you get $0$ once again.


text:
Q: Adding a meta box to determine the sidebar I was trying to customize my WordPress, and I have added some custom meta boxes (it adds custom field) to add values in it, but I don't know how to do this one...
I want to a Meta Box, which will be a drop down menu. The value of this metabox will determine which sidebar to use in the post. Here's the picture:

A: Install metabox plugin and active:
/**** Add this code in your function.php ****/

$meta_boxes[] = array(
    'id' => 'post_sidebar',
    'title' => 'post Sidebar',
    'pages' => array('post'),
    'priority' => 'low',
    'fields' => array(
            array(
                'name' => 'Post Sidebar',
                 'id' => 'post_sidebar',
                 'type' => 'select',
                 "options" => array( "0" => "OFF", "1" => "Left side", "2" => "Right Side"),
            ),
        )
);
if ( class_exists( 'RW_Meta_Box' ) )
{
    foreach ( $meta_boxes as $meta_box )
    {
        new RW_Meta_Box( $meta_box );
    }
}

/**** after single.php on get value using this one option ****/

$sidebar_value = get_post_meta($post->ID,'post_sidebar',true);

if($sidebar_value == 1 && $sidebar_value!=0){
    // Add sidebar code for left side
}

if($sidebar_value=='2' && $sidebar_value!=0){
    // Add sidebar code for right side
}


text:
Q: How to insert nvarchar value in a query string I have a query string which is
   var projectid = sqlConn.Query<int>("insert into project (name,customer_id, service_id,user_id) values (@name,@customerid,@serviceid,@userid);SELECT SCOPE_IDENTITY(); ", new { name = Name, customerid = Customer, serviceid = Service, userid = userId }).Single();

where name is a nvarchar field. Now I know I need to use 'N' character and I have tried the followings
'N@name'
N'@name'

but it doesn't seem to work. Can anyone help me with this please?

A: You don't need to use N prefix with variables.
It is needed only with explicitly typed strings (string constants) like insert into ... values(N'some text', ...)
If your name variable contains unicode string - then no special actions are required.


text:
Q: Calling a class with symbolic name EDIT: I would like to implement it with Jekyll, which (as far as I know) does not have PHP, jQuery, and so on...

I have a simple problem with CSS; it must have a simple solution but I just don't find it.
Suppose one has multiple divs with some classes:

...

and in a .css we want to style these 'pet' divs; the style is very similar from class to class (for instance we have some photos cat.jpg, dog.jpg... and want to show them). Can this be achieved by a somewhat symbolic method? Something like
div.pet{
    width: 50px;
    height: 50px;
    background: url("/pictures/pet.jpg") no-repeat 0 0;
    ...

(but there is no class="pet" nor pet.jpg)

A: I would use sass:
div {
  $list: "cat", "dog", "frog";
  // generate classes for list elements
  @each $element in $list {
    &.#{$element} {
    background-image: url('images/#{$element}.jpg');
      }
    }
  }

A: It isn't possible to add different images sources to the image tags with pure CSS. You may need to use JS, JQuery, PHP , etc.
You may do this using JavaScript/JQuery as follows :
Store all the image names in an array and then run a loop on-load(of page) to get images by using those array element(values).
Using jQuery, you may set img source like this:
$("img:nth-child(i)").attr('src', <new path from array[i th element]>);

The nth-child(i) means ith image.
Using Js, you may do this:
var images = [
    'path/to/image1.png',
    'path/to/image2.png',
    'path/to/image3.png',
    'path/to/image4.png',
    'path/to/image5.png'
];

function loadImages(imgArr, targetId){
    for(var i=0; i< imgArr.length; i++) {
        console.log(imgArr[i]);
        var img = new Image();
            img.src = imgArr[i];
        document.getElementById('output').appendChild(img);
    }
}

loadImages(images);

You can also invode the loadImage() function from yout button:
<button onclick="loadImages(images)">Start</button>

Refer : JavaScript load Images in an Array

A: Im not sure what your asking But as far as I understand you want to have some global setting for div elements and change the background image:
https://jsfiddle.net/shtjab2k/
Css
     #pets > div
  {
    width:100px;
    height:40px;
    border:2px solid black;
    float:left;
  }

  .cat
  {
    background-image: url("https://i.vimeocdn.com/portrait/58832_300x300.jpg");
  }
  .bird
  {
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/2000px-Solid_blue.svg.png");
  }

html

A: That's not something you can do with CSS. CSS can only style objects and can't make other changes/additions/deletions of DOM objects.
But it is definitely something you can do with jQuery! If you know that you always have a class name class="cat" that is the same as the file name cat.jpg, you can do something like this:
$("div").each(function(){
   var petClass = this.attr('class');
   var petImg = petClass + ".jpg";
   this.append("");
});

A: The simplest, pure-css way to do this is this:
.dog, .cat, .bird, .snake {
  width: 50px;
  height: 50px;
  background: url("/pictures/pet.jpg") no-repeat 0 0;
}

It doesn't matter that the background we provide doesn't exist, we'll replace it in the css for individual pet types:
.dog {
  background-image: url("/pictures/dog.jpg");
}

It seems like you're looking for a way to do this in a single ruleset, which, unfortunately, is not possible. For that, you'd have to look into using Javascript or a CSS superset (see other answers on this post).
Otherwise, you can just write a couple more lines of css and set the background image for each pet type. =P


text:
Q: Is there a regex to grab all spaces that separate key value pairs Is there a regex to extract all spaces that separate key+value pairs and ignoring those delimited by double quotes
sample:
key1=value1 key1=value1 spaces="some spaces in text" nested1="key2=value2 key2=value2 key2=value2"  nested2="key2=value2, key2=value2, key2=value2" quoted="his name is \"no body\""

this is where i come for so far: (?<!,) (?=\w+=), but of course it doesn't work.

A: [^\s="]+\s*=\s*(?:"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^\s=]+)\K[ \t]+
PCRE demo
No need to write back. just matches space delimiters.
can replace with new delimiter

([^\s="]+\s*=\s*(?:"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^\s=]+))([ \t]+)
Python demo
Can write back \1 or \2 if needed.
can replace with new delimiter

note - the part of the above expressions matching the field info
could benifit by placing Atomic group around (?>) but not strictly
necessary as the field structure is fairly concise.
are other options to garantee integrity as well like matching every
character with the use of the \G anchor if availibul.
let me know if need this approach.
many ways to go here

A: Here is another option:
".*?(?<!\\)"(*SKIP)(*F)| +

See the online demo
Please do let me know if it actually does what is required as I'm unsure. Anyways, here is a breakdown:

*

*" - A literal double quote.

*.*? - Anything but newline zero or more times but lazy.

*(?<!\\) - A negative lookbehind for \.

*" - A literal double quote.

*(*SKIP)(*F) - Consume all characters of matches, force a failure and continue matching.

*| - Alternation.

* + - One or more space characters.

If it's Python you are using, you'll need a reference to the PypI regex module.

A: You could do that with the following PCRE-compatible regular expression.
\G[^" \n]*(?:(?<!\\)"(?:[^\n"]|(?<=\\)")*(?<!\\)"[^" \n]*)*\K +

Start your engine!
\G           : assert position at the end of the previous match
               or the start of the string for the first match
[^" \n]*     : match 0+ chars other than those in char class
(?:          : begin non-capture group
  (?<!\\)    : use negative lookbehind to assert next char is not
               preceded by a backslash
  "          : match double-quote
  (?:        : begin non-capture group
    [^"\n]   : match a char other than those in char class
    |        : or
    (?<=\\)  : use positive lookbehind to assert next char is
               preceded by a backslash
    "        : match double-quote
  )          :end non-capture group
  *          : match non-capture group 0+ times
  (?<!\\)    : use negative lookbehind to assert next char is not
  "          : match double-quote
  [^" \n]*   : match 0+ chars other than those in char class
)            : end non-capture group
*            : match non-capture group 0+ times
\K           : forget everything matched so far and reset start of match
\ +          : match 1+ spaces


text:
Q: How can I find the value of an unnamed JSON object? (org.json) (java) [Java 17 using the org.json parsing library. Not able to switch to Gson because I've written an insane amount of code in org.json :/ ]
Hello!
I am using an API in Java with the org.json JSON parsing library. I need to get the value of an unnamed JSON object in an array.
{
  "lorem": [
   { // this object needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   },
   { // this object also needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   },
   { // this object needs to be retrieved
     "ipsum":"dolor",
     "sit":"amet",
     "consectetur":"adipiscing"
   }
  ]
}

Note that the entire JSON file is NOT an array, there is just one JSON array inside of a JSON object. How would I be able to get the value of all of these unnamed fields inside of the array?
Thanks in advance for any help, and also sorry if this question has been asked before, I wasn't able to find anything on it when I searched for it on Stackoverflow.

A: Those objects aren't really unnamed objects, they are part of an JSON array. Because they are contained in an array, we can iterate through that array and we can retrieve every object by index.
Assuming that the we read the json provided above from a file:
public static void main(String[] args) throws FileNotFoundException {
    String resourceName = "src/main/resources/input.json";
    InputStream inputStream = new FileInputStream(resourceName);

    JSONTokener jsonTokener = new JSONTokener(inputStream);
    JSONObject jsonObject = new JSONObject(jsonTokener);

    // Get the array named lorem from the main object
    JSONArray jsonArray = jsonObject.getJSONArray("lorem");

    // Iterate through the array and get every element by index
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.getJSONObject(i);
        System.out.println("ipsum:" + object.get("ipsum"));
        System.out.println("sit:" + object.get("sit"));
        System.out.println("consectetur:" + object.get("consectetur"));
    }
}

Also, JSONObject  has a toList method, which returns a List<Object>.


text:
Q: Connect host to virtualbox virtually via usb I have Windows 7 and let's say I want to set up another Windows 7 in VirtualBox. Is there a way to somehow connect both the host and VirtualBox client via a virtual USB or something without any cables etc.?

A: The Virtualbox manual explains in considerable detail how to use Shared folders.
Windows 7 allows folders to be shared over the network.  Virtualbox guest and host to be on the same subnet via Bridged adapters.
USB would seem to be a really hard way of approaching the problem.
Good luck.


text:
Q: Angular: Run JS code when include finished loading image What I want is to show loading animation while image is loading.
Basically I have large system and all code bits are injected using ngInclude.
So if I have to construct the bit I'm interested in it would look like:

        <ng-include src="htmlInclude" />

And htmlInclude html for example would just be a div with img.
The htmlInclude changes when I click different posts I have.
So far I loaded low quality images so loading wasn't an issue - it was quick. Now I want to load high-quality images and their loading takes a while.
So all my included html (text, buttons etc) is loaded, and the image gets replaced after a few moments.
I tried to fiddle with different events I found in other questions, but they don't seem to be working for me. Either the loading doesn't appear at all, or it appears and stays there even after loading is complete.
Some stuff I tried is:
$scope.$on('$includeContentLoaded', function () {
    $scope.isLoadingPreview = false ;
});

or
$scope.$on('$viewContentLoaded', function() {
    $scope.isLoadingPreview = false ;
});

How can I make this happen?
Thanks!


text:
Q: C++ How can I iterate till the end of a dynamic array? suppose I declare a dynamic array like
int *dynArray = new int [1];

which is initialized with an unknown amount of int values at some point.
How would I iterate till the end of my array of unknown size?
Also, if it read a blank space would its corresponding position in the array end up junked?
Copying Input From users post below:
Thing is:
a) I'm not allowed to use STL (means: no )
b) I want to decompose a string into its characters and store them. So far I wanted to use a function like this:
 string breakLine (string line){

         int lineSize = line.size();

         const char *aux;

         aux=line.data();

         int index=0;

         while (index<=lineSize){
         mySynonyms[index]=aux[index];

         index++;
         }

I thought that the array aux would end up junked if there was a large blank space between the two numbers to be stored (apparently not). And I was wondering if there was a way to iterate till an undefined end in this type of array. Thanks for you answers.

A: No portable way of doing this. Either pass the size together with the array, or, better, use a standard container such as std::vector

A: Short answer is that you can't.  If you have a pointer to the first element of an array, you can't know what the size of the array is.  Why do you want to use a array in the first place.  You would be much better off using a std::vector if your array can change size dynamically, or a boost::Array if it will be a fixed size.
I don't understand your second question.

A: You don't: wrap the array into a structure that remembers its length: std::vector.
std::vector v(1);
std::for_each( v.begin(), v.end(), ... );

A: Your code needs to keep to track of the array, so the size would never be unknown. (Or you would have to use some library with code that does this.)
I don't understand the last part of your quesiton. Could you elaborate?

A: You explained in your post below that you want to look at the guts of a std::string.
If you are expecting your stirng to be like a c-string (aka doesn't contain NULLs), then use line.c_str() instead of line.data(). This will guarantee that aux points to a null terminates c-style string.
After that you can iterate until aux[index] == '\0';
Otherwise, you can use line.data() and string.length/size to get it's size like in your example.
However, "decomposing a string into its characters" is pretty pointless, a string is an array of characters. Just make of copy of the string and store that. You are allowed to do:
char ch = line[index];

Better yet, use iterators on the original string!
for(std::string::const_iterator it = line.begin(); it != line.end(); ++it) {
    const char ch = *it;
    // do whatever with ch
}

A:
a) I'm not allowed to use STL (means:
  no )

What??  Who's moronic idea was that?
std::vector isn't part of the "STL" (which is a copyrighted product of HP), but is (and has been for nearly a decade) part of the C++ Language Standard.

A: If you're not allowed to use the STL (for whatever reason), the first thing you want to do is actually to implement your own version of it – at least the parts you need, with the level of customizability you need. For example, it's probably overkill to make your own vector class parametrizable with a custom allocator. But nevertheless do implement your own lightweight vector. Everything else will result in a bad, hardly maintainable solution.

A: This smells like homework, and the teacher's objective is to give you a feeling of what it takes to implement dynamic arrays. So far you're getting an F.
You need to realize that when you allocate memory like this
int *dynArray = new int [1];

you allocate precisely one integer, not an indefinite number of integers to be expanded by some unidentified magic. Most importantly, you can only say
dynArray[0] = 78;

but you cannot say
dynArray[1] = 8973;

The element at index 1 does not exist, you're stepping into memory that was not reserved for you. This particular violation will result in a crash later on, when you deallocate the array, because the memory where you stored 8973 belongs to the heap management data structures, and you corrupted your heap.
As many other responders mention, you must know how many elements you have in the array at all times. So, you have to do something along the lines of
int arraySize = 1;
int *dynArray = new int [arraySize];

arraySize goes together with the array, and is best combined with dynArray in one C++ object.
Now, before you assign to dynarray[1], you have to re-allocate the array:
if (index > arraySize) {
  int newSize = index+1;
  int *newArray = new int[newSize]
  // don't forget to copy the data from old array to new
  memcpy(newarray dynArray, sizeof *newArray * arraySize);
  arraySize = newSize;
  dynArray = newArray;
}
// now you're ready!
dynArray[index] = value;

Now, if you want to make it a bit more efficient, you allocate more than you need, so you don't have to allocate each time you add an element. I'll leave this as an exercise to the reader.
And after doing all this, you get to submit your homework and you get to appreciate the humble std::vector that does all of this for you, plus a lot more.

A: Use a vector, which has a vector.size() function that returns an integer and a vector.end() function that returns an iterator.

A: You could create a simple Vector class that has only the methods you need. I actually had to recreate the Vector class for a class that I took this year, it's not very difficult.

A: If there's a value that cannot be valid, you can use that as a sentinel, and make sure all of your arrays are terminated with that.  Of course, it's error-prone and will cause hard-to-find bugs when you happen to miss doing it once, but that's what we used to do while reading files in FORTRAN (back in the all-caps days, and before END= became standard).
Yes, I'm dating myself.


text:
Q: Show and Hide using hasClass not working I am trying to make button that show some stuff and then when its clicked again it hide that stuff. I have two buttons (.BB11 and .BB12). Clicked button take .OnBotMenu class to change its apperance. #Cont11 is the stuff i show. .Showing class makes that stuff visible.
$(".BB11").click(function(){

    if $(this).hasClass(".OnBotMenu") {

        $(".Showing").fadeOut(500);

    }

    else {

        $(".BB11").addClass(".OnBotMenu");
        $(".BB12").removeClass(".OnBotMenu");
        $("#Cont11").fadeIn(1000);
        $("#Cont11").addClass(".Showing");

    }
});

A: (Posted on behalf of the OP).
Working code:
$(".BB11").click(function(){

    if ($(this).hasClass("OnBotMenu")) {

        $(".Showing").fadeOut(500);
        $(this).removeClass("OnBotMenu");

    }

    else {

        $(".Showing").fadeOut(500);
        $(".BB11").addClass("OnBotMenu");
        $(".BB12").removeClass("OnBotMenu");
        $("#Cont11").fadeIn(1000);
        $("#Cont11").addClass("Showing");

    }
});

A: Use $("#div2").fadeToggle("slow"); for showing and hiding elements with fade effect.
Example is here


text:
Q: Configuration.cs file asp.net 5 mvc I am trying to create project on ASP.NET 5 MVC, so I want to add superuser to my db. In ASP.NET 4 MVC I had Configuration.cs file in my migration folder and I use this code to create superuser in Seed method:
namespace WebApp.Migrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using WebApp.Models;

internal sealed class Configuration : DbMigrationsConfiguration<WebApp.Models.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        // AutomaticMigrationsEnabled = true;
        // AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(WebApp.Models.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        var user = new ApplicationUser()
        {
            UserName = "***",
            Email = "***",
            Guid="0",
            EmailConfirmed = true
        };

        manager.Create(user, "***");

        if (roleManager.Roles.Count() == 0)
        {
            roleManager.Create(new IdentityRole { Name = "admin" });
        }

        var adminUser = manager.FindByName("***");

        manager.AddToRoles(adminUser.Id, new string[] { "admin" });
    }
  }
}

But I can't find the same file in my new project.

Can some1 help me? Thx.

A: I assume you use ASP.net 5 default template which uses ASP.NET MVC6 and Entity Framework 7. From your screenshot I can see you have a snapshot.cs file which was only introduced in EF7.
A seed configuration option  hasn't been added to Entity Framework 7 yet (Beta 8) so as a workaround you'll have to create your own Seed Data class  and run it at your app's start-up.
To determine if you should seed it in your database you can run Linq's Any() method to determine if the table is empty or use your own EF logic instead.
e.g.
public class DbSeedData
{
    private MyDb _context;

    public DbSeedData(MyDb db)
    {
        _context = db;
    }

    public void EnsureSeedData()
    {
        if (!_context.Entities.Any())
        {
            {
                _context.Entities.Add(
                    new Entity{EntityName="blabla" },
                    new Entity{EntityName="blabla2" }
                 )
            }
        }
    }

Then in your Startup.cs
Add toConfigureServices
services.AddTransient<DbSeedData>();

Add to Configure method  the DBSeedData class as a parameter e.g.
public void Configure(IApplicationBuilder app, DbSeedData seeder, IHostingEnvironment env, ILoggerFactory loggerFactory)

At the end of this method add:
seeder.EnsureSeedData();

A: I can't speak for MVC6, like firste was talking about, but in MVC5 it is possible to do the same thing.
In my case, i don't know if it created the configuration.cs file when it enabled migrations or at another point.  However, even if there isn't, you should still be able to create one.
In my project, it created this base code:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using WebSiteName.Models;
using System;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;

namespace WebSiteName.Migrations
{
    internal sealed class Configuration : DbMigrationsConfiguration<WebSiteName.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(WebSiteName.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            // Linq Method
            /*
             * var passwordHash = new PasswordHasher();
             * string password = passwordHash.HashPassword("Password@123");
             * context.Users.AddOrUpdate(u => u.UserName,
             *   new ApplicationUser
             *   {
             *       UserName = "Steve@Steve.com",
             *       PasswordHash=password,
             *       PhoneNumber = "08869879"
             *
             *   });
             */
        }
    }
}

This is from the MVC5 template/w auth from VS2013 Community, just FYI.  This looks like the same code you use, but this works fine in mine and you should be able to copy either code over to your MVC5 project.  I left the linq comments in for you, in case it helps anyone else.


text:
Q: Mocking class attributes and methods with Python and Pytest I'm trying to Mock a class using pytest-mock but I don't quite understand how to do it, even after reading articles everywhere.
The thing is I have a class called Model which one of the attributes returns a list of other elements of different objects inside the model Line, Square, Circle, etc. The Model is generated by reading a huge file and it will be used in many places throughout the application, so I turned into mocking it, because in this phase I just want to check if it works as expected.
I'm using pytest-mock, but it's not very clear for me. I've tried:
def test_parse_find_elements_by_name(parser, mocker):

    def mock_objects(self):
        return ["a","b","c"]

    model = Model()
    mocker.patch(
        "orcaflow.Model.objects",
        mock_objects
    )

    assert model.objects == ["a", "b", "c"]

But it returns a method, not an attribute (with the @property decorator). A work around was to use the mock package by itself:
@pytest.fixture
def mocked_model(mocker):
    objects = []
    for i in range(10):
        obj = MagicMock()
        obj.name = "Line %d" % i
        objects.append(obj)

    model = Mock(objects = objects )
    return model

Is there a way to do it directly with pytest-mock or some way smarter to do it?


text:
Q: Using Recursion to Reverse a String I am trying to reverse a String word by word using recursion. (Ex: "Hello my friend" is reversed to "friend my Hello") This is the code I have attempted to write for this method. I have tried multiple similar variations but the output is only ever the first or last word of the String. I believe the part that is "broken" is the first if statement, but I am not quite sure.
public static String reverse (String words) {
   Scanner sc = new Scanner(words);
   String backwards = "";

   if (sc.hasNext()) {
     String currentWord = sc.next();
     reverse(sc.nextLine());
     backwards = backwards + " " + currentWord;
   } //end if
   else {
     backwards = words;
   } //end else

   return backwards;
 }

I am aware that a few similar questions exist, but their answers have not seemed to help me understand my mistake(s).
Thanks!

A: You shouldn't call nextLine() because your input is all on one line. Your logic is much clearer if you begin by creating a simple helper method, it should take an array of words and a position; from there you can recursively build your desired output with something like
private static String reverse(String[] words, int p) {
    if (p + 1 < words.length) {
        return reverse(words, p + 1) + " " + words[p];
    } else if (p < words.length) {
        return words[p];
    }
    return "";
}

Then your public method is easy to implement, just split the original input on white space and call reverse starting at 0 (remembering to return the result). Like,
public static String reverse(String words) {
    return reverse(words.split("\\s+"), 0);
}

And then, I tested it like
public static void main(String[] args) {
    System.out.println(reverse("Hello my friend"));
}

Which outputs (as requested)
friend my Hello

Alternatively, you could make that helper take your Scanner instead like
private static String reverse(Scanner sc) {
    if (sc.hasNext()) {
        String currentWord = sc.next();
        if (sc.hasNext()) {
            return reverse(sc) + " " + currentWord;
        }
        return currentWord;
    }
    return "";
}

And then your public method is
public static String reverse(String words) {
    return reverse(new Scanner(words));
}

A: Instead of using a Scanner, you can make use of an overload of String.split to split words around the first space:
public static String reverse(String words) {
    String[] wordArr = words.split(" ", 2); // split into a maximum of 2 Strings

    if (wordArr.length > 1) { // If there is more than 1 word
        // return the first word (wordArr[0]),
        // behind the reverse of the rest of the String (wordArr[1])
        return reverse(wordArr[1]) + " " + wordArr[0];
    }

    return wordArr[0]; // else, just return the one word
}

A: public static String reverseSentence(String sentence) {

    StringBuilder sb = new StringBuilder();

    int firstSpace = sentence.indexOf(' ');
    if (firstSpace == -1) {
        return sb.append(sentence.strip()).append(" ").toString();
    }
    String secondPart = sentence.substring(firstSpace + 1);
    String firstPart = sentence.substring(0, firstSpace);//similar to merger sort
    return sb.append(reverseSentence(secondPart)).append(reverseSentence(firstPart)).toString();
}

A: As stated in the comments, you could use a StringBuilder instead of Scanner class.
This example sends the same words, splits them by spaces each time you enter the method and you send the index of the word to be added in the next iteration.
For example:
public class RecursiveReverse {

    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        String stringToReverse = "Hello my friend!";
        System.out.println(reverse(stringToReverse, stringToReverse.split(" ").length - 1));
    }

    public static String reverse(String words, int i) {
        if (i >= 0) { //If the index of the words is greater or equals the first word
            sb.append(words.split(" ")[i]); //We split it and append it to our StringBuilder
            sb.append(" "); //We append a space
            reverse(words, --i); //We do this again
        }
        return sb.toString(); //When the above condition doesn't match we return the StringBuilder object as a String (which contains the words reversed)
    }
}

Which produces this output:
friend! my Hello

A better method would be passing a String array as parameter so you split only once (when sending the words as an array to the method) the String.
public class RecursiveReverse {

    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        String stringToReverse = "Hello my friend!";
        String words[] = stringToReverse.split(" ");
        System.out.println(reverse(words, words.length - 1));
    }

    public static String reverse(String words[], int i) {
        if (i >= 0) {
            sb.append(words[i]);
            sb.append(" ");
            reverse(words, --i);
        }
        return sb.toString();
    }
}

A: You throw away the recursion results:
 reverse(sc.nextLine());
 backwards = backwards + " " + currentWord;

Instead, use this:
 backwards = reverse(sc.nextLine());
 backwards = backwards + " " + currentWord;

Better yet:
 backwards = reverse(sc.nextLine()) + " " + currentWord;

A: Do you must use recursion? You can do that without it.
public static String reverse(String words) {
    String[] list = words.split(" ");
    Collections.reverse(list);
    String reversed = String.join(" ", list);
    return reversed;
}

A: You must keep  hold of the extracted words between calls in an accumulator. Here is an example.
public static String reverse(String words, String acc){
    Scanner sc = new Scanner(words);

    if(!sc.hasNext()){
        return acc;
    }

    return reverse(sc.nextLine(), acc) + " " + sc.next();
}

You would call it like this.
reverse("Hello my friend", "");

It's not the most efficient implementation in the world, but yeah... It must work!
If you want a more efficient one, use a StringBuilder as the accumulator.


text:
Q: Image sometimes does not display in HTML page (Django 3.0) I created a somewhat clone of Instagram main page (for full transparency, please know that I do this for a psychological experiment).
One of my users got a very strange bug : when going on my page, two images seemed to not be loaded (there was no broken link, and the images simply appeared to be skipped, see illustration below).
Images not displaying illustration
On reloading the page, the images indeed appeared normally, and other users did not get any bug.
The thing is, I do not quite understand how this could happen, since I show the page only when all resources are loaded, through these lines of code :
window.addEventListener('load', function () {
    document.getElementById("main-page").style.visibility = "visible";
});

Please find the code for the page below (I removed navbar code for lisibility, please let me know if full version is needed).

                {% include 'instapp/status.html' %}
                {% include 'instapp/post.html' %}

                {% include 'instapp/recommandations.html' %}

And here is the code for displaying a single post :
{% load static %}

{{instapost.pseudo}}

            {% include 'instapp/post_icons.html' %}

{{instapost.likes}} J'aime

{{instapost.pseudo}}  {{instapost.comment|safe}}

{{instapost.time}}

        <input type="text" class="comment-box" placeholder="Ajouter un commentaire">
        <button class="comment-btn">Publier</button>

Do you know what may cause this "bug" ?
I ran into a tutorial about detecting when images are all loaded (see here). Do you think this can improve my situation ? As you may expect, this bug is unfortunately hard to replicate.
Thanks for your help !
Best,
Jessica

A: Search settings.py into the project folder and create Variables like this.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATICFILES_DIRS = [
    BASE_DIR / "static"
]

STATIC_ROOT = 'mtg-django/static'


text:
Q: How can I move files to a directory using Node.JS? like so
► add language identifier to highlight code

```python
def function(foo):
    print(foo)

► put returns between paragraphs
► for linebreak add 2 spaces at end
► italic or bold
► indent code by 4 spaces
► backtick escapes like _so_
► quote by placing > at start of line
► to make links (use https whenever possible)
https://example.com
example
example

A: var fs = require('fs-extra');
var request = require('request');
fs.ensureDir('css');
request('http://agar.io/css/master.css').pipe(fs.createWriteStream('master.css'));
fs.move('master.css', 'css/master.css', function (err) {
  if (err)
      console.error(err);
});

A: You need to wait until the pipe ends to write into the stream before moving the file around.
You can try this:

var fs = require('fs-extra') // This imports the fs-extra dependency
var request = require('request') // This imports the request dependency

fs.ensureDirSync('css') // This creates a folder called css

var stream = request('http://agar.io/css/master.css').pipe(fs.createWriteStream('master.css')) // This downloads the master.css file

stream.on('end', function() {
        fs.move('master.css', 'css')
});

A: Try fs.move('master.css', 'css/master.css')


text:
Q: Asynchronous request in database There is a code:
<form name="step1" action="step2.php" method="POST">
Email: <input type="text" name="email" class="input-medium">
<button class="btn btn-small btn-warning" type="submit">Check</button>
</form>

And that:
step2.php
<?php
$email = $_POST['email'];
$result = mysql_query("SELECT email,discount FROM buyers WHERE email='$email'");
if (mysql_num_rows($result) <= 0)
{
echo "Are you a new client is't it?
";
echo "Your discount is 0%
";
}
else{
echo "
Nice to see you again!
";
$getSalary = mysql_fetch_array($result);
echo "You discount is already: ";
echo $getSalary[discount];
echo " %";
}
?>

So,  is it possible to get request in database without submit the form and redirect to new page (step2.php in this example)?
I mean, query result is shown immediately..
I think about onBlur() method, but I don't know how create similar request with JavaScript.
Maybe it is possible with AJAX?
I would be grateful for any advice. Thx a lot.

A: i guess this is what you want to achieve
<form name="step1" action="step2.php" method="POST" onsubmit = "return postFormAsynchronous(this)" >
Email: <input type="text" name="email" class="input-medium">
<button class="btn btn-small btn-warning" type="submit">Check</button>
</form>

then in javascript put this function
function postFormAsynchronous(frm) {
    frm = $(frm);
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data, status, xhr) {

       //your data from server will appear in data then do what ever with it

        }
    });

    return false;
}

this will make an ajax call to your given action php script with post  data email
on server you can carry on with your existing code
    $email = $_POST['email'];
      ........
      ......

oh yeah dont forget to include Jquery in your html page.
happy coding :)

A: Yes you can do either by calling ajax function on blur OR by validating submit, and do not submit the form until you have reponse from ajax.
For example when you click on submit, call function

onsubmit = "return Validate()"

In Validate function, send ajax request to different page, and do what you need on the basis of the value in your email field at the moment. You can get value of email field using either jquery or javascript.

     document.getElementById('email-field-id').value;

or

     $('#email-field-id').val();

A: in your

instead in your body

    <form name="step1" action="step2.php" method="POST" id="form">
        Email: <input type="text" name="email" class="input-medium">
        <button class="btn btn-small btn-warning" type="submit" on click = "jqAjaxForm('#form', 'step2.php','#target')">Check</button>
    </form>


text:
Q: How to build a subdomain from script In my project I have to make a subdomain, i.e
if the user name is XXX when he register, a sub domain will be created like XXX.example.com
how to do it?
I will use php for scripting.

A: This might be a little more complex than you think.
I suggest to do some reading on mod rewriting and htaccess.
You could start here:
htaccess Tutorial
Modrewrite tutorial
Subdomain Modrewrite Example
EDIT: Or just go with one of the nice examples provided my fellow SO users. ;)

A: I found a script that seems to do exactly that, create a subdomain on your server on demand.
It probably needs a little bit of tweaking for it to work on your particular control panel,  but the review are quite positive as far as I can tell.
Link
Have you considered using htaccess and url rewriting?
Found this code that may help you:
# Rewrite <subdomain>.example.com/<path> to example.com/<subdomain>/<path>
#
# Skip rewrite if no hostname or if subdomain is www
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain (%1), and first path element (%3), discard port number if present (%2)
RewriteCond %{HTTP_HOST}<>%{REQUEST_URI} ^([^.]+)\.example\.com(:80)?<>/([^/]*) [NC]
# Rewrite only when subdomain not equal to first path element (prevents mod_rewrite recursion)
RewriteCond %1<>%3 !^(.*)<>\1$ [NC]
# Rewrite to /subdomain/path
RewriteRule ^(.*) /%1/$1 [L]

Source (Post #6)

A: As long as this is for non-SSL sites, then by far the easiest way is not to bother - just use a wildcard DNS domain and vhost, then map any domain specific behaviours in your PHP code. If you need SSL sites then its a lot more complicated - you need to have a seperate IP address/port for each certificate - and woldcard certs can be very expensive.
If you're wanting to set up some sort of hosting package then its a bit more involved - how you go about this depends on what webserver and DNS server you are using.
Assuming (again no SSL) with Apache on Unix/POSIX/Linux and bind, then, again I'd go with a wildcard DNS entry, then:
1) create a base dir for the website, optionally populate this with a default set of files
2) add a vhost definition in its own file in /etc/httpd/conf.d named as XXX.conf
3) send a kill -HUP to the HTTPD process (causes it to read the new config files without having to do a full restart).
One thing to note is that you really shouldn't allow the httpd process direct write access to its own config files - you definitely don't want to give it root privileges. A safer solution would be to create a CLI script to perform this using the username as an argument then make it setuid and invoke it from the script run by the HTTPD process.
C.

A: the best way is to use a joker in your DNS server :
www.example.com.    IN  A   1.2.3.4
*.example.com.  IN  A   1.2.3.4

By this way, No subdomain has to be created : all are pointing to the same IP by default.
In your PHP code, you just have get $_SERVER["HOST"] and get the fist part :
$hostParts=explode('.',$_SERVER["HTTP_HOST"]);
$user=$hostParts[0]

A: First, you need to make sure you have a wildcard domain setup in DNS, and make sure your webserver (apache?) directs all queries for that wildcard domain to your php file.
Then in php you can look at $_SERVER["HTTP_HOST"] to see which subdomain is used for that particular request.

A: Since you will make sub-domains when an user registers.
Try this as .htaccess file:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^.htaccess$ - [f]

RewriteCond %{HTTP_HOST}!^www.domain.com
RewriteCond %{HTTP_HOST} ^([^.]+).domain.com
RewriteRule ^$(.*) /$1/%1 [L]

make a function of a controller which will take the value of sub-domain and display what necessary.
like::
public function show ($domain)
{
  **.**..*..**.** Your code goes here
}

when a user will try this xxx.domain.com/controller/show this will be domain.com/controller/show/xxx . if you want to xxx.domain.com to be domain.com/controller/show/xxx just edit the htaccess file as you want.


text:
Q: Error while creating autodesk forge viewer extension in angular I wrote an extension for the forge viewer (using angular) but its giving a runtime error saying Autodesk is not defined
export class MyExtension extends Autodesk.Viewing.Extension {

  public static extensionName: string = 'MyExtension';

  public load() {
    console.log('MyExtension loaded!');
    return true;
  }

  public unload() {
    console.log('MyExtension unloaded.');
    return true;
  }
}

I did an npm install @types/forge-viewer and am able to use Autodesk inside a class without any error, just not able to extend it. Does anyone know how to solve this?
Edit: This question seems to be similar to my problem, but I don't understand how the op created the Extension class or how its actually extending the Autodesk.Viewing.Extension since they didn't provide code for that. Using Forge Javascript-based Extension in Angular app

A: The @types/forge-viewer module only includes type definitions, not the actual Forge Viewer code. The viewer code is obtained from https://developer.api.autodesk.com, for example:

*

*https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.js, or

*https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js
This library must be loaded before you start defining your viewer extension classes.


text:
Q: NRules: Issue using DSL extension on Rule with custom base class I am using NRules to define rules that all inherit from a common base class, which itself inherits from Rule.
When I use a DSL extension to insert a new fact that wraps a matched object, it seems that the matched object passed to the extension method is null.
Here's a self-contained example that should demonstrate the problem. I am using the xUnit test framework to define two rules, each with identical tests. The first one passes, the second one fails.
using NRules;
using NRules.Fluent;
using NRules.Fluent.Dsl;
using Xunit;
using System.Linq;
using System.Reflection;

namespace IntegrationTests.Engine
{
    // A simple domain model
    public interface IFruit { }

    public class Apple : IFruit { }

    public class Basket
    {
        public Basket(IFruit apple)
        {
            MyApple = apple;
        }

        public IFruit MyApple { get; private set; }
    }

    // A base class for the rules
    public abstract class RuleBase : Rule
    {
        public override void Define()
        {
            // Empty
        }
    }

    // The first rule, which does not use the extension:
    public class TestRule : RuleBase
    {
        public override void Define()
        {
            base.Define();

            Apple a = null;
            When()
                .Match(() => a);

            Then()
                .Do(ctx => ctx.Insert(new Basket(a)));
        }
    }

    // The second rule, which uses an extension to add a new fact
    public class TestRuleWithExtension : RuleBase
    {
        public override void Define()
        {
            base.Define();

            Apple apple = null;
            When()
                .Match(() => apple);

            Then()
                .AddToBasket(apple);
        }
    }

    // The DSL extension
    public static class DslExtensions
    {
        public static IRightHandSideExpression AddToBasket(this IRightHandSideExpression rhs, IFruit fruit)
        {
            return rhs.Do(ctx => ctx.Insert(new Basket(fruit)));
        }
    }

    // The tests
    public class ExtensionTest
    {
        // This one tests the first rule and passes
        [Fact]
        public void TestInsert()
        {
            //Load rules
            var repository = new RuleRepository();
            repository.Load(x => x
                .From(Assembly.GetExecutingAssembly())
                .Where(rule => rule.Name.EndsWith("TestRule")));

            //Compile rules
            var factory = repository.Compile();

            //Create a working session
            var session = factory.CreateSession();

            //Load domain model
            var apple = new Apple();

            //Insert facts into rules engine's memory
            session.Insert(apple);

            //Start match/resolve/act cycle
            session.Fire();

            // Query for inserted facts
            var bananas = session.Query<Basket>().FirstOrDefault();

            // Assert that the rule has been applied
            Assert.Equal(apple, bananas.MyApple);
        }

        // This one tests the second rule, and fails
        [Fact]
        public void TestInsertWithExtension()
        {
            //Load rules
            var repository = new RuleRepository();
            repository.Load(x => x
                .From(Assembly.GetExecutingAssembly())
                .Where(rule => rule.Name.EndsWith("TestRuleWithExtension")));

            //Compile rules
            var factory = repository.Compile();

            //Create a working session
            var session = factory.CreateSession();

            //Load domain model
            var apple = new Apple();

            //Insert facts into rules engine's memory
            session.Insert(apple);

            //Start match/resolve/act cycle
            session.Fire();

            // Query for inserted facts
            var bananas = session.Query<Basket>().FirstOrDefault();

            // Assert that the rule has been applied
            Assert.Equal(apple, bananas.MyApple);
        }
    }
}

The question is why does the second rule with the DSL extension not work properly? Am I doing something wrong and how can I fix it?

A: First thing to note with the NRules DSL is what happens when you declare a match variable in a rule and bind to it:
Apple apple = null;
When()
    .Match(() => apple);

No value is actually ever assigned to this variable. It is captured as an expression tree, and its name is extracted, and used to later find other expressions referencing the same variable. The engine then replaces those references with the actual matched fact.
For instance:
Then()
    .Do(ctx => ctx.Insert(new Basket(apple)));

Here "apple" is the same apple variable form the When clause, so NRules recognizes that and correctly stitches the expressions together.
When you extracted an extension method, you named the variable "fruit":
public static IRightHandSideExpression AddToBasket(this IRightHandSideExpression rhs, IFruit fruit)
{
    return rhs.Do(ctx => ctx.Insert(new Basket(fruit)));
}

The engine no longer recognizes this as the same fact reference, since "fruit" and "apple" don't match.
So, fix #1 is to just name the variable the same way as the declaration:
public static class DslExtensions
{
    public static IRightHandSideExpression AddToBasket(this IRightHandSideExpression rhs, IFruit apple)
    {
        return rhs.Do(ctx => ctx.Insert(new Basket(apple)));
    }
}

Obviously this is not ideal, since you are relying on matching naming of variable.
Since NRules operates in terms of the expression trees, a better way to build a generic extension method would be to also write it in terms on expression trees, and no longer depend on the variable naming.
So, fix #2 is to write the extension method using lambda expressions.
public class TestRuleWithExtension : RuleBase
{
    public override void Define()
    {
        base.Define();

        Apple apple = null;
        When()
            .Match(() => apple);

        Then()
            .AddToBasket(() => apple);
    }
}

public static class DslExtensions
{
    public static IRightHandSideExpression AddToBasket(this IRightHandSideExpression rhs, Expression<Func<IFruit>> alias)
    {
        var context = Expression.Parameter(typeof(IContext), "ctx");

        var ctor = typeof(Basket).GetConstructor(new[] {typeof(IFruit)});
        var newBasket = Expression.New(ctor, alias.Body);

        var action = Expression.Lambda<Action<IContext>>(
            Expression.Call(context, nameof(IContext.Insert), null, newBasket),
            context);
        return rhs.Do(action);
    }
}

Note that AddToBasket(() => apple) now captures the lambda expression, which is later extracted and used in the implementation of the extension method. With some expression magic I then constructed a lambda expression equivalent to the one you had, but this time not relying on any specific variable naming.


text:
Q: oracle merge operation hangs (or loops); query tuner claims it's a cartesian product operation I have a Merge query (open to better suggestions) that seems to cause the server to hang.  (I'm not sure what it's doing, but it pegs the CPU and never completes)  When I run it through the query tuner, I'm told it's caused by "an expensive cartesian product operation was found at line ID 7 of the execution plan", and that I should "consider removing the disconnected table or view from this statement or add a join condition which refers to it."  The problem is, there is no disconnected table.
Here's the explain plan:
---------------------------------------------------------------------------------------------------
| Id  | Operation                         | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | MERGE STATEMENT                   |               |     1 |    18 |    75  (10)| 00:00:01 |
|   1 |  MERGE                            | CM_SSS_DETAIL |       |       |            |          |
|   2 |   VIEW                            |               |       |       |            |          |
|   3 |    SORT GROUP BY                  |               |     1 |  1352 |    75  (10)| 00:00:01 |
|   4 |     NESTED LOOPS                  |               |       |       |            |          |
|   5 |      NESTED LOOPS                 |               |     1 |  1352 |    74   (9)| 00:00:01 |
|   6 |       NESTED LOOPS                |               |     1 |  1328 |    73   (9)| 00:00:01 |
|   7 |        MERGE JOIN CARTESIAN       |               |     1 |  1306 |    72   (9)| 00:00:01 |
|   8 |         TABLE ACCESS FULL         | CM_SSS_DETAIL |     1 |  1274 |    18   (0)| 00:00:01 |
|   9 |         BUFFER SORT               |               | 12815 |   400K|    54  (12)| 00:00:01 |
|* 10 |          TABLE ACCESS FULL        | CI_CC         | 12815 |   400K|    54  (12)| 00:00:01 |
|  11 |        TABLE ACCESS BY INDEX ROWID| CI_CASE       |     4 |    88 |     1   (0)| 00:00:01 |
|* 12 |         INDEX RANGE SCAN          | XT220S1       |     6 |       |     1   (0)| 00:00:01 |
|* 13 |       INDEX RANGE SCAN            | XT222P0       |     1 |       |     1   (0)| 00:00:01 |
|* 14 |      TABLE ACCESS BY INDEX ROWID  | CI_CASE_CHAR  |     1 |    24 |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

10 - filter("CC"."CC_TYPE_CD"='1NAA-LTR' OR "CC"."CC_TYPE_CD"='1NEA-LTR' OR
"CC"."CC_TYPE_CD"='1NIP-LTR' OR "CC"."CC_TYPE_CD"='CBS-LTR' OR
"CC"."CC_TYPE_CD"='CBS1-LTR' OR "CC"."CC_TYPE_CD"='CBS2-LTR' OR
"CC"."CC_TYPE_CD"='DNAR-LTR' OR "CC"."CC_TYPE_CD"='INR-LTR' OR "CC"."CC_TYPE_CD"='IPL-LTR'
OR "CC"."CC_TYPE_CD"='SOFB-LTR')
12 - access("CC"."PER_ID"="C"."PER_ID")
13 - access("CHR"."CASE_ID"="C"."CASE_ID" AND "CHR"."CHAR_TYPE_CD"='OBLGID')
14 - filter("D"."SA_ID"="CHR"."CHAR_VAL_FK1")

-------------------------------------------------------------------------------

Here's my query:
MERGE INTO cm_sss_detail d
USING (
    SELECT chr.char_val_fk1, MIN(cc.cc_dttm) first_date
    FROM ci_case c
    JOIN ci_cc cc
        ON (cc.per_id = c.per_id)
    JOIN ci_case_char chr
        ON (chr.case_id = c.case_id)
    WHERE chr.char_type_cd = 'OBLGID'
        AND cc.cc_type_cd IN (  '1NAA-LTR','CBS1-LTR','CBS2-LTR','CBS-LTR',
                                'DNAR-LTR','IPL-LTR','INR-LTR','SOFB-LTR',
                                '1NEA-LTR','1NIP-LTR')
    GROUP BY chr.char_val_fk1
) b
ON (d.sa_id = b.char_val_fk1)
WHEN MATCHED THEN UPDATE
    SET d.fst_bill_date = b.first_date;

The cm_sss_detail table has an index on the sa_id column (it's also the PK).

A: According to the query plan, the optimizer expects that the MERGE statement is going to modify 1 row.  It appears to expect the Cartesian join to return a single row as well.  Based on the fact that the query isn't returning in a few milliseconds, that would generally imply that the statistics on one or more of the objects (tables or indexes) are substantially incorrect.  When was the last time statistics were gathered on these tables and their dependent indexes?  Has the actual data in the tables changed substantially since that time?


text:
Q: Display error message if inquiry not in mySQL databases I have this code in a cgi text file:
if inquiry == "Number":
    cursor.execute('SELECT * from NUMBER_INFO where NUMBER_ID = "%s";' %(inquiry))
    number_info = cursor.fetchall()
    number = number_info[0][1]

In essence a user inputs a value and it searches through my mysql database and outputs a value.
I was wondering how do I print an error message, such as the value is not in database, if whatever the user inputs is not found in the database?
All I know is that the mysql database returns empty set.

A: isn't it just
if not number_info:
    print "nothing's there"
else:
    number = number_info[0][1]

?


text:
Q: Undefined method [] in Ruby I am running Ruby 2.2.2 on Windows 7 Professional. I am trying to make a menu program that stores multiple menus in one array. I thought that I had succeeded, but I get the error message
Menu.rb:7:in 'block in load':undefined method '[]' for nil:NilClass (NoMethodError)

Here is my code:
#-Functions-#
def load(page)
    data = [["menu","Menu",[["obj1","Object 1",false],["exit","Exit",true]]],["obj1","Object 1",[["menu","Back",false],["exit","Exit",true]]],["exit","Exit",false]]
    itemNum = 0
    data.each do
        pageData = data[itemNum]
        if pageData[0] == page      #ErrorLine
            if pageData[2] == false
                send(page)
            else
                system "cls"
                puts
                puts " #{pageData[1]}"
                puts
                itemNum = 1
                pageData[2].each do
                    puts
                    puts "  #{itemNum}. #{pageData[2][itemNum-1][1]}"
                    itemNum += 1
                end
                puts
                puts
                print " Choice: "
                choice = gets.chomp.to_i
                load(pageData[choice-1][0])
            end
        end
        itemNum +=1
    end
end
def exit
    exit
end

#-Program-#
load("menu")

A: Your data array is set up with 3 elements, however if you log your program,
try this at the end of your each loop
data.each do
  ...
  itemNum +=1
  puts "itemNum is now #{itemNum}"
end

Run it and you will see that at some point "itemNum is now 4".
Hence at your line 7 pageData is nil, as data[4] element doesnt exist.


text:
Q: Почему defer не работает? Примитивный пример: Есть скрипт с алертом, подключенный вот так <script src="js.js" defer></script> с defer. При обновлении сперва появляется алерт и только потом контент страницы. Почему так ведь defer подразумевает сперва загружать содержимое страницы и только потом скрипт?

A: Скрипт с атрибутом defer выполняется не после отрисовки контента, а после окончания парсинга HTML, построения DOM и CSSOM. Ваш алёрт появляется потому, что к моменту его исполнения эти необходимые условия выполнены. Первый пэинт страницы происходит уже после.
defer нужен для того, чтобы не блокировать парсинг HTML и чтобы несколько идущих подряд скриптов выполнились в указанном порядке.

Вот вам пара статей на изучение: https://bitsofco.de/async-vs-defer/, https://bitsofco.de/understanding-the-critical-rendering-path/


text:
Q: JPQL query updating CollectionTable I have the following entity:
@Entity(name = "Directory")
@Table(name = "Directory")
public Directory {

@Id
@Column(name = "id")
protected String id;

@ElementCollection
@MapKeyColumn(name = "file")
@CollectionTable(name = "Directory_Files", joinColumns = @JoinColumn(name = "id"))
@Column(name = "hash")
protected Map<File, String> fileToHash;

...

}

The hash of a file of a directory should be updated using a JPQL query.
I have tried the following query but it's not working:
UPDATE Directory t SET t.Directory_Files.hash = :hash WHERE t.Directory_Files.id = :id AND t.Directory_Files.file = :file

Does anyone found the mistake in this query?
Any help is appreciated.

A: "Directory_Files" is a database table and doesn't exist in your object model, and so cannot be used in JPQ - You would need to access the fileToHash Map within Directory
Unfortunately JPQL bulk update statements define update Item to be:
update_item ::= [identification_variable.]{single_valued_embeddable_object_field.}*
{state_field | single_valued_object_field} = new_value
fileToHash is a collection and so cannot be used in an Update statement.
You will need to use an SQL query and pass it to EntityManager.createNativeQuery(sqlString)


text:
Q: LWC @wire change 'this' context I have a problem with my code
export default class PdmNewModalPlist extends LightningElement {
    @api objectName;
    @api fieldName;
    @api apiName;
    @api recordTypeId;
    @track obj;
    @wire(getPicklistValues, {
        recordTypeId:'$recordTypeId',
        fieldApiName: {
            fieldApiName: *this.fieldName*,
            objectApiName: *this.objectName*
        }
    })
    PicklistValues;
}

In marked places i want to call variables but that's don't work. Propably because 'this' context shows function not document. How i can change 'this' context or make this function works?

A: You want to use reactive variables:
    @wire(getPicklistValues, {
        recordTypeId:'$recordTypeId',
        fieldApiName: {
            fieldApiName: '$fieldName',
            objectApiName: '$objectName'
        }
    })
    PicklistValues;

You can read more in Understand the Wire Service.

A: 'This' context isn't a problem here, The main problem is an execution order. @Sfdcfox's solution won't work because values will be 'undefined'. The solution that works for me is creating an object in connectedCallback function and pass that object to @wire function
 connectedCallback(){
        this.obj = { fieldApiName: this.fieldName, objectApiName: this.objectName};
     }

 @wire(getPicklistValues, { recordTypeId:'$recordTypeId' , fieldApiName: '$obj' })
                                PicklistValues;


text:
Q: Do transferring energy and applying force to a body imply same? Do transferring energy and applying force to a body imply same meaning? When we say, "I throw a ball using my pushing force so on the other hand, can I say that I transferred my kinetic energy to the ball therefore it became moving.

A: No. In a uniform circular orbit the orbiting body maintains constant energy while a constant force, only changing in direction, operates on that body.
Kinetic energy changes when a net force is applied in the direction that an object is moving. It will reduce if the net force opposes velocity, or increase if net force supports velocity.

A: Yes. When you apply a net force to a mass (please note the word "net"), the object become accelerated . This acceleration means the body changes velocity, and a change in velocity means there is a change in the energy, because of the energy formula:

$E=\frac{1}{2}mV^2$

The case of the circle is particularly interesting, because there is a force applied but the energy does not change. This is the result of applying force to decrease the velocity of the mass in a direction (say the x axis, if the mass initially moves over the x axis) while at the same time you apply force to accelerate the same mass in a perpendicular direction (the y axis). This makes the velocity-energy to keep constant while you apply a centripetal force. You can check this by yourself by decomposing the centripetal force in its x-y components and calculating work done (and work done = energy). Or, you can check the demonstration.


text:
Q: ActiveRecord destroy - no exception I'm doing a destroy via ActiveRecord using a field. However, a record in the database with that field value does not exist. So, given this bit of debugging using pry:
[1] pry(main)> fieldvalue
=> "17785"
[2] pry(main)> person =  Person.where(:fieldname => fieldvalue.to_i)
=> []
[3] pry(main)> person
=> []
[4] pry(main)> person.destroy_all
=> []

...why does it not raise an exception at step 4?
The original bit of code, similarly, silently fails to raise an exception:

begin
      Person.where(:fieldname => fieldvalue.to_i).destroy_all
rescue ActiveRecord::RecordNotFound => exception
  @logger.info("ActiveRecord::RecordNotFound exception raised. Details: #{exception}")
rescue Exception => exception
  @logger.info("Unknown exception raised. Details: #{exception}")
else
  @logger.info("Destroying person with field value: #{fieldvalue}")
end

i.e. it just logs the "Destroying..." line each time it's run.

A: destroy_all does not raise an exception when executed on an empty set ([]) because the method, according to the documentation:

Destroys the records matching conditions by instantiating each record and calling its destroy method.

Because your where query is returning an empty set, there are no records to instantiate – destroy is never actually being executed on anything, hence there are no exceptions thrown.
Contrast this to a hypothetical situation wherein a set is returned that – for some unlikely reason – contained a nil object. The set might look something like this
people = Person.where("created_at < ?", Time.now)
#=> [#<Person id:1>, nil, #<Person id:2>] # for demonstration only; would not actually happen

people.destroy_all
#=> NoMethodError: undefined method `destroy' for nil:NilClass

A NoMethodError would be thrown on the second iteration of destroy_all, since destroy would be executed on nil, which does not have a destroy method.
One other thought: you may be conflating the where ActiveRecord method with the find method. where returns an ActiveRecord::Relation object, which effectively operates as an array of objects which match the passed conditions. find, in contrast, returns the first object itself_ which match the conditions passed. In the real world example from above, if you're seeking to return a single object from your query, it may make more sense to use find rather than where:
people = Person.where(:fieldname => fieldvalue.to_i) # returns a collection of all objects matching the condition
people.class
#=> ActiveRecord::Relation

person = Person.find(:fieldname => fieldvalue.to_i) # returns the FIRST object matching the condition
person.class
#=> Person


text:
Q: How to determine if SQL Server will not execute parts of the script in parallel? Are there any general rules or maybe easy way to tell if SQL script will execute in batches instead of "all at once"?
USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 5);
GO
DBCC SHRINKFILE (DataFile2, 5);
GO

Will it start shrinking DataFile2 only after DataFile1 has finished, or simultaneously?

A: GO

is a batch terminator in SSMS. Every time you have a GO (or a ;) you have told SQL Server that the batch just ended. So you are sending your commands in batches, and the batches are executed after another - not at the same time.
SO in this case they are all executed serially. Really anytime you run commands they are executed serially in one connection.
The bigger question in my mind is - Why are you doing Shrinkfile? I hope this isn't a production database? This is not a best practice operation to regularly be running at all, as this link describes.
Preview: Shrinking your data files shouldn't be needed - unless you just cleared a ton of space you'll never grow back into, are having serious disk capacity issues or are doing something in dev - and even in these situations, there may be alternatives that are better for you.
Shrinking means introducing index fragmentation. It means some expensive IO operations and there is a good chance you'll be growing back into the space eventually anyway if your database is still live and in use with inserts and updates.

A: so far i am not aware of any SQL command that can initiate two query/command execution at the same time or in parallel. regard less of the GO stmt. if you are running set of commands using t-sql in SSMS they are executed in order one after another. you can create 2 SQL JOBS and invoke each using individual t-sql command or schedual them a the same time. in case of t-sql invoking, immediately after invoking first job DB engine will go for second invoke it will not wait for that JOB to complete. but still operation of invoking each job will get executed in order.

A:
Will it start shrinking DataFile2 only after DataFile1 has finished, or simultaneously?

If executing these statements out-of-order is in question, it would also be prudent to ask when the statement USE UserDB will be executed...
In any event,

*

*Statements within a batch are executed serially (procedural logic), top-to-bottom

*Batches within a SSMS window/selection are executed serially (GO is the default batch separator), top-to-bottom

The only way to get multiple logical operations running in parallel is to somehow separate them onto different server connections. There are several ways to do this; off the top of my head, here are a few:

*

*Multiple SSMS windows (or a single window connected to multiple servers using Registered Servers or Central Management Servers)

*Multiple instances of sqlcmd

*SQL Agent job(s) (I don't say multiple for the case where you want to do the same thing multiple times in parallel)

*Service Broker with MAX_QUEUE_READERS set to a value greater than 1 (I believe this doesn't guarantee parallelism, but I'm mentioning it just because I thought of it)

Whether or not what you're attempting to do with this information is a good idea is a separate discussion which has been covered many times, so I'm not going to cover it here.


text:
Q: Reference for the sobolev space $H^{1/2}([0,1];\mathbb{R}^{n})$ I need a reference for the Sobolev space $H^{1/2}([0,1]; \mathbb{R}^{n})$. The article that I am reading says that this space consists of all $L^2$ curves $\gamma: [0,1] → R^n$ such that the coefficients $(x_k)_{k\in Z}$ of the Fourier decomposition
\begin{equation}
\gamma (t) = \displaystyle\sum_{k\in \mathbb{Z}}e^{-2\pi kJt}x_k,\;\; x_k \in \mathbb{R}^n
\end{equation}
satisfy
\begin{equation}
\displaystyle\sum_{k\in \mathbb{Z}} |k||x_k|^2 <\infty.
\end{equation}
If anyone knows a reference with this definition it would be perfect.
Thank you very much!


text:
Q: Oracle Active Session Pool Questions what is oracle active session pool? is it activated by default?
what is the default maximum active session that there is per user?

A: The Active Session Pool allows a limit to be place on the number of sessions that can be active on your instance. It is a part of the Resource Manager. The number possible is defined according to your current resource plan. The default plan allows an unlimited number of sessions. It is activated if resource management is performed in the instance. To find out if this is so then check the resource_manager_plan parameter:
show parameter resource_manager_plan

If there is a value then it is activated. You may see something like DEFAULT_PLAN as the VALUE. You can then query DBA_RSRC_PLAN_DIRECTIVES for the number of active sessions possible:
select GROUP_OR_SUBPLAN, ACTIVE_SESS_POOL_P1
  from DBA_RSRC_PLAN_DIRECTIVES
 where PLAN = 'DEFAULT_PLAN';

You'll get a few rows back relating to the number of groups/subplans that are part of this plan. NULL will indicate unlimited.
I prefer using Enterprise Manager to query and amend this. To find it in EM go to the Server tab then under the Resource Manager heading is Plans.
More information on the Resource Manager can be found here.


text:
Q: Getting values from Multilevel JSON I have a json below but I am struggling to get the values for the keys e.g. TransactionAmount and ReceiverPartyPublicName.
Kindly someone help. Thank you.
{
  "ResultType": "0",
  "ResultCode": "0",
  "TransactionID": "LIB76ANQYD",
  "ResultParameters": {
    "ResultParameter": [
      {
        "Key": "TransactionAmount",
        "Value": "750"
      },
      {
        "Key": "TransactionReceipt",
        "Value": "LIB76ANQYD"
      },
      {
        "Key": "ReceiverPartyPublicName",
        "Value": "345706611796 - PETER Parr"
      }
    ]
  },
  "ReferenceData": {
    "ReferenceItem": {
      "Key": "QueueURL",
      "Value": "http://xxxxxx"
    }
  }
}

A: You can use json_decode to iterate over your array checking for the correct Key then you've got the reference to the Value
Demo: https://3v4l.org/CaPWL
<?php

$json = <<<JSON
{
  "ResultType": "0",
  "ResultCode": "0",
  "TransactionID": "LIB76ANQYD",
  "ResultParameters": {
    "ResultParameter": [
      {
        "Key": "TransactionAmount",
        "Value": "750"
      },
      {
        "Key": "TransactionReceipt",
        "Value": "LIB76ANQYD"
      },
      {
        "Key": "ReceiverPartyPublicName",
        "Value": "345706611796 - PETER Parr"
      }
    ]
  },
  "ReferenceData": {
    "ReferenceItem": {
      "Key": "QueueURL",
      "Value": "http://xxxxxx"
    }
  }
}
JSON;

foreach (json_decode($json, true)['ResultParameters']['ResultParameter'] as $parameter) {
    if ($parameter['Key'] === 'TransactionAmount') {
        echo 'TransactionAmount: ' . $parameter['Value'] . PHP_EOL;
    }
    if ($parameter['Key'] === 'ReceiverPartyPublicName') {
        echo 'ReceiverPartyPublicName: ' . $parameter['Value'] . PHP_EOL;
    }
}


text:
Q: Ruby open interactive sub process within the shell I want to use ruby and in one moment open another program (cfdisk) and let the user interact with it, then return to my code
I can use
exec "cfdisk; ruby another.rb"
but that is very hacky and certainly not the right thing to do
I know about Open3 but i dont know how to use it properly for my usecase. I know that when I use capture3 on irb on Windows it says:

["Running under a virtual console, enabling 256/true-color support\n", "Screen size 28640x499 is not supported; limit 500x500.\nCheck the TERM environment variable.\n", #]

In Arch it opens it but the graphical output isnt present, the keystrokes are registered, they work (for example mc exits with F10) but the window isnt there, just blinking cursor.
parted exits immediately
Tried popen3 but I had no luck with it either

A: What is wrong with system for this case?

*

*The exec ruby command replaces the running process, so it will not return to your code.

*The Open3 library is used when you want to capture stdout and stderr.

Isn't this what you are looking for?
puts "here"
system "cfdisk"
puts 'there'

If you have some screen related issues, this is another issue that you might be able to resolve with different TERM value in the environment variable.


text:
Q: IncludeInvocationHeader not working with Start-Transcript I'm working with a script that parses out a Windows Powershell transcript. The script is dependent on the ...
**********************
Command start time: 20170426095605
**********************

...headers that appear in the transcript before each command when Start-Transcript is used with the -IncludeInvocationHeader switch.
However, now that I'm testing this script on a windows 7 and Windows 2012 (2012 ver. 6.2 build 9200) Start-Transcript is telling me -IncludeInvocationHeader is not valid.
PS C:\Users\Administrator> Start-Transcript -Path C:\Users\(snip)\PowerShell_transcript.txt -IncludeInvocationHeader
Start-Transcript : A parameter cannot be found that matches parameter name 'IncludeInvocationHeader'.
At line:1 char:91
+ ... pt.newfile.txt -IncludeInvocationHeader
+                    ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-Transcript], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StartTranscriptCommand

PS C:\Users\Administrator>

Was this a new addition? An outdated switch? Do I need to enable it somewhere?

A: It Looks like this is related to the Powershell version. The switch is not available in PSv3 or less. I believe it's available in v4. It is tested as available in v5.


text:
Q: How can I convert this SQL to Oracle format I need to issue a select statment to an oracle table as below:
SELECT
    T."Node"
FROM
    DW.KPX_PHYSICAL_MEMORY_DV T
where
    T."Node" like 'cigp%'
    AND  CAST((FROM_TZ(CAST(GET_UTC_TIMESTAMP(T."Timestamp", TMZDIFF) AS TIMESTAMP),'+00:00') AT TIME ZONE 'US/Eastern') as DATETIME)>='04-Jun-13 10.46.46.00'

I get invalid data type, I am very new to oracle. Can somebody tell me what I am doing wrong here?
Timestamp is type char and the values are like this:
1121004234558000
1121004234523000
1121004234550000
1121004234513000
1121004234559000

I need to convert the time stamp to human readable format and and select based on greater than a value.
I tried this sql query but does not seem like it is working, I get "invalid relational operator" error.
SELECT T."Node" as LPAR, CAST((FROM_TZ(CAST(GET_UTC_TIMESTAMP(T."Timestamp", TMZDIFF) AS TIMESTAMP),'+00:00') AT TIME ZONE 'US/Eastern') AS DATE) as TimeStamp,T."MAX_Memory_Size_MB",T."MIN_Comp_Memory",T."AVG_Comp_Memory", T."MAX_Comp_Memory", T."MIN_Non_Comp_Memory", T."AVG_Non_Comp_Memory", T."MAX_Non_Comp_Memory" FROM DW.KPX_PHYSICAL_MEMORY_HV T where T."Node" like 'server%'

and

CAST((FROM_TZ(CAST(GET_UTC_TIMESTAMP(T."Timestamp", TMZDIFF) AS TIMESTAMP),'+00:00') AT TIME ZONE 'US/Eastern') AS DATE) as TimeStamp > '04-Jun-2013 02:00:00 PM'


text:
Q: Future.timeout(Duration()) weird behavior in Flutter i'm trying to make Interactor with lifetime and with no care for result, so i create an abstract class :
abstract class Interactor<P> {
  Stream<callStatus> call(P params,
      {Duration timeoutMs = defaultTimeoutMs}) async* {
    try {
      yield callStarted();
      await doWork(params).timeout(timeoutMs, onTimeout: () => throw TimeoutException(""));
      yield callSuccess();
    } on Exception catch (e) {
      yield callError(e);
    }
  }

  @protected
  Future<void> doWork(P params);

  static const Duration defaultTimeoutMs = Duration(minutes: 5);
}

and each sub class can extend that and override the doWork() function :
class TestTimeOutInteractor extends Interactor<int> {
  @override
  Future doWork(int params, {timeoutMs: const Duration(seconds: 2)}) {
    return Future.delayed(Duration(seconds: 6));
  }
}

but there is no exception thrown the test wait for 6 second and return success.
the test :
test('fails timeout exception', () async {
      await expectLater(TestTimeOutInteractor()(1),
          emitsInOrder([callStarted(), callError(TimeoutException(""))]));
    });

output of test is
ERROR: Expected: should do the following in order:
          • emit an event that callStarted:<callStarted>
          • emit an event that callError:<callError>
  Actual: <Instance of '_ControllerStream<callStatus>'>
   Which: emitted • callStarted
                  • callSuccess
                  x Stream closed.
            which didn't emit an event that callError:<callError>


text:
Q: iPhone NavigationController Application I am following the tutorial here to use a UINavigationController to switch between ViewControllers.  If I download the code and follow the tutorial it works all fine and dandy, but when I try to apply this to different apps I encounter the following confusion/issue.  When I am in the "FirstViewController" how do I access [self navigationController] if I do not have any navigationController in my viewController class?  In this example, I cannot find out how or where the navigationController comes from in the FirstViewController.  Can someone please explain how this works?
**Note: The full source code for the entire project can be found on the page I linked to above as well.
This is the line that confuses me:
[[self navigationController] pushViewController:secondViewController   animated:YES];

This is the entire code for the viewController:
.h
#import <UIKit/UIKit.h>
@class SecondViewController;

@interface FirstViewController : UIViewController {

    IBOutlet SecondViewController *secondViewController;
}

@property(nonatomic, retain) SecondViewController *secondViewController;

- (IBAction)PressMe:(id)sender;

@end

.m
#import "FirstViewController.h"
#import "SecondViewController.h"

@implementation FirstViewController

@synthesize secondViewController;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"First View";
}

- (IBAction)PressMe:(id)sender
{
    [[self navigationController] pushViewController:secondViewController animated:YES]; //This line
}

- (void)dealloc {
    [super dealloc];
}

@end

A: From Apple's Documentation:

If the receiver or one of its ancestors is a child of a navigation controller, this property contains the owning navigation controller. This property is nil if the view controller is not embedded inside a navigation controller.

So you don't have to declare the navigation controller. If the current view controller was loaded onto a navigation controller then the line you are referencing will provide you with the current navigation controller

A: simply , you don't have any navigation controller, so you can't switch from view to another one with this
[[self navigationController] pushViewController:secondViewController   animated:YES];

create navigation controller object in your FirstView and use it to move between views
and in your PressMe method :
SecondViewController *secondView = [[secondView alloc] initWithNibName:@"SecondViewController" bundle:nil];
        [self.navigationController pushViewController:secondView animated:YES];
[secondView release];

A: If you are using IB (as you write in the code) right click the button, drag it to the SecondViewController and then select "Touch Up Inside"


text:
Q: Snowflake Query - How can I get an specific set of users with an specific kind of name (all this users have @domain) from all the users? I am starting with the Snowflake stuff and I would like to get all the users that contain the '@domain' as a name.
How can this be possible?
Im trying:
select * FROM users where name like '@domain';

However I am still getting all the users without any exception.
Any help or advise would be appreciated!

A: You need to use wildcards:
SELECT * FROM users WHERE name ILIKE '%@domain';


text:
Q: Парсер файлов Посоветуйте парсер для новичка, чтобы было просто разобрать и заменить переменные. Нужен парсер для файлов!
Мы имеем мой сайт1. Имеем сайт2. У сайта2 на сервере есть файлы. Нужно сделать так, чтобы у меня на сайте был поиск по их сайту. И трек с названием, которое мы вводим в поиске у меня, появлялся на сайте1. С инфой о весе, исполнителе и так далее.
A: Согласен с KoVadim) Нужен самописный парсер. ПО поводу регулярок - без них скорее точно никуда. Единственно если сайт правильно оформлени и можно работать с ним через DOM - что будет элегантнее и быстрее


text:
Q: Python missing argument Where is my fault
"this code is only part of my code
I just copied part of it"
import turtle

wn=turtle.Screen()
wn.bgcolor("black")
wn.title("Pacman")
wn.setup(900,700)
class Pacman(turtle.Turtle):
    def __init__(self):
        turtle.Turtle.__init__(self)
        self.shape("square")
        self.color("yellow")
        self.penup()
        self.speed(0)
    def up(self):
        self.goto(self.xcor(),self.ycor()+24)
    def down(self):
        self.goto(self.xcor(),self.ycor()-24)
    def left(self):
        self.goto(self.xcor()-24,self.ycor())
    def right(self):
        self.goto(self.xcor()+24,self.ycor())

wn.listen()
wn.onkey(Pacman.down, "Down")
wn.onkey(Pacman.up, "Up")
wn.onkey(Pacman.right, "Right")
wn.onkey(Pacman.left, "Left")
wn.tracer(0)

while True:
   wn.update()

Fail
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Programs\Python\Python37-
32\lib\tkinter\__init__.py", line 1702, in __call__

return self.func(*args)

File "C:\Users\asus\AppData\Local\Programs\Python\Python37-
32\lib\turtle.py", line 686, in eventfun

fun()
TypeError: up() missing 1 required positional argument: 'self'

When I click Right,Down,Up or Left Button square not moving and in console writing this fail

A: "Pacman" is a class template, so you can't call methods on it like that. You should either create a Pacman object (like so):
new_pacman = Pacman()

And then you could run your functions like so:
new_pacman.up()

Or (if I'm not mistaken) you could try this, which I think should also work:
Pacman().up() which

A: do pacman_instance = Pacman() right before wn.listen()
The issue is that you're trying to do an operation on a class rather than an instance of the class

A: If you just add Pacman = Pacman() before the line wn.listen(), it'll work!
The issue is you're trying to access a class that was not instantiated, and with this line you create this instance, and everything will work perfectly ;)


text:
Q: Wavefronts, refraction, and the marching soldiers analogy I am not a physicist, but rather a middle school science teacher. Please be gentle. The marching soldiers has been a really good analogy for explaining why a change of direction is caused by hitting the boundary of a new medium at a non-normal angle. In a pre-Covid time, you could actually have students do this in the classroom. Very fun. Except... what does the pole locking the marchers together represent?
Yes, it's a wavefront, but what makes that wavefront stay together in shape? I've never seen that explained. I think I understand that being in the same phase is what makes that surface of points a wavefront, but is this a descriptive definition or a prescriptive one? What keeps a wavefront together in the same shape, in perpetuity?
Suppose we are in a universe where change in direction does not happen passing through a new medium. We start the marching soldier analogy: Alice is connected to Bob by a pole, and Alice hits the slower medium first because they are approaching the medium-boundary at a non-normal angle. We would then say that holding the same pole as Alice makes Bob slow down too even though he's still in the faster medium because that is the only way to preserve direction— the thing we're observing in this supposed universe. We would just say that of the analogy: the pole does it, they're connected (sharing information about velocity?), so Bob slows down too. But why? Maybe the pole has some property that keeps it from turning, so Bob has to slow down too. Maybe in this universe, the definition of a wavefront— or whatever this universe calls the pole— is the set of all points where the wave stays in the same direction. That does not happen in our universe, so we don't have to answer that.
In our universe, it is still the analogical pole that does it. (Is it possible that saying the "pole does it" is doing too much work in my understanding? Where are the cause and effect happening in the real world as opposed to the analogy?) In our universe, a wavefront is the set of all points in a wave that is at the same phase. Okay. Alice slows down in the new medium, but Bob at the other end of the pole in the faster medium does not, so the pole turns. But why is there a pole? Why is the wavefront staying in phase through its shape when that's just the definition of what the wavefront is? It feels a bit like circular reasoning to me: the wavefront is changing direction because the wavefront... is a set of points in a wave that we observe to be changing direction?
Does this question make any sense?? It is obviously something I don't understand about what a wavefront is... can anybody explain it? Why does being the same phase lock you in shape? It seems like information has to be shared between photons for this to work, so that's my hint that the answer is getting quantum. But please explain it? I am comfortable with pop-sci explanations of quantum electrodynamics, what's the leap I need? Or maybe it's not quantum and it's actually much simpler than I make it out to be?
Essentially, what makes the wavefront a prescriptive thing? The wavefront is a set of points in the same phase, what makes them stay that shape (we also just accept the pole doesn't shrink, bend, or deform in any way) even when a part of it starts changing speed?

A: As you know, the peaks and troughs of water waves are examples of wavefronts. Wavefronts are lines or surfaces along which particles are oscillating in phase, so asking why a wavefront stays in phase would indeed invite the response 'by definition'. But it would not be illogical to ask why a straight or plane wavefront stays this shape when the wave passes into a new medium.
When we are presented with a good picture of water waves entering shallower water from deeper, across a straight interface, it's easy enough to explain the change in angle of the wavefronts and their getting closer together, in terms of the speed change. It seems perfectly reasonable, given straightness of both the incident waves and the interface, that the refracted wavefronts should also be straight. You can back this up, by noting that the extra time spent in the 'slower' medium is proportional to the distance along the wavefront. This is one sort of 'explanation'.
What my last paragraph has avoided is explaining how incident wavefronts actually travel and get to be the refracted wavefronts. This is more difficult, and invites the general question: how do waves travel, and specifically, how do straight wavefronts travel (in a quasi two dimensional medium)? Answer (a) We represent the wave mathematically and solve the equations that result. Answer (b) (less rigorous) We use Huygens' Principle, which starts by regarding all points on a straight wavefront as acting like 'point sources' and producing circular wavefronts. We then draw an 'envelope' around these 'wavelets'. This is not difficult to apply to refraction; it used to be on A-level syllabuses in the UK. But I'm afraid that a pole that takes an active part, as opposed to merely showing the position of the wavefront, has no analogue in the propagation of real waves, as far as I know.

A: I've already accepted Philip Wood's answer as the answer to my question, but I wanted to post the diagram of Huygens' principle and refraction that helped me understand more of the "how/why" that answers my question. I'm new to Stack Exchange, please let me know if this is bad form.

I find the image to be self-evident, but there is a description of what's happening in the picture from UC-Davis.
Read Philip Wood's answer, but I will say it this way: There is no analog to the pipe. The bending of the light ray seen is a result of the new envelope of the point-source wavelets that are moving at a different speed in the new medium. As this animation implies (watch for when the thick red line appears), there is no pipe or envelope to speak of until the other end of the wavefront also meets the new medium. You could perhaps force the analogy to work by saying the pipe is bent constantly along the length of it until it is straight again but at a new angle. I think that's clumsy though. I've decided that marching soldiers is not an analog at all to WHY refraction occurs, but is a useful thought experiment to show that a changing of angle does occur when media (and therefore velocity) changes gradually along a wavefront.
If you find animation distracting, the following diagram was also helpful to me.

You might be able to imagine the pipe bending down the length until the new envelope is formed a little better on this one. But really, don't imagine that. The pipe is a false analog.