Q:

javascript iterate over objects in nested array of objects and filter by ids and return the same original dataset updated

I have an array of nested objects, that i want to keep the objects in items that have the id equal to one in the filter list that i have as reference.

const data = [{
  "otherStuff": "otherB",
  "items": {
    "item1": [{
        "id": "id1",
        "info": "info1"
      },
      {
        "id": "id2",
        "info": "info22"
      }
    ],
    "item20": [{
      "id": "id3",
      "info": "info5"
    }],
    "item5": [{
        "id": "id4",
        "info": "info6"
      },
      {
        "id": "id5",
        "info": "info7"
      }
    ]
  }
}, {
  "otherStuff": "otherA",
  "items": {
    "item1": [{
        "id": "id1",
        "info": "info10000"
      },
      {
        "id": "id2",
        "info": "info220000"
      }
    ],
    "item20": [{
      "id": "id3",
      "info": "info5000"
    }],
    "item5": [{
        "id": "id4",
        "info": "info60000"
      },
      {
        "id": "id5",
        "info": "info7000"
      }
    ]
  }
}];

const keep = ['id4', 'id2'];
keep.forEach(function(val) {
  data.forEach(function(entry, index){
      const entrySelected = [];
      Object.keys(entry.items).forEach(item => {
        var match = entry.items[item].find(obj => obj.id === val);
        if (match) {
          entrySelected.push(match)
        }
      });
      data[index].items = entrySelected;
  });
})
console.log(data)

I am getting an error right now,
but the idea is to get the following output:
 [
        {
            "otherStuff": "otherB",
            "items": [
                    {
                          "id": "id2",
                          "info": "info22"
                    },
                    {
                        "id": "id4",
                        "info": "info6"
                }
            ]
        },
        {
            "otherStuff": "otherA",
            "items": [
                    {
                          "id": "id2",
                          "info": "info220000"
                    },
                    {
                        "id": "id4",
                        "info": "info60000"
                }
            ]
        }
    ]

how can i achieve this?

A:

You could iterate the values of the objects and then reduce the wanted items for a new array. Later assing this to items.

var data = [{ otherStuff: "otherB", items: { item1: [{ id: "id1", info: "info1" }, { id: "id2", info: "info22" }], item20: [{ id: "id3", info: "info5" }], item5: [{ id: "id4", info: "info6" }, { id: "id5", info: "info7" }] } }, { otherStuff: "otherA", items: { item1: [{ id: "id1", info: "info10000" }, { id: "id2", info: "info220000" }], item20: [{ id: "id3", info: "info5000" }], item5: [{ id: "id4", info: "info60000" }, { id: "id5", info: "info7000" }] } }],
    keep = ['id4', 'id2'];

data.forEach(o =>
    o.items = Object
        .keys(o.items)
        .reduce((r, k) => o
            .items[k]
            .reduce((s, p) => s.concat(keep.includes(p.id) ? p : []), r), []));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With a filter for arrays.

var data = [{ otherStuff: "otherB", items: { item1: [{ id: "id1", info: "info1" }, { id: "id2", info: "info22" }], item20: [{ id: "id3", info: "info5" }], item5: [{ id: "id4", info: "info6" }, { id: "id5", info: "info7" }] } }, { otherStuff: "otherA", items: { item1: [{ id: "id1", info: "info10000" }, { id: "id2", info: "info220000" }], item20: [{ id: "id3", info: "info5000" }], item5: [{ id: "id4", info: "info60000" }, { id: "id5", info: "info7000" }] } }],
    keep = ['id4', 'id2'];

data.forEach(o =>
    o.items = Object
        .keys(o.items)
        .filter(k => Array.isArray(o.items[k]))
        .reduce((r, k) => o
            .items[k]
            .reduce((s, p) => s.concat(keep.includes(p.id) ? p : []), r), []));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q:

Unable to scp from remote to local Mac

I have gone over SU and SO posts looking for a way to get this to work, but I'm about to put up my hands and stick with a GUI. I want to scp a ZIP file from a remote server to my local machine. I can SSH in just fine. I can create, delete, edit, etc... but am unable to download a ZIP. The "closest" so far.
# scp backup.zip Steven@111.111.111.11:/Users/Steven/Desktop/test.
For clarity, "backup.zip" is what I want to pull down from the server and is in my current directory. "Steven" is my username on my laptop. I've blanked out the IP address for my local machine with the ones, and the path is the path to the location I would like to copy to.
With that, however, I get:
ssh: connect to host 111.111.111.11 port 22: Connection timed out
lost connection
Funny thing is, I'm not booted out of the session. It just leaves me right where I was before entering in the command.
Am I missing some syntax?

A:

Do I understand correctly that you're using SSH to connect to the remote host, then you're running scp on the remote host to copy the file back to the local host?
Without knowing anything about these two hosts, it's perfectly possible that your local host can make SSH connections to the remote, but the remote can't make SSH connections to the local.
If you can make SSH connections from the local host to the remote host, you could run scp on the local host instead of the remote one:
scp remoteuser@remotehost:/path/to/backup.zip /Users/Steven/Desktop/test/


Q:

Left side of mutating operator isn't mutable: 'visiter' is a 'let' constant? WHY?

at the point where I tried to subtract the costs from the money of the guest, the error ''Left side of mutating operator isn't mutable: 'visiter' is a 'let' constant'' was throw when I tried to use the operator -=
But why? I declared it as variable! What can I do? The error was thrown at the entry function and the bar function:
struct ClubGuest: Guest {
    var name: String
    var money: Double
    var onDrugs: Bool
}
var mikel = ClubGuest(name: "Mikel", money: 50.5, onDrugs: false)
var angelina = ClubGuest(name: "Angelina", money: 400, onDrugs: true)
var steve = ClubGuest(name: "Steve", money: 100.80, onDrugs: true)
var july = ClubGuest(name: "July", money: 1050, onDrugs: false)

struct Club: Party {
    var name: String
    var location: String
    var entryPrice: Double
    var guests: [Guest]
    var maximumguests: Int
    var revenue = 0.0
    mutating func entry(visiter: Guest) {
        if visiter.money > entryPrice && guests.count < maximumguests {
            guests.append(visiter)
            visiter.money -= entryPrice
            revenue += entryPrice
        } else {
            stop()
        }
        GuestCheckUP(guest: visiter)
    }

    mutating func Bar(guest: Guest, drink: Drink) {
        print("\(guest) want to buy a drink")
        if guest.money >= drink.price {
            guest.money -= drink.price
        revenue += drink.price
        print("\(guest.name) bought a \(drink.name) for \(drink.price)$, now he/she has \(guest.money)$ in his/her pocket")
        } else {
            print("\(guest.name) has too less money for a drink!")
        }
    }

    mutating func GuestCheckUP(guest: Guest) {
        if guest.onDrugs {
            throwOut(visiter: guest)

        }
    }

    mutating func throwOut(visiter: Guest) {
        print("\(visiter.name) was throwed out by the security!")
    }

    func stop() {
        print("Stop! No entry!")
    }
    func Earnings() {
        print("The earnings of tonight are \(revenue)$")
    }
}

A:

Note that Guest is a protocol, not a type. You should first make sure in your Guest protocol to declare money property to require a setter, make your method generic and add inout keyword to it:
protocol Guest {
    var money: Double { get set }
    // your code
}

mutating func entry<T: Guest>(visiter: inout T) {
    // your code
}


Q:

What do Hilbert and Bernays mean when they say "finitist number theory"?

Perhaps it is not a fair question to be addressed here. Anyway, when I read that Hilbert and Bernays develop finitist number theory. What does "finitist number theory" mean here?

A:

I think the standard reference on this question is W. W. Tait, Finitism, Journal of Philosophy 78 (1981), 524-546.


Q:

Can I increase the character count of the Label of form fields?

In Sitecore 9, I'm constructing some forms using the form builder. When I add Single-line and Multiple-line fields, there seems to be a 256-character limit on the Label of those form elements. When you enter a stsring longer than that, it cuts it off.
Is there a way to override/increase this without utilizing a custom field?

A:

You need to update the label from the Content Editor for this. If you are using Form Designer it will cut off the text. but if you will use the Content Editor for this it will work fine, because the Title field is single-line text field in Sitecore. All you need to navigate the field for which you want to update the label and then select the Title field, add your text and save the field-


Q:

How to giving address from assets folder?

I intend opening a PDF file with the default application of my device. I have a problem giving address from the assets folder.
My giving address code is as follows:
File pdfFile = new File("file:///android_assets/test.pdf");
    Uri path = Uri.fromFile(pdfFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setDataAndType(path, "application/pdf");
    startActivity(intent);

This code gives the error This path is not valid when Adobe Reader opens. What's the correct address?

A:

It shows the error because only your application have the permission to access that folder. You can think to copy the file in a different directory (e.g. some place in the sdcard) and provide acrobat reader with the uri to the copied file,


Q:

Nested 'using' in C# as equivalent to typedef

I have a class to handle config files and I want to tidy up the code to make it more readable and maintainable.  In C++ I would usually do this using typedefs but I found that there is a way to do this in C# by using the 'using' keyword (see Equivalent of typedef in C#).  My only problem is that there doesn't seem to be a way to nest these.  Here is what I want to achieve:
using ConfigValue = System.Collections.Generic.List< System.String >;
using ConfigKey = System.String;
using ConfigSection = System.Collections.Generic.Dictionary< ConfigKey, ConfigValue >;

How can I achieve this without making ConfigSection explicit just in case I change the type of the ConfigKey or ConfigValue and forget to change the ConfigSection?
Thanks
Allan

A:

You can't do this, unfortunately. The main C# alternative to typedef in C/C++ is usually type inference, e.g. with the var keyword, but you still have to type out generic definitions in many cases. There's a reason why almost all C# programmers use Visual Studio or other IDE's that save them from typing out everything in many cases.
I wouldn't really recommend the "using-as-typedef" pattern too much, because I expect it will be unfamiliar and surprising to most C# programmers. Also, I think the fact that you have to include the "psuedo-typedef" in every file anyway greatly reduces the utility of it.
One thing you could consider doing is of course to make actual classes out of the things you want to typedef, e.g. like this:
public class ConfigValue : List<string>
{
}

public class ConfigKey
{
    private string s;

    public ConfigKey(string s)
    {
        this.s = s;
    }

    // The implicit operators will allow you to write stuff like:
    // ConfigKey c = "test";
    // string s = c;

    public static implicit operator string(ConfigKey c)
    {
        return c.s;
    }

    public static implicit operator ConfigKey(string s)
    {
        return new ConfigKey(s);
    }
}

public class ConfigSection : Dictionary<ConfigKey, ConfigValue>
{
}

But this is of course overkill unless you also have other reasons to want to make concrete classes.


Q:

Spring cloud aws (messaging) - not getting message

I am attempting to get spring cloud to work with messaging using auto configure.
My properties file contains:
cloud.aws.credentials.accessKey=xxxxxxxxxx
cloud.aws.credentials.secretKey=xxxxxxxxxx

cloud.aws.region.static=us-west-2

My Configuration class is as follows:
@ComponentScan
@EnableAutoConfiguration
public class Application {

public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }
}

My Listener class:
@RestController
public class OrderListener {

@MessageMapping("orderQueue")
public void orderListener(Order order){

    System.out.println("Order Name " + order.getName());
    System.out.println("Order Url" + order.getUrl());

    }

}

However, nothing seems to print out. I've verified that my queue is in the right region and there is a message on the queue thats ready to be received.
Can someone please provide some guidance?

A:

I see three possible reasons why it is not working

The OrderListener class is not scanned by the component scanner. In order to be scanned this class must be in the same package as your Application class or in a sub-package.
The spring-cloud-aws-autoconfigure artifact is missing on you classpath and therefore the AmazonSQS client is not automatically configured and the queues are not registered.
The message you have in your queue is missing a message header contentType with value application/json (for more information about this see question Spring Cloud - SQS).


Q:

The lightning struck the hut and set it alight or set it on fire?

Let's say you were storytelling something about a hut that was struck by lightning, is there any difference between the two?

The lightning struck the hut and set it alight?

Vs.

The lightning struck the hut and set it on fire?

A:

Alight could simply mean "lit up". It does not specifically tells if the thing is on fire or not. (Especially in American English)
There's not much difference in British usage, but it's better to use set it on fire as this clearly describes the event without leaving a doubt in the reader's mind.

A:

That use of alight sounds awkward to me. Things can be alight, but you don't set them alight. I'm not saying it's technically incorrect, just that IMHO it would be distracting to me as a reader.
On fire is fine, but probably what you're looking for is ablaze.

A:

The difference is the second example uses an Idiom to explain what happens

alight
  adjective [ after verb ] UK   /əˈlaɪt/ US   /əˈlaɪt/
  alight adjective [ after verb ] (BURNING)
The rioters overturned several cars and set them alight.
--Cambridge English Dictionary

Reference Cambridge Thesaurus
Idioms
set sth/sb on fire
set fire to sth/sb


Q:

why do we want to build the same project more than one build machine at a time?

Getting confused about this setting. How can it make sense when there is more than one concurrent builds for a single project.

A:

First, it uses for release now, in general, the release is used to deploy (There is the same setting in build, but do not work).
Secondly, the tasks are the same, but the variables’ value can be different, also some tasks can be run or not per to different agents through task conditions.
For example:

Add PowerShell task to release definition

Script to set variable value per to agent name
param(
[string]$a
)
 Write-Host $a
if($s -eq "XXX"){
Write-Host "##vso[task.setvariable variable=webname]devWeb"
}
else
{
Write-Host "##vso[task.setvariable variable=webname]ReleaseWeb"
}

Arguments: -a $(Agent.Name)
Logging Commands

Then the following tasks can use this variable (webname) with different value.


Q:

python dictionary with one key and multiple values

I have a list like: somelist= ['a','b','c','d']
I want to have a python dictionary with key as "key1"and values 'a','b','c','d' from some list.
d={}
for l in somelist:
d["key1"]=l
returns only {key1:'d'} but not values as the list.
How do i do this?

A:

When you do
for l in somelist:

you are looping through each element of somelist. In this case, each element is a string, so when you do:
d["key1"] = l

you are assigning the current element as the value for the key "key1" of the dictionary d. On each iteration, this value will be overwritten, so at the end, you will only have one element, the last one 'd'.
What can you do? Just assign the whole list as the value:
d["key1"] = some_list

there is no need to use a for loop.


Q:

Saving Inserted and Deleted tables into variables for use in .NET code (via sp_oamethod) [SQL Server 2000]

I am trying to create a SQL Trigger in SQL Server that will somehow serialize the Inserted and Deleted tables for use in .NET code (via sp_oamethod). I would like this to be generic enough to use for any table.
My first attempt involved using "for xml" to serialize it into XML, and pass it to .NET code. However, I have been unable to assign the XML to a variable, as it is not supported in SQL Server 2000 (2005 is not yet an option for us). The only option is to do the serialization manually (see saving the FOR XML AUTO results to variable in SQL) and that does not fit my requirements of being generic.
--This does not work
declare @OldValue varchar(5000)
select @OldValue = (select * from Deleted for XML auto)

Does anyone know of a way to do this generically, using any method? I do not care about the format, as long as I can get the column names and values into my .NET code.

A:

You do understand that triggers take place within a transaction and that one you are attempting will lengthen the transaction and, even more importantly, rely on processes outside of SQL Server being available and completing without error, right?
I'd recommend against doing this in a trigger, especiall the sp_OA* stuff.  Can you accomplish what you need by queuing the results from the inserted and deleted tables in a staging table and having a job or windows service process the data?


Q:

Lowenthal-LabourdonnaisSicilian Kalashnikov Variation

I have been studying the Kalashnikov Sicilian:

e4 c5
Nf3 Nc6
d4 cxd4
Nxd4 e5 (signaling the Lowenthal variation)
Nb5 d6 (d6 signals the Kalashnikov variation)

I have two books I have been studying that cover variations from this point forward. However, I spend a lot of time analyzing my openings and a line that comes up over and over again is

Bg5!?

The book Neo-Sveshnikov by Silman "covers" this line with one brief note about it on the last two pages of the book. The other book I am studying "Sicilian Kalashnikov" by Jan Pinski, Jacob Aagaard which I really like does not cover this move AT ALL.
Can anyone recommend a resource for me to read about the Bg5 continuation of this line? I find it hard to believe that it can be used somewhat commonly in GM level games and not discussed in any opening books.

A:

This has been one of my main two openings since it became popular in the 1980's again. With strong computers today, they say, and I agree with them, that black is virtually winning after the following line:
  [fen ""]

 1.e4 c5 2.Nf3 Nc6 3.d4 cxd4 4.Nxd4 e5 5.Nb5 d6 6.Bg5 Qxg5 7.Nc7+ Kd8 8.Nxa8 Nf6 {already -2.05 on Stockfish} 9. Nc3 Nd4! 10. h4 {best per four engines} (10. Qd2 Qxd2 11. Kxd2 b6) Qf4 11. g3 (11. Bd3 Be6 {and there is still nothing to stop the roundup of the Na8.}) Qf3 12. Qxf3 Nxf3 13. Kd1 {is given as best, and the Na8 soon falls.}

It is clear that black's development combined with his soon-to-be material advantage (Na8 falls), makes this winning for black, and there really isn't even much counterplay to make it interesting.
The problem earlier is that the Qg5 is very actively posted, e4 is weak, and the move Nc6-d4 is not only keeping the white queen from being active due to c2 being weak, but it blocks white from getting at many critical weak squares like d5, d6, and the d8 square where the black king is.

A:

While it's a somewhat dated source by this point, I'm certain that Neil McDonald's 1995 book Winning with the Kalashnikov covers this 6.Bg5 variation to some extent, and I'm nearly certain that he recommends taking it head on with
[fen ""]

1.e4 c5 2.Nf3 Nc6 3.d4 cxd4 4.Nxd4 e5 5.Nb5 d6 6.Bg5 Qxg5 7.Nc7+ Kd8 8.Nxa8

I don't recall how much concrete analysis followed (it's been many years since I owned/saw the book). Moreover, I don't know if there's more or less coverage than what you mention from Silman's book; even though I've played the Kalashnikov with considerable frequency since the days of McDonald's book, for my purposes I've never needed to consult a newer source.
To that point, I'll say that my experience has differed from yours, in that I almost never face this 6.Bg5 line, despite plenty of personal Kalashnikov tournament games and countless blitz games, and indeed I've never faced it in tournament play. I think one reason for that might be that Black can sidestep any messiness if she so chooses, so that it's not that testing a try from White. In particular, my own (potentially flawed) sense is that Black could even comfortably go for the following:
[fen ""]

1.e4 c5 2.Nf3 Nc6 3.d4 cxd4 4.Nxd4 e5 5.Nb5 d6 6.Bg5 Be7!? {This might look strange, as White can now force the black king to lose castling rights, but this comes along with an exchange of the dark-squared bishops that Black generally welcomes in this opening, and all things considered I think the black king can live comfortably.} 7.Bxe7 Kxe7  {This wouldn't be every black player's cup of tea, but if I'm right that this position is alright for Black, then the fact that this simple defusing of White's play is available would be a reason for 6.Bg5 to be infrequently played.} (7...Ngxe7? 8.Nxd6+)


Q:

convert scala hashmap with List to java hashmap with java list

I am new to scala and spark.I have below case class A
case class A(uniqueId : String,
               attributes: HashMap[String, List[String]])
Now I have a dataFrame of type A. I need to call a java function on each row of that DF. I need to convert Hashmap to Java HashMap and List to java list..
How can i do that.
I am trying to do following
val rddCaseClass = RDD[A]
val a = rddCaseClass.toDF().map ( x=> {
val rowData = x.getAs[java.util.HashMap[String,java.util.List[String]]]("attributes")
callJavaMethod(rowData)

But this is giving me error :

java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot be cast to java.util.List

Please help.

A:

You can convert Scala Wrapped array to Java List using
  scala.collection.JavaConversions

 val wrappedArray: WrappedArray[String] = WrappedArray.make(Array("Java", "Scala"))
 val javaList = JavaConversions.mutableSeqAsJavaList(wrappedArray)

JavaConversions.asJavaList can also be used but its deprecated: use mutableSeqAsJavaList instead


Q:

Can't figure out how to change navbar in bootstrap 4

Using Bootstrap 4.
I have this HTML for navbar:

  Home
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2 my-sm-0" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
    </form>
    <button *ngIf="!isSignedIn" (click)="signIn()" class="btn btn-danger my-2 my-sm-0" type="submit">SignIn</button>
      <button *ngIf="isSignedIn" (click)="signOut()" class="btn btn-danger my-2 my-sm-0" type="submit">SignOut</button>

In collapsed state it looks like this:

If I remove navbar-brand (Home), I get this:

Question 1: for some reason the "Expand" is moved to the left side

When I click to expand I get this:

In full mode I get this:

What I want is:

The Expand button (the hamburger icon) to stay on the right side even when I remove the navbar-brand text.
The red SignOut button to be on the right side.
The Search Form with Search button to stay on the left side with NO navbar-brand (Home) text
And the last thing - is it possible to make the entire navbar a little thinner, using bootstrap only? I know this can be done with css.

Please advise. Thank you!

A:

Use ml-auto (margin-left:auto) to push the buttons to the right...

    <button class="navbar-toggler ml-auto" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2 my-sm-0" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
        </form>
        <button class="btn btn-danger my-2 my-sm-0 ml-auto" type="submit">SignOut</button>

https://www.codeply.com/go/UG0l2aoHNs
Also see: Bootstrap 4 align navbar items to the right


Q:

Can an iPhone/Android app have access to microphone during phone calls?

I'm wondering if it's possible to record phone calls via apps. (changing voice pitch and etc.)

A:

Android can access the microphone. There are apps in the Android Market that record phone calls. I am not sure if you can change the stream without root access.
iPhone - this is completely out - this is all private API and will cause your app to be rejected.


Q:

Changing Background Colour with a While Loop

I wrote a snippet of code so a prompt would come up in chrome asking for a colour and using a loop it would keep asking and keep changing the colour till an empty string is given. If the loop is taken out it changes the colour but with the loop added in the background, the colour does not change. Is there a logical error I am missing?
let empty=false;
while(empty===false){
  const colour= prompt("Give me a colour");
  document.body.style.backgroundColor=colour;
  if(colour===""){
    empty=true;
  }
}

A:

JavaScript blocks repaints of the document.
Until the JS finishes (which it never does until colour is ""), the browser won't have an opportunity to update the display to reflect the changes you made to the DOM.
You can't use a while loop for this. Use setTimeout recursively instead.

function update_background() {
    const colour = prompt("Give me a colour");
    document.body.style.backgroundColor=colour;
    if (colour) {
        setTimeout(update_background);
    }
}

update_background();


Q:

Bare metal ARM cortex M programming sequence

I'm beginning ARM projects with bare metal STM32F051R8 development by CMSIS core in KEIL. Used the
following sequence to blink LED:

Enable Reset and clock register bit (RCC) for the AHB bus controlling the LED port.
Set the mode register (MODER) for the LED pin as General purpose output mode.
Set output type register (OTYPER) for LED pin as Output push-pull.
Set output speed register (OSPEEDR) to normal speed for the LED pin.
Set the pull up down register as no pull up/ down for LED pin.
In an infinite loop, set the pin bit to high/ low in the output register (ODR) to blink the LED with a delay in between.

Is the sequence above a standard for ARM Cortex M LED blink regardless of manufacturer? Or each
manufacturer has its own sequence?
If it is a standard, it will make switching between manufacturers (ST, NXP, TI, etc) a less
daunting task with more complicated projects where you don't have to dig through a gigantic manual.
For example, a protocol like I2C will have the same execution sequence for data transmission regardless
of manufacturer, so I thought if ARM is a similar standard for MCU's. Hope I made the question clear.
Waiting to be enlightened!

A:

It is not standard. The peripherals are different between manufacturers. However, within a manufacturer, the peripherals tend to be very similar (to encourage you to stick with their products since once you use one it is much faster to move between their products than someone else's). For example, I use the STM32F303 on Segger IDE and the steps and register names are identical (due to CMSIS) to yours.
Only the ARM core is the identical, which mostly doesn't matter to you as an high-level language programmer).
Since writing libraries is a lot of work...choose the manufacturer you want to learn with carefully. You're probably going to be together for a while.
Regarding your I2C comment, sure the data transmission on the OUTSIDE of the microcontroller might be the same, but that in no way shape or form means that it has to be organized and configured the same way inside the microcontroller. That's like saying because two people can talk to each other, they must both think and act alike.


Q:

First chance exception at $7C81EB33

I have an application that when run at home works fine, however when ran on school computers(Windows XP) i get the following message. (This is recompiling it, not just running the .exe)- In Delphi 2005

First chance exception at $7C81EB33. Exception class EAccessViolation with message 'Access violation at address 0045E5E2 in module 'Project2.exe'. Read of address 00000198'. Process Project2.exe (440)

Code: Ignoring unneeded stuff.
        Image1: TImage; // Image(all the way to 72)
        Timer1: TTimer; Timer2: TTimer;
        procedure Button1Click(Sender: TObject);
        procedure FormCreate(Sender: TObject);
        procedure SomeOtherProcedure(Sender: TImage);
        procedure Timer1Timer(Sender: TObject);
        procedure Timer2Timer(Sender: TObject);
          private
        { private declarations }
      public
        { public declarations }
      end;
    var
      Form1: TForm1;
      left : integer;
      top  : integer;
      gap  : integer;
      type
        coordinates = record
          row : integer ;
          col : integer;
        end;

      var
      picarray : array[0..5,0..5] of timage;
      thiscover, midcover, lastcover : timage;
      imageindex : array[0..5,0..5] of integer;
      picloc: array[0..3] of coordinates;
      clickcount, pairsfound, attemptcount : integer;
implementation
{$R *.lfm}
procedure initialise();
var
i, j, whichcol, whichrow : integer;
begin
        for i := 0 to 5 do
        for j := 0 to 5 do
        imageindex[i,j] := -1; // not used
        randomize;
        for i := 0 to 11 do
        for j := 1 to 3 do
        begin
        repeat
          begin
          whichcol := random(6) ;
          whichrow := random(6)  ;
          end;
        until imageindex[whichcol, whichrow] = -1;
        picarray[whichcol, whichrow].Picture.LoadFromFile('C:\Users\Hayden\Pictures\'+ inttostr(I+1) +'.jpg');
        imageindex[whichcol, whichrow] := I  ;
        end;
        clickcount := 0  ;            //
        pairsfound := 0    ;
        attemptcount := 0  ;
        end;

    procedure TForm1.FormCreate(Sender: TObject);
var
cpic : tcomponent;
whichcol: integer;
whichrow : integer;
begin
gap := image2.left - image1.left;
top := image1.Top;
left := image1.left;
for cpic in form1 do
begin
     if (cpic.ClassType = timage) and (cpic.Tag = 10) then
     begin
     whichcol := (timage(cpic).left - left) div gap;
     whichrow := (timage(cpic).Top - top) div gap;
     picarray[whichcol, whichrow] := timage(cpic)   ;
end;
end;
initialise;
end;

Line >>> picarray[whichcol, whichrow].Picture.LoadFromFile('C:\Users\Hayden\Pictures\'+ inttostr(I+1) +'.jpg');
seems to cause the error. And if it is a coding error, what is the correct way to do this?

A:

First, I'm going to clean up your code a little, because as it stands, it's very difficult to figure what's going on. I highly recommend you get into the habit of taking a few minutes to keep your code clearly formatted - it will save you hours of debugging.
I've applied only the following simple changes: Indentation, Blank lines, and liberal use of begin .. end;
var
  picarray : array[0..5,0..5] of timage;
  thiscover, midcover, lastcover : timage;
  imageindex : array[0..5,0..5] of integer;
  picloc: array[0..3] of coordinates;
  clickcount, pairsfound, attemptcount : integer;

implementation

{$R *.lfm}
procedure initialise();
var
  i, j, whichcol, whichrow : integer;
begin
  for i := 0 to 5 do
  begin
    for j := 0 to 5 do
    begin
      //It's clear you're initialising the 36 entries of imageindex to -1
      imageindex[i,j] := -1; // not used
    end;
  end;

  randomize;
  for i := 0 to 11 do
  begin
    for j := 1 to 3 do
    begin
      //This loop also runs 36 times, so it fills the whole of imageindex with new values
      //It also loads all 36 entries of picarray with an image specfied by the current value of i
      //The approach is dangerous because it depends on the 'loop sizes' matching,
      //there are much safer ways of doing this, but it works
      repeat
        begin //This being one of the only 2 begin..end's you provided inside this is routine is pointless because repeat..until implies it.
          whichcol := random(6) ;
          whichrow := random(6)  ;
        end;
      until imageindex[whichcol, whichrow] = -1;

      //This line itself will throw an access violation if picarray[whichcol, whichrow] doesn't
      //contain a valid TImage instance... we have to check other code to confirm that possibility
      picarray[whichcol, whichrow].Picture.LoadFromFile('C:\Users\Hayden\Pictures\' + inttostr(I+1) + '.jpg');
      imageindex[whichcol, whichrow] := I  ;
    end;
  end;

  clickcount := 0  ;            //
  pairsfound := 0    ;
  attemptcount := 0  ;
end;

Moving on to the next piece of code:
procedure TForm1.FormCreate(Sender: TObject);
var
  cpic : tcomponent;
  whichcol: integer;
  whichrow : integer;
begin
  gap := image2.left - image1.left;
  top := image1.Top;
  left := image1.left;
  for cpic in form1 do
  begin
    //This loop attempts to assign existing TImage instances to picarray
    //However, the way you're going about it is extremely dangerous and unreliable.
    //You're trying to use the position of a component on the form to determine its
    //position in the array.
    //There are many things that could go wrong here, but since this seems to be a
    //homework excercise, I'll just point you in the right direction - you need
    //to debug this code.
    if (cpic.ClassType = timage) and (cpic.Tag = 10) then
    begin
      whichcol := (timage(cpic).left - left) div gap;
      whichrow := (timage(cpic).Top - top) div gap;
      picarray[whichcol, whichrow] := timage(cpic)   ;
    end;
  end;

  //Here you call initialise, which as I said before, will
  //cause an Access Violation if picarray is not correctly 'set up'
  //The previous code in this method certainly has a bug which is
  //preventing one or more picarray entries from being assigned a
  //valid TImage instance.
  //You could write a simple for I := 0 to 5, for J := 0 to 5 loop
  //here to check each of picarray entries and pinpoint which is
  //incorrect to aid your debugging of the pevious loop.
  initialise;
end;


Q:

save result to variable

How can I save result from nc to the variable?
I want:

nc: connect to localhost port 1 (tcp) failed: Connection refused

on my variable. I tried:
a="$(nc -z -v localhost 1)"
echo $a

but output is empty.

A:

Just use $() to get the result of the command:
your_var=$(nc -z -v localhost 1)

If you also want the error to be stored, then redirect the 2 (error) to 1 (normal output):
your_var=$(nc -z -v localhost 1 2>&1)

A:

Just redirect stderr to stdout, expressed by 2>&1:
a="$(nc -z -v localhost 1 2>&1)"
echo $a
nc: connect to localhost port 1 (tcp) failed: Connection refused

File descriptor 2 is attached (unless redirected) to stderr, and fd 1 is attached to stdout. The  bash syntax $( ... ) only captures stdout.


Q:

SQL How to group by two columns

Bellow is an example table.
ID   FROM       TO         DATE
1    Number1    Number2    somedate
2    Number2    Number1    somedate
3    Number2    Number1    somedate
4    Number3    Number1    somedate
5    Number3    Number2    somedate

Expected result is to get 1 row for each unique pair of TO and FROM columns
Example result if ordered by ID ASC
(1,Number1,Number2)
(4,Number3,Number1)
(5,Number3,Number2)

Ok I have found how to do this with the following query
SELECT * FROM table GROUP BY LEAST(to,from), GREATEST(to,from)

However I am not able to get the most recent record for every unique pair.
I have tried with order by ID desc but it returns the first found row for unique pair.

A:

SQL fiddle isn't working for some reason so in the mean time you will need to help me to help you.
Assuming that the following statement works
SELECT
    LEAST(to,from) as LowVal,
    GREATEST(to,from) as HighVal,
    MAX(date) as MaxDate
FROM table
GROUP BY LEAST(to,from), GREATEST(to,from)

then you could join to that as
select t.*
from
    table t
    inner join
        (SELECT
            LEAST(to,from) as LowVal,
            GREATEST(to,from) as HighVal,
            MAX(date) as MaxDate
        FROM table
        GROUP BY LEAST(to,from), GREATEST(to,from)
        ) v
        on t.date = v.MaxDate
        and (t.From = v.LowVal or t.From = v.HighVal)
        and (t.To = v.LowVal or t.To= v.HighVal)


Q:

How to Show the Related Content in another Div when an Image Clicked

I have a div area (for main slider. But there will not be sliding inside).
And under this div area there is a tab system.
In these tabs there are 1-6 images (In each tab there are another images (1 to 6 images)
When I click one of these images I want to show the related content / photo etc in this Div area above.
How can I do that? Any example? Any clue?
I tried to use jquery for show/hide, toggle etc but for example I couldnt find how to keep those big divs unvisible within my html (I tried css "display:none;" but that didn't seem to me wise enough) and call them in its place (above of the tab system)
P.S: when an image is shown the others must be hidden.

A:

Here you are demyr obviously you will have to modify to your exact needs:
http://jsfiddle.net/S4LGr/1/
It is no problem here is the updated code, edit as you need you should really be able to take it from here:
http://jsfiddle.net/S4LGr/3/
I changed the images on this one so you can actuall see it happen, very similiar to ford.ca:
http://jsfiddle.net/S4LGr/5/
Here you go man all the pieces brought together:
http://jsfiddle.net/S4LGr/9/
totallyFeelLikeIdidYourHomeWork lol you owe me a beer!


Q:

Doctrine2 one-to-one correctly done

I have an entity, say A. And another one B.
A={id,name} B={id,details}
I want a one-to-one relation. Basically for each x from A there must be exactly one y from B and the reverse. So I thought about solutions and came up with the following.
1. The id is shared.
But then basically it will be like.
A={same_id,name} B={same_id,details} same_id is unique

B will have a foreign key for same_id to A.same_id.
Or A will have a foreign key for same_id to B.same_id

But I want to be able to get the details from A.
Basically doing $a->getAB()->getDetails();
Which means that we need to implement 2).
But that sounds counterintuitive since that will mean, one must first create a new B entity and then create an A entity and point it to the B entity.
Which looks like B owns A - and is not what I want.
And in the reverse - if B has a foreign key to A, can I still tell A about B's existence, so I can do $a->getAB()->getDetails(); ?
2. B has another id, and A has a foreign key to it:
So it will be like: A={id,name,bId} B={bId,details} bId is unique, id is unique
But in this way - it seems like I am wasting a column for A.
B won't know it's attached to A too which perhaps is a bad practice.
EDIT: But this doesn't solve any problem, just noticed I must again first create B, since any x from A needs to point to a valid y from B.
3. Is the problem about the automatic generation of my mappings?
Currently I am generating my XML mappings and entity classes from my MySQL database.
Could it be that this generation won't automatically tell A if B has a foreign key to it?

A:

One-To-One, Bidirectional association is what you're looking for (something like your example in point 2).
And yes - owning is important. Please also read about the concepts of owning and inverse sides of associations.
I'd say in your example A is the owning side - it has a name. Name is usually something more significant than details.
There's no problem to create both Entities at the same time;
$a = new A();
$a->setName("Alpha");

$b = new B();
$b->setDetails("Alpha goes first");

$a->setB($b);
$em->persist($a)->flush();

and both entities will be aware of the counterpart:
$a->getB();
$b->getA();

Again - there MUST be an owning side and you must maintain the logic.


Q:

log4javascript - open the same PopUpAppender so all the log is in one log window

Can log4javascript reuse the same (the exact same) PopUpAppender ?
What do I mean by that : once you start logging the PopUpAppender will create a new window (usually with an 'windowId' something like *'log4javascriptConsoleWindow_1381843187828_742325019557029'*).
Now, the appender (PopUpAppender) is setup so : appender.setReopenWhenClosed( true ) - in this case even if the window is closed the next log message will open a new window for it.
What do I want is to get back the previously closed window (the one with the strange windowId) so all my log messages are in one place.
In a couple of words - I want all my log messages in just 1 window.
One way to do that (I think) - is to modify the HTML that represents the PopUpAppender and modify the line that generates the windowId - in this way the same window will be created every time. So far so good - only that the array of 'LogEntry' is emptied. So before logging you might need to save them and then somehow insert them back (at the beggining) in the new window.
I'm willing to try this - I'm not sure that this is the right way - so if somebody has a better idea please share it with us (me).

A:

I may add support for this in log4javascript 2.0. In the meantime, I suggest creating an appender object that wraps a PopUpAppender and stores all logging events that pass through so that they can be re-appended when the pop-up reopens.
function WrappedPopUpAppender(popUpAppender) {
    var appender = this;
    this.popUpAppender = popUpAppender;
    this.loggingEvents = [];
    this.closed = false;

    popUpAppender.addEventListener("unload", function() {
        appender.closed = true;
    });
}

WrappedPopUpAppender.prototype = new log4javascript.Appender();
WrappedPopUpAppender.prototype.append = function(loggingEvent) {
    this.loggingEvents.push(loggingEvent);
    if (this.closed) {
        for (var i = 0, evt; evt = this.loggingEvents[i++]; ) {
            this.popUpAppender.append(evt);
        }
        this.closed = false;
    } else {
        this.popUpAppender.append(loggingEvent);
    }
};

var popUpAppender = new log4javascript.PopUpAppender();
popUpAppender.setReopenWhenClosed(true);
var wrappedAppender = new WrappedPopUpAppender(popUpAppender);

var log = log4javascript.getLogger("main");
log.addAppender(wrappedAppender);


Q:

Does a photon have a wave function or not?

I have read this question:
Why doesn't there exist a wave function for a photon whereas it exists for an electron?
where annav says:

Here is the [wavefunction of the photon,][1] which is a solution of a quantized maxwell's equation:

Now write the complex wave function as the sum of real imaginary parts $\bar E_{\tau}(\bar r)$ and $\bar B_{\tau}(\bar r),$ $$\bar \psi_{\tau}(\bar r,t)=2^{-1/2}\left(\bar E_{\tau}(\bar r,t)+i\bar B_{\tau}(\bar r,t)\right).$$
where Chiral Anomaly says:

In this generalized sense, a single photon can have a wavefunction.
  When physicists say that a photon doesn't have a wavefunction, they mean that it doesn't have a wavefunction that is a function of the eigenvalues of position observables, and that's because it doesn't have any strict position observables.

Can we define a wave function of photon like a wave function of an electron?
where J.G. says:

This ultimately scuppers any attempt to interpret a relativistic wavefunction as a 1-particle probability amplitude.

where MS Tais in a comment says:

Just adding to this, a photon is by definition relativistic always, so position is undefined for it. So, the answer to your question is "no".

photon wave function, double slit, single photon source
where Punk_Physicist says:

There's an old argument by Newton and Wigner, that the photon as a massless particle can't have a position operator and therefore no position space wave function.

Now for clarification, the question is about more then just context, and using the phrase wave function in different ways. Photons do not have strict position observables. Though, they are QM objects, and I do believe that all elementary particles in the SM are QM objects, and should have a wave function. Now for photons the Fourier transform of $f(\nu)$ is sometimes considered as wave function, but this is for photons meaningless, as time oscillations are fast, but the observation process is too slow. Our eyes observe the frequency distribution, not the Fourier transform. Because of the transversal nature of photons, the Fourier transform can never be interpreted as something in space (only along planes perpendicular to momentum).
Wave function of a photon?
Question:

Does a photon have a wave function or not?

A:

The difference is that in classical physics electron is a particle, while electromagnetic field is a wave. When they are quantized, the particle-wave duality kicks in: the electron acquires wave-like properties - a wave function which can undergo interference and produce a discrete spectrum when confined, whereas the electromagnetic field acquires particle-like properties - it now has a momentum and it is created in discrete units (photons). Thus, properly speaking, the modes of the electromagnetic field are its wave functions. (This hardly comes as a surprise, if you read about quantizing electromagnetic field, which nearly always involves modes expansion and then imposing the commutation relations on the expansion coefficients.)
Things become really odd when we perform second quantization for electrons, which is mathematically identical with the first quantization for the electromagnetic field.


Q:

What is the best way to introduce Superpowers into a world that previously never had them... WITHOUT destabilizing society

Let me pitch you a setting: The year is 2017, and thanks to an extradimensional portal Humans have begun to develop superpowers. The Power Scale for these supers is low-to-mid Street Level
(meaning that a Superman-esque superhuman would cause EVERYONE to flip).
Note: The source of the Superhumans power comes from a variety of Nodes scattered across their body/in their cells [Similar to the Magic System from this question: Would "magic" still be called "magic" in a modern era? (except the fact that their Nodes can only channel their energy in a specific manner)].
So my question is... How could I introduce these Superhumans into my setting (which is IDENTICAL to our world... except for the superhumans) without causing the collapse of society.
Bonus if you can come with a good name for them!
Note: The advent of Superpowered Humans is not immediate, rather it occurs over a few generations (with an increasing number of them per generation)

A:

If twenty-five percent of the world's population developed super-powers, then everybody will know someone who has super-powers. Often that will be someone in your family. It's hard to panic if Aunt Hortense can levitate or light the gas stove with her finger tip.
While there maybe people who can bend steel bars with their bare hands, there were be few who can transport skyscrapers or change the course of mighty rivers. (And if I read the OP's question correctly, that means none.)
There are a couple of aspects of this transformation to the global population. These supers are beginning to develop their super-powers. Aunt Hortense might start by hovering a centimetre or two off the ground, gradually she will rise higher, and perhaps eventually she might sail up to tree tops.
The supers will need to learn how to use super-powers. Strong enough to lift a car? OK. That's about a ton. So someone who can lift a ton will need to learn how to lift cars carefully, without wrecking them.
As for flying, never does anyone explain how super who can fly can do so without flying lessons. Flying an aircraft is extremely non-intuitive. Ask anyone has to fly an aircraft. Fortunately, the level of flight supers are likely to have means they get stuck in orbit or achieve escape velocity to never return. Perhaps they can only fly at one hundred metres maximum and at about running speed. or if they're lucky as fast as a fast car.
Since their super-powers have a form of biological basis, those super-powers will need to be powered and fueled by metabolic energy. They have to eat. Not all their super-powers will enable the supers to just take what they want. Soon they will slow down or run out of power, then face the consequences of their super-powered misdeeds.
Zapping your kid sister and the dog with your electrocyte-based electricity manipulation may have been fun at the time. But when your battery's flat and a pair of angry parents descend on you, it might be time to rethink junior supervillainy as a career option.
The chances are this will become a world where people, at least, a quarter of them, will be able to do remarkable things. This won't change their lives too drastically. Very few will don a mask, become a vigilante and go crime fighting. The usual suspects will use their new found super-powers to assist with their criminal activities. But the boys and girls in blue will have their fair share of super-powers too.
There will be a distinct absence of supers who can achieve world domination overnight. In some ways it will be like if 25% of the population became instant Olympic athletes. Amazing at first, amusing later on, and eventually situation normal before next Xmas.
The next generation of kids will soon be asking: how did people cope without super-powers? And they will the usual answer of we just did because that's how things were back then.


Q:

Opening a remote Excel file via WebDAV without full WebDAV support

I am looking to implement a fairly simple system where a user can open and edit an Excel file via a link to a WebDAV resource. I am using a custom ASP.NET solution for this (running on Azure, so extra software installation/configuration is very difficult). Doing a basic implementation, I can get the document open, but in read only mode. I have seen a number of posts of how to open in read-write mode, but I am not sure what WebDAV verbs/options that I need to support in order to make this happen on the backend.
Is there a list of verbs that Excel (and Office in general) use when working with a WebDAV resource/file?
Thanks,
Erick

A:

After looking into this and writing some prototype code, it appears that you need pretty much all the WebDAV features, including both levels. Or so close to all of them that it isn't worth doing a partial implementation.
Erick


Q:

Remove ANY Grid-Item on the click of an 'x' button that is within each item, my method only deletes the last one

I am re-vamping a program for my Engineering departments research team, my app has been built using Electron, Vuex, HTML/Sass/Javascript. The program's purpose is to allow the user to create "steps" which are items/tiles that you can go into & set system parameters & processes to run X amount of times. Setting up the values and settings within each step can take a while, so if the user creates 5 steps, and realizes they want to delete step number 2 entirely, there needs to be a 'remove' or a small 'x' within each step/item. Currently, I can only remove the last populated step/item using the 'pop' function to remove the last item in the array 'stepsGrid'.
Using vue-grid-layout to populate grid-items/tiles which will each be a 'step' that our system will run. I am able to dynamically add new 'steps', however I have only been able to successfully remove steps by using pop() to remove the last item from the array in which grid-items are. I want to place a
<button id="remove" @click="removeStep()">Remove</button>

within each step, so that I can delete any item on the grid instead of just the last item.
I have seen a few examples, but not being the best at javascript- I haven't had any luck. I tried referencing the functions used here: https://chrishamm.io/grid-demo/
and  https://github.com/chrishamm/vue-dynamic-grid
for removing grid items, however this library is a little more complicated than the regular Vue-Grid-Layout.
Here is my code, the key is the step.i component which is the ID of each item populated, each tile will have an 'x' in the corner and the function needs to be able to recognize the ID of that tile, and delete the corresponding item from the stepsGrid array:

Steps

<grid-layout
  :layout.sync="stepsGrid"
  :col-num="8"
  :row-height="75"
  :is-draggable="true"
  :is-resizable="false"
  :is-mirrored="false"
  :vertical-compact="true"
  :margin="[50, 50]"
  :use-css-transforms="true">

<grid-item
  v-for="step in stepsGrid" :key= "step.i"
  :x="step.x"
  :y="step.y"
  :w="step.w"
  :h="step.h"
  :i="step.i"
  :isDraggable="step.isDraggable">

Step: {{step.i}} //displays item # on each tile

 Loop Count: <input type="number" value="1">

Status:

<button @click="removeStep()">Remove</button>

</grid-item>
</grid-layout>

//Grid arrays are in store.js, as shown below(this is for an electron app):
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

export const store = new Vuex.Store({
state: {
 stepsGrid : [
{"x":0,"y":0,"w":2,"h":1,"i":"0"}
],

mutations: {
addStep (state, step){
state.stepsGrid.push(step);
}
},

actions: {
  addStep ({state, commit}){
    const step =
    {"x":0, "y": 1, "w": 2,"h":1,"i":String(state.stepsGrid.length) };
    commit('addStep', step);
 },

I know I need to incorporate the use of a key here, but I am unsure how to do it. I found this, but he goes about it an unusual way:
"I deleted the element in array by the button and could not understand the problem, as the last element was always deleted, although the key was unique. I added an extra unique uuid and it all worked."
<dish-item v-else class="dishItem"
v-for="(item, key) in dishes" :key="key + $uuid.v1()" :value="item"
@removeDish="$delete(dishes, key)"
@editDish="$refs.modal.showEdit({item, key})"
/>

Lastly, I went digging through the files for Vue-Dynamic-Grid and found that they are removing items with the following method:
methods: {
    removeElement(item) {
    if (item == this.selectedItem) {
    this.selectElement(null);
}

this.gridItems.splice(item.i, 1);
this.items.splice(item.i, 1);
breakpoints.forEach(function(size) {
    this.layouts[size].splice(item.i, 1);
    this.layouts[size].forEach(function(layout, i) {
       if (layout.i > item.i) {
         layout.i--;
        }
    });
}, this);
this.$emit("itemRemoved", item);
    }

If anyone could be of help, I would appreciate it! I have been learning JS on the go with this project, so if anyone has some tips please let me know! Thanks
I have tried attempting to write a function based on the way Vue-Dynamic-Layout's method for removing items, but I was not successful. As of right now, I don't have a small 'x' in each tile, I have a button for adding/removing a step in the bottom left of my app, to remove items I am simply popping the last item out of the stepsGrid array, so I can only remove the last populated item.

A:

First let the event handler know which step is being clicked
<button @click="removeStep(step)">Remove</button>

Then find that step in the array and remove it
methods: {
    removeStep(step) {
        const index = this.stepsGrid.indexOf(step);
        if (index >= 0) this.stepsGrid.splice(index, 1);
    }
}


Q:

Multiple Render Targets in DirectX9

I'm trying to implement very basic deferred shading in DirectX9. I have the ability right now to only use 2 render targets (The back buffer and another texture). So I can render the normals or the depth but not both. My question is can someone explain how to render to more than one texture target. I was under the impression I could just use something like the code below. It only works if the indexes are zero which probably means one of the surfaces is not being written to.
d3dDevice->SetRenderTarget(0, surfaceDepth);
d3dDevice->SetRenderTarget(1, surfaceNormal);

I get this message: Direct3D9: (WARN) :Can not render to a render target that is also used as a texture. A render target was detected as bound, but couldn't detect if texture was actually used in rendering.
I know there is probably a few things that could be related to this message...I guess if someone could explain how to use multiple render target indexes correctly. Also do you change the technique for each render target. Right now my shader has a "normal technique" and a "depth technique" and the "post process technique" for the pipeline.
Thanks for your time.
here is some more code:
SetTransforms();
d3dDevice->SetRenderTarget(0, surfaceDepth);
HR(d3dDevice->Clear( 0, NULL, D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, 0xff000000, 1.0f, 0));
scenes[sceneIndex]->setTechnique("depthTech");
scenes[sceneIndex]->render(dt);

d3dDevice->SetRenderTarget(1, surfaceNormal);
HR(d3dDevice->Clear( 0, NULL, D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, 0xff000000, 1.0f, 0));
scenes[sceneIndex]->setTechnique("normalTech");
scenes[sceneIndex]->render(dt);

A:

You just say set d3dDevice->SetRenderTarget(n, surface) for all targets where n is the target number and then you set the technique that outputs to a multiple render target structure in the pixel shader


Q:

html tabs removeClass & addClass in jquery not working

I have an index page with tabs for now, they are not linking to anywhere yet but I'm trying to set the active class when you click on a tab.
Here are the tabs:

            @foreach(var division in Model)
            {

@division.Description

            }

All

Summary

And the jquery:


Q:

UnicodeEncodeError: 'charmap' codec can't encode character '\u010d'

I am using a Python script to open a .csv file and import the data to a database.  There are several latin characters that were causing errors, so I have tried to encode those with UTF-8 and use the errors='replace'  specification to replace those troublesome characters with a question mark.  However, even after doing this I have been receiving the following error:
UnicodeEncodeError: 'charmap' codec can't encode character '\u010d' in position 2: character maps to <undefined>

I am using Python 3.7.4. Here is my current code:
import csv
import cx_Oracle
import io

localfile = 'C:/User/Documents/Upload/data.csv'
connection = cx_Oracle.connect()

with io.open(localfile, 'r', encoding='utf-8', errors='replace') as csvfile:
        for row in reader:
                connection.execute("INSERT INTO database.my_table (Column_1, Column_2, Column_3) values (:1, :2, :3)", [
                    row[0], row[1], row[2]])
                    connection.execute('commit')
            connection.execute('commit')

EDIT:
Here is the full Traceback
Traceback (most recent call last):
  File "c:\User\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\User\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\lib\python\ptvsd\__main__.py", line 432, in main
    run()
  File "c:\User\.vscode\extensions\ms-python.python-2019.8.30787\pythonFiles\lib\python\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\User\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\User\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\User\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\User\Documents\Python_Projects\python_sftp_remote_server_edition.py", line 116, in <module>
    insert(localfile, c)
  File "c:\User\Documents\Python_Projects\python_sftp_remote_server_edition.py", line 28, in insert
    row[0], row[1], row[2]])
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character '\u010d' in position 2: character maps to <undefined>

A:

Thanks everyone for your help.  While none of the answers directly fixed the problem, I was able to use them to research a bit more and ultimately find a solution that allowed the script to run without errors and insert the data into my Oracle database.  Just wanted to post my (working) code below in case anyone else runs into the same difficulties.
import csv
import cx_Oracle
import io

localfile = 'C:/User/Documents/Upload/data.csv'
connection = cx_Oracle.connect(conn_str, encoding="utf-8")

with io.open(localfile, 'r', encoding='utf-8', errors='backslashreplace') as csvfile:
        for row in reader:
                connection.execute("INSERT INTO database.my_table (Column_1, Column_2, Column_3) values (:1, :2, :3)", [
                    row[0], row[1], row[2]])
                    connection.execute('commit')
            connection.execute('commit')


Q:

New column in pandas dataframe based on existing column values

I have a dataframe with a column named 'States' that lists various U.S. states. I need to create another column with a region specifier like 'Atlantic Coast' I have lists of the states that belong to various regions so if the state in df['States'] matches a state in the list 'Atlantic_states' the specifier 'Atlantic Coast' is inserted into the new column df['region specifier'] my code below shows the list I want to compare my dataframe values with and the output of the df['States'] column.
 #list of states
 Atlantic_states = ['Virginia',
              'Massachusetts',
              'Maine',
              'New York',
              'Rhode Island',
              'Connecticut',
              'New Hampshire',
              'Maryland',
              'Delaware',
              'New Jersey',
              'North Carolina',
              'South Carolina',
              'Georgia',
              'Florida']
 print(df['States'])

 Out:
                 States
       0         Virginia
       1    Massachusetts
       2            Maine
       3         New York
       4     Rhode Island
       5      Connecticut
       6    New Hampshire
       7         Maryland
       8         Delaware
       9       New Jersey
       10  North Carolina
       11  South Carolina
       12         Georgia
       13         Florida
       14       Wisconsin
       15        Michigan
       16            Ohio
       17    Pennsylvania
       18        Illinois
       19         Indiana
       20       Minnesota
       21        New York
       22      Washington
       23          Oregon
       24      California

A:

Whilst Andy's answer works it is not the most efficient way of doing this. There is a handy method that can be called on almost all pandas Series-like objects: .isin(). Entries to this can be lists, dicts and pandas Series.
df = pd.DataFrame(['Virginia','Massachusetts','Maine','New York','Rhode Island',
                   'Connecticut','New Hampshire','Maryland', 'Delaware',
                   'New Jersey','North Carolina', 'South Carolina','Georgia','Florida',
                   'Wisconsin','Michigan', 'Ohio','Pennsylvania','Illinois',
                   'Indiana','Minnesota','New York','Washington','Oregon',
                   'California'],
                  columns=['States'])

Atlantic_states = ['Virginia', 'Massachusetts', 'Maine', 'New York','Rhode Island',
                   'Connecticut', 'New Hampshire',  'Maryland', 'Delaware',
                   'New Jersey', 'North Carolina', 'South Carolina', 'Georgia',
                   'Florida']

df['Coast'] = np.where(df['States'].isin(Atlantic_states), 'Atlantic Coast',
                       'Unknown')
df.head()

Out[1]:

    States          Coast
0   Virginia        Atlantic Coast
1   Massachusetts   Atlantic Coast
2   Maine           Atlantic Coast
3   New York        Atlantic Coast
4   Rhode Island    Atlantic Coast

Benchmarks
Here are some timings using for mapping the first 10 letters of the alphabet to some random int numbers:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=0, high=26, size=(1000000,1)),
                  columns=['numbers'])
letters = dict(zip(list(range(0, 10)), [i for i in 'abcdefghij']))

for apply
%%timeit
def is_atlantic(state):
    return True if state in letters else False

df.numbers.apply(is_atlantic)

Out[]: 1 loops, best of 3: 432 ms per loop

Now for map as suggested by JohnE
%%timeit
df.numbers.map(letters)

Out[]: 10 loops, best of 3: 56.9 ms per loop

and finally for isin (also suggested by Nickil Maveli)
%%timeit
df.numbers.isin(letters)

Out[]: 10 loops, best of 3: 20.9 ms per loop

So we see that .isin() is much quicker than .apply() and twice as quick as .map().
Note: apply and isin just return the boolean masks and map fills with the desired strings. Even so, when assigning to another column isin wins out by about 2/3 of the time of map.


Q:

Linetype and Guide options for ggplot2 when using geom_smooth with continuous variables

I am using ggplot2 and the geom_smooth functions to make predicted lines from a lm model. I am using continuous y and x functions in my ggplot code.
I am trying to create a different line type for each line in the plot (which is the variable "location" ranging from -1,0, or 1), and I would like each location listed in the guide (where -1 = Location A, 0 = Location B, and 1 = Location C). A replicable excerpt of my code is below:
#test scores that range from 1 to 7
score <- c(6, 3, 5, 6, 7, 2, 4, 6, 3, 5, 4, 3, 3, 1, 3, 3, 3, 5, 2, 3, 2, 2, 7, 3, 7,     5, 4, 1, 3, 2, 7, 6, 6, 3, 6)
#location of the school
location <- c(1,  0,  0,  0,  1,  1,  1, -1,  1, -1,  0, -1,  0,  1,  0,  0,  0, -1,     0, -1,  0, -1,  0,  0,  0,  0,  0, -1,  0, -1,  0,  0,  0,  1,  0)

IQ <- c(0.7171425604,    0.7056850461,    1.3929736220,    0.0633936624,   -0.6872828336,   -1.3665840767,    1.4368569944, 0.7297599487,   -0.5735047485,   -0.6752912747,   -0.6213572428,   -0.6110533924,   -0.7090921238,    0.0501744806, 1.3916802944,   -0.0055243194,    1.3619753292,    1.4406369365,    0.6529601586,    0.0538097896,    1.3821853866, 1.3870600993,    0.0040551996,    0.6600558495,    1.3550162100,    1.3081187951,   -1.7541949601,    1.3768167017, -0.6232446826,   -1.2793074919,    0.0560708725,   -0.5993356051,   -0.5857733192,   -0.6005459705,   -0.6659873442)

df <- data.frame(score, location, IQ)

p1 <- ggplot(data=df,aes(y=score,x=IQ,shape=factor(location))) +
geom_smooth(method = "lm", se=F) + scale_y_continuous("Test Score",limits=c(1,7)) +
scale_x_continuous("IQ level", limits=c(-2.45, 1.45)) +
theme_bw() +
theme(axis.text.x=element_text(size=rel(1.2), color = 'black'),
    axis.title.x=element_text(size=rel(1.3)),
    axis.title.y=element_text(size=rel(1.3)),
    axis.text.y=element_text(size=rel(1.2), color = 'black'),
    panel.grid.minor=element_blank(),
    panel.grid.major.x=element_blank(),
    panel.grid.major.y=element_blank(),
    axis.ticks.y = element_blank(),
    panel.border = element_blank(),
    plot.title = element_text(size = rel(1.4)))

print(p1)

Whenever I try to add linetype or the manual linetype, I keep getting errors about how linetype cannot be mapped with continuous variable (only discrete).  Is there any way around this or should I be using a different function? Maybe create labels for the values in location (School 1, School 2, and School 3?) beforehand? Or should I be using some alternative to linetype? I cannot find a solution online or in Wickham's book. Thank you!

A:

You are getting this error message because location is continuous variable (numeric variables are treated as continuous in ggplot) and for linetype= only discrete variables can be used. To use it for linetype= convert location to factor. To change labels in legend use scale_linetype() and provide argument labels=.
ggplot(data=df,aes(y=score,x=IQ,linetype=factor(location))) +
  geom_smooth(method = "lm", se=F) + scale_y_continuous("Test Score",limits=c(1,7)) +
  scale_x_continuous("IQ level", limits=c(-2.45, 1.45)) +
  scale_linetype(labels=c("Location A","Location B","Location C"))


Q:

How to access nested Unity Dependency Injection created objects?

This is a beginner question for Unity so forgive me.
In my Unity Config I have the following that creates my database context (Entity Framework), Unit of Work, and a Repository pattern object (from reverse pocos and generic repo/uow):
container
.RegisterType<IDataContextAsync, myDbContext>(
    new PerRequestLifetimeManager(),
    new InjectionConstructor(new object[] { connString }))
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Contact>, Repository<Contact>>()

In Microsoft MVC, my controllers are injected with services:
public myController(IContactService contactService) {
    _contactService = contactService;
}

My services are injected with repositories:
public class ContactService : Service<Contact>, IContactService
{
    public ContactService( IRepositoryAsync<Contact> repository) {...}
}

Everything works well but I'm not sure how to access the Unity created Unit of Work object in the Controller to save changes: UnitOfWork.SaveChangesAsync()
Without DI, here's how to create the objects:
IRepositoryProvider repoProvider = new RepositoryProvider( new RepositoryFactories());
IDataContextAsync context = new MyDbContext();
IUnitOfWorkAsync uow = new UnitOfWork(context, repoProvider);
IRepositoryAsync contactRepo = new Repository<Contact>(context, uow);

...  // database changes

uow.SaveChangesAsync(); // In the Controller

The obvious thing to do is reference a UOW in the Controller constructor function, but how would Unity use that same object for the Service, and how would the Service use it for the Repositories?

A:

You have already solved your own problem...
Your UnitOfWork class is registered with the PerRequestLifetimeManager.  This lifetime will ensure that anytime a UOW is resolved within the same MVC request you will receive the same instance.  So you will automatically get the same instance of your UOW passed to your controller constructor as you will get passed to your repository constructor.


Q:

reset toggle when screen resizes (multiple styles)

I have a site that has its navigation expand when a button is clicked/toggled (#nav-icon); one click 'open' next click' closed' etc. #main contains the site content, #mytopnav is the navigation. It is 'pushed down' by by adding
 top-margin:85vh and height when clicked.
js
$(document).ready(function () {
    // Animate Toggle button
    $('#nav-icon').click(function () {
        $(this).toggleClass('open');
        $('#main').toggleClass('openMargin');
        $('#myTopnav').toggleClass('openHeight');
    });
});

css
#nav-icon { position: absolute; ...
#nav-icon.open { top: 80vh; }

@media screen and (max-width: 768px) {

.openHeight { height: 80vh; }
.openMargin { margin-top: 80vh; }

}

html
<button id="nav-icon" class="navbar-toggler" type="button" onclick="toggleNav()">

</button>

The issue I have is when the screen is resized, the menu remains open (and all he styles applied when the button was clicked remain on.
Basically I want it to be 'reset' when the screen is resized. Essentially the equivalent as if they clicked the button again before resizing the screen.

A:

A working example would have helped understanding the problem and suggesting the code but what i undertand that you want to remove the open,openMargin and openHeight classes from #nav-icon,#main and #myTopnav if the window is resized and want the menu to reset to its default position before it was clicked.
You can use javascript to detect if the window was resized and remove the class from the #nav-icon,#main and #myTopnav elements by adding the below code before the  tag
jQuery(function ($) {
    $(window).resize(function (event) {
        $("#nav-icon").removeClass("open");
        $("#main").removeClass("openMargin");
        $("#myTopNav").removeClass("openHeight");
    });
});

if you like to limit the above functionality to a specific width only lets say you dont want the styles to be reset unless the resize window width reaches 780px then you can wrap the inner code in the check
jQuery(function ($) {
    $(window).resize(function (event) {
        if ($(this).width()<=780) {
            ..///rest of the code
        }
    });
});


Q:

Show/Hide IDs with multiple radio buttons and IDs

So I have run into a little problem. I am making a Contact Form that changes according to the Users needs.
This is my html code. My goal is to First, Hide most of the Content with the first set of raio buttons. I actually managed to get that with this Javascript:

$(function() {
  $('#report').on('click', function() {
    if ($(this).is(':checked')) {
      $('#phonenumber').hide();
      $('#dateofplay').hide();
      $('#customertype').hide();
      $('#studentprices').hide();
      $('#privateprices').hide();
      $('#companyprices').hide();
      $('#customsetup').hide();
    } else {
      $('#phonenumber').show();
      $('#dateofplay').show();
      $('#customertype').show();
      $('#studentprices').show();
      $('#privateprices').show();
      $('#companyprices').show();
      $('#customsetup').show();
    }
  })
  $('#booking').on('click', function() {
    if ($(this).is(':checked')) {
      $('#phonenumber').show();
      $('#dateofplay').show();
      $('#customertype').show();
      $('#studentprices').show();
      $('#privateprices').show();
      $('#companyprices').show();
      $('#customsetup').show();
    } else {
      $('#phonenumber').hide();
      $('#dateofplay').hide();
      $('#customertype').hide();
      $('#studentprices').hide();
      $('#privateprices').hide();
      $('#companyprices').hide();
      $('#customsetup').hide();
    }
  })
  $('#student').on('click', function() {
    if ($(this).is(':checked')) {
      $('#privateprices').hide();
      $('#companyprices').hide();
    } else {
      $('#privateprices').show();
      $('#companyprices').show();
    }
  })
});

      Booking Form

      <form method="post" action="">

          <fieldset data-role="controlgroup">
            <legend>While the page is still under developement please define your inquiry: </legend>
            <input type="radio" name="settings" id="report" value="report">
            Bug Report
            <input type="radio" name="settings" id="booking" value="booking" checked="checked">
            Booking
          </fieldset>

          First Name:
          <input type="text" name="firstname" id="firstname" value="" placeholder="First Name...">

          Last Name:
          <input type="text" name="lastname" id="lastname" value="" placeholder="Last Name...">

          E-Mail
          <input type="email" name="email" id="email" value="" placeholder="E-Mail...">

          Phone:
          <input type="tel" name="tel" id="tel" value="" placeholder="Phone #...">

          Date of event:
          <input type="date" name="date" id="date" value="" placeholder="Please choose a Date">

          Write a quick Message:
          <textarea cols="40" rows="8" name="message" id="message" placeholder="Your Message here..."></textarea>

          <fieldset data-role="controlgroup">
            <input type="radio" name="customertype" id="student" value="Student/Apprentice">Stundent/Apprentice
            <input type="radio" name="customertype" id="private" value="private" checked="checked">Private
            <input type="radio" name="customertype" id="company" value="company">Company
          </fieldset>

          <fieldset data-role="controlgroup">
            <input type="radio" name="studentprice" id="studentminimal" value="studentminimal" checked="checked">Minimal
            <input type="radio" name="studentprice" id="studentsoundonly" value="studentsoundonly">Sound Only
            <input type="radio" name="studentprice" id="studentsoundandlight" value="studentsoundandlight">Sound and Light
            <input type="radio" name="studentprice" id="studentpartypackage" value="studentpartypackage">Total Party Package
            <input type="radio" name="studentprice" id="studentcustom" value="0">Custom
          </fieldset>

          <fieldset data-role="controlgroup">
            <input type="radio" name="privateprice" id="minimal" value="150" checked="checked">Minimal
            <input type="radio" name="privateprice" id="soundonly" value="200">Sound Only
            <input type="radio" name="privateprice" id="soundandlight" value="300">Sound and Light
            <input type="radio" name="privateprice" id="partypackage" value="400">Total Party Package
            <input type="radio" name="privateprice" id="custom" value="0">Custom
          </fieldset>

          <fieldset data-role="controlgroup">
            <input type="radio" name="companyprice" id="companyminimal" value="200" checked="checked">Minimal
            <input type="radio" name="companyprice" id="companysoundonly" value="300">Sound Only
            <input type="radio" name="companyprice" id="companysoundandlight" value="400">Sound and Light
            <input type="radio" name="companyprice" id="companypartypackage" value="500">Total Party Package
            <input type="radio" name="companyprice" id="companycustom" value="0">Custom
          </fieldset>

          <fieldset data-role="controlgroup" id="customsetup">
            <legend>Custom choices:</legend>
            <input type="checkbox" name="speakers" id="speakers" value="">Speakers
            <input type="checkbox" name="subwoofer" id="subwoofer" value="">Subwoofer
            <input type="checkbox" name="lighting" id="lighting" value="">Lighting
            <input type="checkbox" name="strobe" id="strobe" value="">Strobelight
            <input type="checkbox" name="fog" id="fog" value="">Fogmachine
            <input type="checkbox" name="table" id="table" value="">Table
          </fieldset>

          <input type="submit" name="submit" value="Submit" data-inline="true">
          <input type="reset" name="reset" value="Reset" data-inline="true">

      </form>

I think the problem is that, because the first show/hide function is hiding/showing the ID's it overrides any following function. I can't wrap my head around how I can continue the code so the radio buttons that are not required are hidden.
So if,
#student is selected, #privateprices and #companyprices choices are hidden
#private is selected, #studentprices and #companyprices choices are hidden
#company is selected, #studentprices and #privateprices choices are hidden
Is it even possible or is there a easier more effective method of achieving this? Especially when I start creating the php for the form? Thanks in advance
EDIT: The last piece of code in the Javascript is my attempt hide the first set of radiobuttons.

A:

You can check which radio button is selected in page loading and show / hide the panels. Please see working fiddle here:
https://jsfiddle.net/ranjitsachin/Leav016c/2/
$('#student').on('click', function() {
     if ($(this).is(':checked')) {
        $("#studentprices").show();
        $('#privateprices, #companyprices').hide();
   }
});
$('#private').on('click', function() {
    if ($(this).is(':checked')) {
        $("#privateprices").show();
        $('#studentprices, #companyprices').hide();
    }
});
 $('#company').on('click', function() {
    if ($(this).is(':checked')) {
        $("#companyprices").show();
       $('#studentprices, #privateprices').hide();
    }
});


Q:

Count elements and find the maximum

I've got a table like this:
+-----+-----+-----+
| uid | aid | tid |
+-----+-----+-----+
| 1   | 6   | 7   |
+-----+-----+-----+
| 2   | 6   | 7   |
+-----+-----+-----+
| 3   | 5   | 7   |
+-----+-----+-----+
| 4   | 5   | 7   |
+-----+-----+-----+
| 5   | 5   | 7   |
+-----+-----+-----+

I'm expecting to find, for each tid, which aid has more elements.
For example, i know that tid 7 has 2 times aid 6, like this.
+
-----+-----+-------+
| tid | aid | count |
+-----+-----+-------+
| 7   | 6   | 2     |
+-----+-----+-------+
| 7   | 5   | 3     |
+-----+-----+-------+

The final result I'm expecting is 7 5 3, because I want the maximum count.
I've achieved my desired result using two queries:
CREATE TABLE temp AS
SELECT tid, aid, count(aid) as c
FROM startingtable
GROUP BY tid, aid
ORDER BY tid, aid;

and then
CREATE TABLE result AS
select a.tid, a.aid, a.c
from temp a
inner join
(SELECT tid, max(c) as m
FROM temp
GROUP BY tid) b
on a.tid = b.tid and a.c = b.m
order by tid;

I need it to be functional using just one query. How would you do that?
Thank you for your time.

A:

You can try to use self-join with subquery.
CREATE TABLE temp AS
SELECT t1.*
FROM (
    SELECT tid,
           aid,
           count(aid) as cnt
    FROM startingtable
    GROUP BY tid, aid
) t1 JOIN (
    SELECT tid,
           MAX(cnt) maxcnt
    FROM (
        SELECT tid,
           aid,
           count(aid) as cnt
        FROM startingtable
        GROUP BY tid, aid
    ) t2
    GROUP BY tid
)t2 ON t1.tid = t2.tid and t1.cnt = t2.maxcnt

another way you can try to use CTE with Row_number window function to insert your data to the table.
WITH CTE AS (
    SELECT tid,
       aid,
       count(aid) as cnt
    FROM startingtable
    GROUP BY tid, aid
)
insert into #temp (tid,aid,cnt)
select t2.tid,
       t2.aid,
       t2.cnt
from (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY tid order by cnt desc) rn
    FROM CTE
) t2
where rn = 1


Q:

In Azure, how to change the authentication of the server?

When spinning up a linux virtual machine, I have chosen the authentication type as password. Now I want to change to ssh. How to achieve this?
Thanks

A:

You can use Azure portal to reset password, like this:

If you want to change authentication type, you can follow this steps:
1. Create an SSH key pair
ssh-keygen -t rsa -b 2048

2. rename id_rsa.put to authorized_keys
mv /home/user/.ssh/id_rsa.pub /home/user/.ssh/authorized_keys

3.Copy id_rsa to your local, then you can use this key to SSH it.


Q:

What are the rules for Chrollo to steal an ability?

Chrollo, the leader of the Phantom Troupe possess a book which contains all of the abilities that he has stolen from other Nen Users. When he opens the book to a specific page where an ability is, he can use that ability.
We know that some conditions are needed to be complete before a certain ability can be activated.
My question is 'what are the rules that Chrollo needs to complete before he can steal the ability?'

A:

For Chrollo to steal a Nen ability from another Nen user four conditions must be met:

He must witness the Nen ability in action with his own eyes.
He must ask about the ability and be answered by the victim.
His victims palm must touch the handprint on the cover of Bandit's Secret.
All of the above must be completed within an hour.

Chrollo can only use a stolen ability when he has the Bandit's Secret open and on the page of the ability he wishes to use. The book must remain open and on that particular page for the full duration of the ability he choses, he can not close the book and still use the ability. Ref(Chrollo Lucilfer)


Q:

How to write linq query from sql query using LINQ?

I have a table with two columns like BookingArrivedEnquiredTime with varchar datatype and datetime BookingArrivedEnquiredDateTime. When I execute this query in SQL Server the result give perfect with time sorted order
the sql query will be like
select BookingArrivedEnquiredTime from BookingArriveds where BookingArrivedEnquiredDateTime='2015-02-17 00:00:00.000'
order by CAST(('01/01/2000 ' + BookingArrivedEnquiredTime) AS DATETIME)

and it gives out put like this
11:27 AM
11:47 AM
11:53 AM
12:13 PM
12:50 PM
02:02 PM
02:47 PM
03:04 PM
03:16 PM

When i try this query into using linq
public ViewResult Index1(DateTime? Startdate)
{
    Startdate = DateTime.Now.Date;
    var fm = DateTime.Parse("01/01/2000");
    var qr = from item in db.BookingArriveds
             where item.BookingArrivedEnquiredDateTime == Startdate
             orderby DateTime.Parse("01/01/2000 " +
             item.BookingArrivedEnquiredTime.ToString())
             select item;
     return View(qr);
}

but it gives error like this

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated
  into a store expression.

where is wrong and I need help for how to rewrite  above sql query to linq query also casting from varchar to datetime in linq?

A:

You have two options:
you can do the casting and sorting on client:
db.BookingArriveds
  .Where(item => item.BookingArrivedEnquiredDateTime == Startdate)
  .AsEnumerable()
  .OrderBy(item => DateTime.Parse("01/01/2000 " + item.BookingArrivedEnquiredTime);

or you can use SqlFunctions.DatePart to do the cast in Sql server: https://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx
EDIT: DatePart function is not suitable, because it gives you only date part. To do the casting in SQL server, you should define your own sql function: https://msdn.microsoft.com/en-us/library/vstudio/dd456847(v=vs.100).aspx
The question is, why are you storing BookingArrivedEnquiredTime in a varchar column. I believe it should be part of BookingArrivedEnquiredDateTime or it should be stored as integer or numeric column


Q:

how to override the save-file command in org-babel

I really like the org-babel that enables me to organize my scripts in org-mode, however, i found there are some issues with the org src buffer when i edit the source code in a separate buffer (using keybinding C-c ').
first thing is, even i explicitly run write-file, and then specifies the file path and name to save, the buffer is not saved to that file, but the source code block in the .org file gets updated and the .org -file is saved.
second thing is, whenever i run save-buffer in org src buffer, the buffer screen will automatically scroll down till current mouse position is the last line in the buffer. this is annoying because sometimes i lose tracking my scripts.
i am not so familiar with elisp, and can only do simple work like define-key or add-hook, i hope i can get help from here. thanks

A:

Org-babel is not meant for organizing scripts, but for including source code as part of your document.
You may be interested in tangling, which allows to join and extract source code blocks from your orgmode document into separate files.
The following example will merge 2 source code fragments into the file test.m when tangling (org-babel-tangle, bound to C-c C-v t):
* Tangling example

Set up a vector:

#+begin_src octave :tangle test.m
  a = 1:10;
#+end_src

Then find out squares

#+begin_src octave :tangle test.m
  b = a.^2
#+end_src


Q:

Custom Combobox with values

I have a windows application with multiple Forms containing the same ComboBoxes.
These Comboboxes have fixed items. On each Form I load the Comboboxes with these values.
For example:
Public Sub New()
   InitializeComponent()
   With Combobox1.Items
         .Insert(0, "Value1")
         .Insert(1, "Value2")
         .Insert(2, "Value3")
   End With
   With Combobox2.Items
         .Insert(0, "Value4")
         .Insert(1, "Value5")
         .Insert(2, "Value6")
   End With
End Sub

I don't want to repeat this code on every Form so, is there a way to create a custom Combobox that is pre-filled with these values, and then inherit the Comboboxes on each Form? Or is there another proper solution?
UPDATE 1
Based on jmcilhinney's comment, I have created this class
 Public Class ComboClass
    Inherits System.Windows.Forms.ComboBox
    Public Sub New()

    End Sub

    Sub New(ByVal sender As String)
        If sender = "R" Then
            With Items
                    .Insert(0, "Value1")
                    .Insert(1, "Value2")
                    .Insert(2, "Value3")
            End With
        Else
                With Items
                    .Insert(0, "Value4")
                    .Insert(1, "Value5")
                    .Insert(2, "Value6")
                End With
        End If
    End Sub
End Class

And then I added the new custom control to my Form.
In the Private Sub InitializeComponent() method designer code, I have the following:
Me.Combobox1 = New MyApplication.ComboClass("R")
Me.Combobox2 = New MyApplication.ComboClass("A")

I get the following designer error:
The variable 'Combobox1' is either undeclared or was never assigned.
The variable 'Combobox2' is either undeclared or was never assigned.

I'm missing something but I don't know what it is.
Thanks for your help.

A:

Instead of using the class Constructor (which isn't much useful if you want to create your controls in the Designer), you could add a Public Property that accepts an Enumerator (or even a String value, as you're doing here) that lets you define, at Design Time, pre-defined data sets when the property value is changed.
As a note, avoid tampering with the Designer.vb code. It's handled by the Form Designer, you don't usually write anything here: it will be delete as soon as  the Form design is modified.
The custom Property is called CustomDataSet, here.
The code here also drops down the ComboBox List, so you can see what has been set.
This is how it works:

Imports System.ComponentModel

<DesignerCategory("Code")>
Public Class ComboClass
    Inherits ComboBox

    Public Enum DataSelector
        None = 0
        Set1
        Set2
    End Enum

    Private Selector As DataSelector = DataSelector.None
    Public Sub New()
        MyBase.New()
    End Sub

    <DefaultValue(DataSelector.None)>
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
    Public Property CustomDataSet As DataSelector
        Get
            Return Selector
        End Get
        Set(ByVal value As DataSelector)
            Selector = value
            Me.SetData()
        End Set
    End Property

    Private Sub SetData()
        Me.Items.Clear()
        Select Case Me.Selector
            Case DataSelector.None
            Case DataSelector.Set1
                Me.Items.AddRange({"Value1", "Value2", "Value3"})
            Case DataSelector.Set2
                Me.Items.AddRange({"Value6", "Value7", "Value8"})
            Case Else
                'NOP
        End Select
        If Me.DesignMode Then Me.DroppedDown = True
    End Sub

End Class


Q:

Replace na´s in specific columns by the median of the same columns

I would like to replace the na´s in v1 to v4 with the median of the same columns
Here are some example data
id <- c(1,2,3,4)
v1 <- c(1,3,0,2)
v2 <- c(NA,1,NA,2)
v3 <- c(2,4,1,2)
v4 <- c(NA,1,0,2)
v5 <- c(5,1,NA,2)
v6 <- c(7,1,9,NA)

df <- data.frame(id, v1, v2, v3,v4,v5,v6)
df_pre <- df %>% group_by(id) %>% mutate(Median_v1_v4 = median(c(v1,v2,v3,v4), na.rm=TRUE))

This is what data looks like now:
id v1 v2 v3 v4 v5 v6  Median_v1_v4
 1  1 NA  2 NA  5  7          1.5
 2  3  1  4  1  1  1          2.0
 3  0 NA  1  0 NA  9          0.0
 4  2  2  2  2  2 NA          2.0

This is what i want the data to look like
id v1  v2 v3  v4 v5 v6 Median_v1_v4
1  1 1.5  2 1.5  5  7          1.5
2  3 1.0  4 1.0  1  1          2.0
3  0 0.0  1 0.0 NA  9          0.0
4  2 2.0  2 2.0  2 NA          2.0

A:

What about this solution:
df[,2:5] <- t( apply(df[,2:5], 1, function(x) {
  x[is.na(x)] <- median(x,na.rm=T)
  return(x)}
) )

df

  id v1  v2 v3 v4 v5 v6
1  1  1 1.0  2  1  5  7
2  2  3 1.0  4  1  1  1
3  3  0 0.5  1  0 NA  9
4  4  2 2.0  2  2  2 NA

Adjusted from: Replace NA values by row means
PS: Saw the comment too late (@Sai Saran), this is an adjustment of the solution in the link above.


Q:

Convert MySql query in JPA Spring Boot query

I have this query, working, but I should use it in spring boot,
SELECT username
FROM user
WHERE enabled = 1
AND id IN (SELECT makerprofile_user_id
           FROM makerprofile_has_job
           WHERE job_id = (SELECT id
                           FROM job
                           WHERE job = "photographer"))

This is the part of the Job class
@JoinTable(name = "makerprofile_has_job", joinColumns = {
        @JoinColumn(name = "job_id", referencedColumnName = "id")}, inverseJoinColumns = {
        @JoinColumn(name = "makerprofile_user_id", referencedColumnName = "user_id")})
    @ManyToMany
    @JsonIgnore
    private List<Makerprofile> makerprofileList;

and I write this, but it does not work
@Query("SELECT a.username\n"
            + "FROM ApplicationUser a \n"
            + "WHERE a.enabled = 1 \n"
            + "AND a.id IN(SELECT p.id\n"
            + "        FROM Job m\n"
            + "        JOIN m.makerprofileList p"
            + "            WHERE p.id = (SELECT j.id\n"
            + "              FROM Job j\n"
            + "              WHERE j.job = :job))")
    List<String> findUsernameByJob(@Param("job") String job);

who can help me? (excuse me, but this is my first question on Stack)

A:

You can use one of the following ways:

Use EntityManager.createNativeQuery() API
Use @NamedNativeQuery annotation. Or @Query(value = "sql here", nativeQuery = true)


Q:

Java code Optimization and Safe

class Testing{
    private static int counter;
    private static int[] intArray;
    public static ReturnClassName className(File f){
        ReturnClassName returnCN= new ReturnClassName();
        byte[] b;
        try{
            DataInputStream dataIStream= new DataInputStream(new FileInputStream(f));
            intArray= new int[dataIStream.available()];
            b= new byte[dataIStream.available()];
            dataIStream.read(b);
            intArray= b;
            // setting methods for ReturnClassName
            // counter increment
            returnCN.setNumber(someMethod(5));
            }//catch() block

    return returnCN;
}
private static int[] someMethod(int l){
    return Arrays.copyOfRange(intArray, counter, counter + l);
}

Or
class Testing{
    private static int counter;
    public static ReturnClassName className(File f){
        ReturnClassName returnCN= new ReturnClassName();
        byte[] b;
        try{
            DataInputStream dataIStream= new DataInputStream(new FileInputStream(f));
            intArray= new int[dataIStream.available()];
            b= new byte[dataIStream.available()];
            dataIStream.read(b);
            intArray= b;
            // setting methods for ReturnClassName
            // counter increment
            returnCN.setNumber(someMethod(intArray,5));

    }//catch() block

    return returnCN;
}

private static int[] someMethod(int[] iArray, int l){

    return Arrays.copyOfRange(iArray, counter, counter + l);
}

I want to know which one is more optimized and safe of the above two codes.
Also while passing the array in the 2nd code, is it passing the whole array or just the address of that array. Like both intArray and iArray are pointing to the same integer array?

A:

Arrays are passed by reference so both snippets are equivalent concerning efficiency except for the fact that if you are not using intArray for some other purpose: The second version will unreference the array and make it a candidate for garbage collection.
This is, in the second case, the array will be a candidate to be collected as soon as someMethod execution returns whereas the first version will keep the array referenced until the program ends since it is static.
From your comments I understand that you will call className once per file for different files and for each file you will call 'someMethod' many times. Then I like a solution similar to the firstone at some points but different to both the first and the second one.
That solution is to have a instance of Testing for each file you load data from:

Force each instance to be associated with a concrete file.
Make methods and attributes not static. This is for each Testing element to have its own data loaded from its file.
Change className so it will load data from its file only once.
Make a right user of Testing and its instances.
class Testing{

    public Testing(File f)
    {
        this.f = f;
    }

    private File f;
    private int[] intArray;
    public static ReturnClassName className(){
        ReturnClassName returnCN= new ReturnClassName();
        byte[] b;
        if(intArray == null || intArray.length > 0) return //If it was called before, then we don't load the file again.
        {
            try{
                DataInputStream dataIStream= new DataInputStream(new FileInputStream(f));
                intArray= new int[dataIStream.available()];
                b = new byte[dataIStream.available()];
                dataIStream.read(b);
                intArray= b;
                // setting methods for ReturnClassName
                // counter increment
            } catch(Exception e) {
            ...
            ...
            }
        }
        returnCN.setNumber(someMethod(5));
        return returnCN;
    }

    private int[] someMethod(int l){
        return Arrays.copyOfRange(intArray, counter, counter + l);
    }
}

Example of use:
Testing forFile1 = new Testing(fileObj01);
ReturnClassName x = ReforFile1.className();
ReturnClassName y = ReforFile1.className();

Testing forFile2 = new Testing(fileObj02);
ReturnClassName z = ReforFile2.className();
ReturnClassName w = ReforFile2.className();

You could, on the other hand, implement a better solution were you have a map of integer arrays indexed by the input file (like a cache) and you keep a copy if their bytes on it. Having thus a single instance od Testing and keep File f as input parameter for 'className'.