Two appliances with connection cords sharing power outlet

Question: I have my dishwasher and my garbage disposal fed from two separate electrical circuits but sharing the same power outlet under the sink. I broke off the tabs on the outlet and connected it to two cables/circuits. The garbage disposal is side is controlled by a switch while the dishwasher one is always on.
I was planning to use connection cords for both, which look like this:

but, because of the 90 deg angle, only one can be plugged in a conventional double outlet where each twin outlet is positioned the same way. At best, I can plug this and another plug which comes straight out of the cable and not at a right angle.
I am noticing that all connector cords come at a right angle and not straight, which would make them more convenient, and was wondering if there is a technical reason for it, as in maybe only one such cord should be plugged in a single box in the wall. Is there a way for me to somehow override the default configuration and plug this into a very short extension cord that plugs into the wall straight, or is that a code violation?

Alternatively, do they make double outlets where the twins are positioned opposite ways, which could support two of these plugs facing away from one another?
Comment: google `sideways power outlet`
Comment: Can you post the model #s of the disposal and dishwasher?
Answer: Many of these cords are made this way to reduce the stress on the wires inside caused by having the appliances then shoved up against them. There are many cords available which are not made with the 90 degree angle. You just have to go to your store and find them.
Here's an example of one from Amazon:

They have dishwasher cords similar to this too. Keep in mind that dishwashers need to have GFCI protection so you might want to add a two gang box and have two outlets, which would allow you to use the cords you originally wanted to. Good luck.
Comment: GFCI can be at the breaker. Double gang box as a solution is really independent of whether there is GFCI at this location, at the breaker or not at all.
Comment: This is location-specific. Not every location requires GFCI for dishwashers
Answer: Widen your search for cordage
They're not all straight-down 90's (maybe in that store or vendor).  You need any appliance cord that is of sufficiently large ampacity - e.g. 12 AWG is a little excessive for a cord with a NEMA 5-15 plug on it, but it assures legality/safety (nobody can argue with it.
The cordage must be SJOW, SJOOW or any of about a dozen types legal for flexible cord.  The cordage must be marked.   I generally have several sources for it.

Appliance cords with wires or lugs on the other end, just like you're buying, but I widen my search out to places like McMaster-Carr, Galco, Grainger, Mouser, Digi-Key etc.  I routinely buy straight-out 12 AWG cords from McMaster-Carr.
A factory-built extension cord with molded-on socket and plug, marked on the cordage with correct gauge and type(SJOOW etc.)  SNIP! goes the socket end, and now I have an appliance cord.
Dead appliances, again of appropriate wire gauge and markings on the cordage itself.
Bare Cordage bought from the electrical supply house of correct rating, and a field-attachable plug with appropriate strain relief for the cordage (i.e. Not random Home Depot plugs, which are sized for 16 AWG).  This must be cordage, never house wiring such as NM, UF, AC, BX etc.

I am not a fan of field-attachable plugs anywhere near where water might be, unless the plug is protected by GFCI.
Must be handle-tied
Glad we caught you on this; an important part of Code requires that the 2 circuits be handle-tied since they are on the same yoke (receptacle).  The handle-ties must be proper, UL listed items for that breaker, you can't use a nail (and the breaker must be UL listed or classified for that panel).
Handle-ties can be annoying to find, especially for double-stuff breakers, so we recommend using a 2-pole breaker instead simply because everyone sells them.  The only difference between a 2-pole breaker and 2 handle-tied breakers is that a 2-pole breaker guarantees common trip.  This doesn't require common trip, just common maintenance shuoff.
Since you wired independent neutrals, the two circuits are allowed to be on the same pole.  However, it will be difficult to arrange them on the same pole with handle-ties, and impossible with 2-pole.  (A 3-pole/phase breaker or tie would do, but then, you'd have an unrelated or dead circuit in the middle - yet another reason plenty of extra panel spaces are always a good idea.)
Breaker ampacity must exactly match socket ampacity
You know how normally, you can put the common NEMA 5-15 receptacles on 20A circuits just fine? Not here.
Because this feeds precisely one socket, the breaker must match the socket exactly.  If your breakers are 20A, you must use a NEMA 5-20 receptacle, not 5-15.
Hardwire it
You're not required to use cord-and-plug connection.  You can hardwire one or both appliances.   This also eliminates the handle-tie and receptacle-ampacity problems shown above.
A very easy way to get a port to run the wires into is to use a Surface Conduit Starter Kit.
Comment: I've seen a number of questions about plug-in dishwasher & disposal. Mine (originally installed ~ 20 years ago, replaced one disposal since then without changing the wiring method) are hardwired. Is plug-in now preferred, required, or is hardwired still just fine? Seems to me that for these types of appliances hardwired makes sense.
Comment: @manassehkatz, I'm guessing manufacturers started supplying cordage by default when some locations started requiring GFCI on dishwashers -- it's often much easier to retrofit a GFCI right at the outlet than to have to put it somewhere upstream of a hardwired dishwasher.
Comment: Latest edit confirms that hardwire is OK. Is there anything wrong with (provided it isn't Chicago, etc. and is secured properly and safe from damage) simply running NM from the existing box to the dishwasher and disposal and removing the receptacle? Is surface (or other) conduit actually needed if you're using cable rather than wires?
Comment: @manassehkatz that sounds like "can I use NM instead of cordage".  I would say no, unless you can fully protect the wire in the normal fashion required for the NM wiring method. It's rather hard for the AHJ to argue with using a dishwasher's factory supplied cord, whether it's plug connected or lopped off and hardwired.
Comment: Curiosity got the best of me...I checked my disposals - using NM installed into built-in junction box on each disposal. Dishwashers...not going to mess with them, so I downloaded installation manual for a current mid-range Whirlpool and it has detailed instructions for using a power cord or for hardwire. Dishwasher (can't say they all have this, of course) has a terminal box designed to handle either type of cable/connection.
Comment: @manassehkatz hmmm... If you look at the *rationale* behind the use of cordage vs in-wall cabling, it's pretty clear that cord going through open space to a vibrating thing should *definitely not* be solid-core wire, which cannot flex repeatedly, and will be prone to cracking/breaking/overheating from small cross-section at crack, or arc-faulting.
Comment: That is a quite reasonable point. But the directions (at least on the one installation manual I looked at) don't indicate any special requirements. My guess (just a guess) is that (a) a typical dishwasher is designed that it should not have significant vibrations affection the built-in junction box (those same vibrations would also cause excess noise, which would not be a good selling point) and (b) the OP is falling back on "it has cordage now, so I *assume* that is how it should be connected" instead of checking out what are the actual requirements.


Where does attack helicopter's rockets land?

Question: Some people say it is the "I" sign, others say it is the "crosshair" and some say it is somewhere in the middle.
It would be good to clear this issue up once and for all. Please don't just write "I" or crosshair with no explanation. I am sure there are lots of guys out there with this question in their minds. So for the community to be sure, you need to provide a very solid proof or justification.
Comment: I am so tempted to just write "I" or "crosshair" xD
Comment: :))) That would be an incomplete answer.
Comment: It does depend on the distance to target, but the linked video is very good.
Answer: I suck as a helicoptor pilot, but Munchies is very good. He shows that the best way to line up the rockets is to use the top of the "I" beam.
Comment: I will check this out as soon as possible.
Comment: I downloaded and watched the video numerous times frame-by-frame and still I am not sure about the top of the "I" beam. Just go to 3:00-3:01 and watch it frame-by-frame and you will see that there is no way that the rockets go to the top of the "I". But in some other moments the rockets don't go to the crosshair neither. This is very confusing...
Comment: @Anar you do realize that the heli is not just staying at one place? It moves forward as well(not sure about altitude), so the top of the `I` would go lower and lower the faster you go(I mean the `I` at the moment of a missile impact)
Comment: @Novarg Of course I am taking that into account.
Comment: @Novarg That's why it is hard to pinpoint where the rockets land, hence the question.
Comment: yes, that is true.  So because movement makes the exact location of where the rockets land difficult to determine, if we take movement out of the picture we should be able to tell exactly how it works.  Try parking the heli on the top of a building and then fire the rockets.  That should tell you exactly where on the HUD the rockets land.
Comment: Also, note that the different choppers may use target differently.
Comment: When the helicopter is stationary, both the crosshair and the I-beam are on top of each other and the rockets go to the middle. So it is  not possible to tell to which one they are going.


Is it preferred to set a door slab flush with the jamb face?

Question: I have been watching many videos on how to install door slabs and in particular how to install hinges. I see most videos where the barrel of the hinge is flushed up against the edge of the door slab. However in most real world cases I see hinges that are actually offset from the edge of the door slab, and the barrel is not pressed up against the edge. I have seen a 3/8 to ½  gap from the barrel to the edge of the door.
When I have installed a couple of door, I'm not a carpenter, I have put the barrel of the hinge flushed with the door slab as well as on the jamb side, the barrel is flushed with the jamb's edge. However when doing this the door slab is never flushed with the door jamb edge when it's in the closed position. The door passes the door jamb edge about ½ to ¾ when it's closed, although it is horizontally leveled etc.
In order to get the door leveled on the hinge and stopper side and door slab aligned with the edge of the striker jamb I always need to off set the hinge about 3/8, so the barrel sticks out from the door slab's edge, the same is true on the jamb hinge side. This then allow me to have the door flushed with the jamb on the sticker/stopper side.
I guess my question is, should the door be flushed with the jamb? I have mostly seen it this way, or is it ok for the door to be set in more past the edge of the door jamb when closed. If the latter is the right method and it needs to be flushed with the jamb's edge I cant see how having the hinge barrel butt up against the edge of the slab and jamb making this possible. Most of the videos on YouYube have the barrel flushed up against the jamb and the other videos what do not, never explain why they are leaving an off set or gap between the hinge barrel and the edge of the door slab and jamb.
I'm hoping  a real carpenter can give me the correct answer on this.
Comment: So when closed on the non-stop side of the door jamb, the door surface is proud of the jamb surface?  I don't think carpenters install non pre-hung doors anymore.  My pre-hung doors seem to close and have the non-stop side of the door 1/8" shy of the room side of the jamb, when you add the trim to the door jamb the door is shy of the trim.  The door is generally tight to the stop side of door jamb with minimal reveal.
Answer: This is mostly an aesthetic matter, but at some point it becomes a functional issue. Prefab door sets tend to have the slab flush with the jamb edge. This is how the slab looks best to most people and fits properly against the stops or weatherstripping.
It's completely irrelevant where the hinge barrel falls. Hinge leaves are often wider than the slab, so they protrude a bit. And since modern aesthetic sensibilities have the hinge mortise stop before the back side of the slab, conventional hinge sizes would naturally protrude because they're shifted forward. Here's an example, where the protrusion roughly equals the mortise backset:

source: Amazon
The critical factors:

The door closes without mashing into the stops on the hinge side
The latch side operates well
The offset or recess is consistent around the entire door
You're happy with the appearance

tl;dr It doesn't much matter as long as the door operates properly.
Comment: With the hinges flushed against the door jamb the door goes passed the door jamb edge when closed and to me it just doesn't look right. I find it that I have to set the barrel about 3/8 from the the edges to produced a flushed door to the jamb edge once close. This is something that is never discussed online. The other issue is hinge placement, 10 inches from the bottom or all evenly spaced etc. Its nice to know that there isn't a set preference but these things can be a pain to figure out for the DIYer.   Thanks for your reply.
Comment: I'm not sure I understand the situation as you describe it. It doesn't matter if the barrel is tight to the slab or an inch out. That's not what sets slab position.
Answer:
Most of the videos on YouTube have the barrel flushed up against the jamb and the other videos what do not, never explain why they are leaving an off set or gap between the hinge barrel and the edge of the door slab and jamb.

As DIY I would say it is all in the installation ease.
Barrel flush mount gives instant correct alignment while offset does not.
Comment: Fair point. The drawback is that the mortise would usually need to go the full depth of the slab unless the hinges were undersized. Of course, uniform mortises do the same job.


how to control multiple ajax requests in laravel 5.2

Question: I am working on an application where different ajax requests fires depending upon different actions.
For example, there is a chat window having send button. When i click on that button an empty message is sent with ajax, successfully. It work nice. But when I hit the send button too many times, at start some requests respond 200 (ok) but then it respond 500 (internal server error). Due to this the other requests that are going continuously like updateLastActivity also disturb.
The preview of the error in developer's tool is:
Whoops like something went wrong.
Note: When I make this chat system in core PHP, it work fine. There is no internal server error when I send too may requests.
Here is the code I am using
    //the following code is used to send the message
 $(document).on('click','.send_message_bt',function(event){
     event.preventDefault();

        var id=$(this).data('id');
        var name=$(this).data('name');
        var message=$("#message_field-"+id).val();

    $.ajax({
        //headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
         headers: { 'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!} },
        url:'{{route('user.sendmessage')}}',
        type:'POST',
        data:{
          id:id,
        message:message
           },
        success:function(data,status){
        //clear the message field value
        $("#message_field-"+id).val('');

        //update the chat history
        fetchChatHistory(id,name);

    },
        error:function(response){
           if(response.status==401){
                  alert('You are not logged in!');
                  window.location=window.location.href;
                   }

           }

});

});

here is the back end code
public function sendMessage(Request $request){
    $message=new Userchatmessage();
     $message->message=$request->message;
     $message->sender_id=Auth::user()->id;
     $message->receiver_id=$request->id;
     $message->save();
     return response('success');
}

How to fix this issue.
Comment: Would you mind sharing the error message when you get 500?
Comment: Internal server error is displaing on console.
Comment: Yes. Please copy and paste the console logs.
Answer: I guess it's not a problem with Laravel or anything, but with your browser. Each browser has a maximum amount of simultaneous connections it will open for a certain domain.
Read more about this problem here and here.
If you want to make a realtime chat application, consider using something like NodeJS and Socket.io.
Comment: Then why it don't give error when i make the system in core php instead of Laravel.
Comment: Because the problem is with simultaneous requests. A single PHP file will return a response really quick, where a complete framework like Laravel is a little bit slower.
Comment: probably because Laravel goes through a bunch of function call stacks (that may cause php out of memory/timeout) just to process a request, while in your core php, that's just that.
Comment: Can i use sockets for all of my real time work like...making real time notifications...chat...maintain real time online status etc.
Comment: @habib Yes, this is certainly possible! Just read up on some use cases, tutorials and you'll be implementing those things in no time!
Answer: Async and await can help. Let an async function
async function doAjax(){
    await runFirstAjaxCall();
    await runAfterFirstAjaxCallSuccess();
    ....
    ....
}
doAjax();


case-of / case expression with or in pattern matching possible?

Question: I am learning haskell on my own. And was working on implementing a custom List data type using basic lists and case of.
So data structure is something similar to this
data List = List [String] | EmptyList deriving Show

now if I am doing case expressions for base case, I have to do two matchings. A simple example would be the size function
size :: List -> Int
size lst = case lst of
  (List []) -> 0
  EmptyList -> 0
  (List (x:xs)) -> 1 + size (List xs)

Can't I do something like combining the two base cases of list being empty (List []) and EmptyList somehow to reduce redundancy?
size :: List -> Int
size lst = case lst of
  (List []) | EmptyList -> 0
  (List (x:xs)) -> 1 + size (List xs)

I have tried searching all over the net for this, but unfortunately wasn't able to find anything concrete over matching multiple patterns in one case.
Comment: you could use _  that cover all other options so do the non empty first and use _ for the rest of your cases
Comment: If you are learning on your own then I would have a look at this one `data List' a = Empty | Node a Int List'`.
Comment: Ocaml has "or patterns" similar to the one you mention, but Haskell does not. You need to use two `case` branches. Alternatively, one could exploit view patterns / pattern synonyms to create a single branch, but that would require some preliminary boilerplate, making the code longer.
Comment: I would prefer to use pattern matching that explicit `case` statements - but either way you need separate cases for these 2. The only way I think to use a single statement with an "or" operator is to use guards - which I personally find less readable here than putting each case on a separate line. In any case, the best solution here to reducing redundancy is to use a type which doesn't have this redundancy built in. (ie. it has only one way to represent the empty list)
Comment: Are there *any* functions which should return different results for `EmptyList` and `List []`? What do they do?
Comment: @DanielWagner nope there are no such functions. That's why I wanted to combine the two cases. I know how to do it using guards or multiple declarations but was wondering if this could be achieved using case expressions or not.
Comment: @dave yep good point, I guess I'll have to go with that. But still, I'm kinda surprised at this limitation.
Answer: First of all you should consider why you have separate constructors for List and EmptyList in the first place. The empty list clearly is already a special case of a list anyway, so this is an awkward redundancy. If anything, you should make it
import Data.List.NonEmpty
data List' a = NEList (NonEmpty a) | EmptyList

Another option that would work for this specific example is to make the empty case into a "catch-all pattern":
size :: List -> Int
size lst = case lst of
  (List (x:xs)) -> 1 + size (List xs)
  _ -> 0

BTW there's no reason to use case here, you can also just write two function clauses:
size :: List -> Int
size (List (x:xs)) = 1 + size (List xs)
size _ = 0

Anyways – this is generally discouraged, because catch-all clauses are an easy place for hard to detect bugs to creep in if you extend your data type in the future.
Also possible, but even worse style is to use a boolean guard match – this can easily use lookups in a list of options, like
size lst | lst`elem`[EmptyList, List []] = 0
size (List (x:xs)) = 1 + size (List xs)

Equality checks should be avoided if possible; they introduce an Eq constraint which, quite needlessly, will require the elements to be equality-comparable. And often equality check is also more computationally expensive than a pattern match.
Another option if you can't change the data structure itself but would like to work with it as if List [] and EmptyList were the same thing would be to write custom pattern synonyms. This is a relatively recent feature of Haskell; it kind of pretends the data structure is actually different – like List' – from how it's really layed out.
Comment: Size was just an example function. But I like your idea of `_`  as I can use it to achieve the same in cases I suppose.
I am aware of how it can be achieved using guards/multiple declarations. What I was wondering whether it was possible to combine cases together or not.
Comment: `elem` introduces an Eq constraint, which is quite a bummer for this function
Comment: @amalloy yes – that's what I meant with "even worse style", but I should have elaborated.
Answer: In the comments, you say

there are no such functions [which should return different results for EmptyList and List []]

therefore I recommend merging these two constructors in the type itself:
data List = List [String] deriving Show

Now you no longer need to distinguish between EmptyList and List [] in functions that consume a List.
...in point of fact, I would go even further and elide the definition entirely, simply using [String] everywhere instead. There is one exception to this: if you need to define an instance for a class that differs in behavior from [String]'s existing instance. In that exceptional case, defining a new type is sensible; but I would use newtype instead of data, for the usual efficiency and semantics reasons.


here, for a non prime number, the break statement in the inner loop is executed but the else statement of the outer loop is not executed, why?

Question: L = []
nmax = 30

for n in range(2, nmax):
    for factor in L:
        if n % factor == 0:
            break
    else: # no break
        L.append(n)
print(L)

Does the else in the outer loop work if the if statement is not execute din the inner loop...are they really connected inspite being in different loops
Answer: The else isn't connected to the if statement but to the break statement.
The for/else syntax means that the else block will be executed if there is no break encountered inside the for loop.
Here is an example for ppl to understand it :
fruits = ["Orange", "Apple", "Banana", "Strawberry"]

def searchFruit(wanted):
    for fruit in fruits:
        if fruit == wanted:
            break
    else: # Can't find the wanted fruit
        return False
    # Found the wanted fruit
    return True

searchFruit("Tomato") # Output : False

Comment: once break is encountered in the loop, shouldn't we jump to the outer loop and execute the else statement... but it doesnt happen, why?
Comment: No, if the break is encountered, the else statement will NOT be executed ^^ : You'll only jump in the outer loop and do nothing
Comment: but why.... the break statement takes us out of the inner loop ,and since else is in the outer loop, shouldn't it be executed
Comment: This else statement is related to your for loop, it will only be executed is the for loop ends normally.. That's how it works


Angular 4 "export 'AnimationEvent' was not found in '@angular/animations'

Question: Angular version 4.3.2
@angular/cli version 1.2.6
I'm using TypeScript (v2.4.2) for a component that imports
import {animate, AnimationEvent, state, style, transition, trigger} from '@angular/animations';

I'm getting warnings that say

"export 'AnimationEvent' was not found in '@angular/animations'

The other functions (animate, state, style, etc.) trigger no warnings.  I discovered that the @angular code in node_modules/@angular/animations.d.ts includes
export * from './public_api';

and ./public_api.d.ts has
export * from './src/animations';

and ./src/animations.d.ts has
export { AnimationBuilder, AnimationFactory } from './animation_builder';
export { AnimationEvent } from './animation_event';
export { AUTO_STYLE, AnimateChildOptions, AnimateTimings, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, animate, animateChild, animation, group, keyframes, query, sequence, stagger, state, style, transition, trigger, useAnimation, ɵStyleData } from './animation_metadata';
export { AnimationPlayer, NoopAnimationPlayer } from './players/animation_player';
export * from './private_export';

and ./animation_event.d.ts has the interface definition
export interface AnimationEvent {
    fromState: string;
    toState: string;
    totalTime: number;
    phaseName: string;
    element: any;
    triggerName: string;
}

If I copy the interface definition into my code everything works fine.
All of this is quite similar to many other imports I've used but this is the only one that generates warnings.
How can I prevent these warnings without copying the interface definition into my code?
Answer: app-module.ts: Did you import BrowserAnimationsModule?
See here in docs.
Along with a plunker example.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule ],
})

If that doesn't solve it:

Make a note of what system.config.js is doing in the Plunker.
Another related resource is a github issues thread.

Be sure to comment which steps if any fixed it. ;-)
Comment: I did import BrowserAnimationsModule and all my animations are working as expected.  In fact, except for the compiler warnings, everything is running and working as expected.
Comment: TL;DR Fixed by changing tsconfig.js compilerOptions.module from 'es2015' to 'CommonJS'.  Assuming this must be a compiler configuration, I analyzed the systemjs.config.js in the Plunker to compare with my (Angular CLI generated) tsconfig.app.json file.  There were only two differences, 1) noImplicitAny: true, and 2) module: 'commonjs'.  I changed both, one at a time.  The TypeScript doc states that the module type is CommonJS so I used that.  I hope this change won't cause other problems down the road...
Comment: https://www.typescriptlang.org/docs/handbook/compiler-options.html --noImplicitAny Raise error on expressions and declarations with an implied 'any' type. So that might not have been necessary. But glad you resolved it.
Comment: I should have said that I changed the noImplicitAny back to its default value because I had *lots* of implicit 'any' declarations :)


Shifting column header and column value down by n rows

Question: This is my data set and my starting row is Name onwards. How do I put the brand column down along with the name, address... row? I cannot drop the row above the starting row because I need it for extraction.
2        3      4      5      6       7     ...    Brand
A        B     nan    nan    nan     nan    ...     nike
Nan      B     nan    nan     C      nan    ...     nike
Nan      B     nan    nan     C      nan    ...     nike
AA       B     nan    nan     C      nan    ...     Adidas
Name  Address  Type   Size   Comment Grade  ...     Adidas
John    ggg    sports  8     Nil      A     ....    Adidas

This is the result I want:
2        3      4      5      6       7     ...
A        B     nan    nan    nan     nan    ...
Nan      B     nan    nan     C      nan    ...
Nan      B     nan    nan     C      nan    ...
AA       B     nan    nan     C      nan    ...
Name  Address  Type   Size   Comment Grade  ...     Brand
John    ggg    sports  8     Nil      A     ....    Nike
John    ggg    sports  9     Nil      B     ....    Nike
Mary    ggg    sports  6     Nil      A     ....    Adidas

Answer: You can use
df['Brand'] = df['Brand'].shift(df['2'].str.contains('Name').idxmax()+1)
df.at[df['2'].str.contains('Name').idxmax(), 'Brand'] = 'Brand'
print(df)

Output
    2   3     4        5      6     7   ...     Brand
0   A   B   NaN     NaN     NaN     NaN     ...     NaN
1   Nan     B   NaN     NaN     C   NaN     ...     NaN
2   Nan     B   NaN     NaN     C   NaN     ...     NaN
3   AA  B   NaN     NaN     C   NaN     ...     NaN
4   Name    Address     Type    Size    Comment     Grade   ...     Brand
5   John    ggg     sports  8   Nil     A   ....    nike


Is it possible to have enumerated data types in NetLogo?

Question: Is it possible to have enumerated data types in NetLogo?
Let's say that I have a model of marital status change.
An agent can have 3 marital status states: single, married, divorced.
I would like to map those states into numbers so that it takes less memory when executed.

single = 1
married = 2
divorced = 3

so that I can just do
ask agents with [ marital-status = single ][ get-married ]

I have found a trick to do that with "to-report"
eg:
to-report single
   report 1
end

But this means I have to create many to report functions if I were to have many categories in many variables. Is there a better workaround than this?
Thanks :)
Comment: This is an excellent question! I normally just use strings for this. They are more readable in code than numbers are. The assumption that strings use more memory than numbers isn't correct. If I have 1000 turtles and I say `ask turtles [ set marital-status "single" ]`, all 1000 turtles store a reference to the same string, I don't end up with 1000 copies of the string.
Comment: Hi @SethTisue, thank you for the clarification on my misunderstanding. I actually have a follow up question from this but not sure if I should put it on a new thread (let me know if I need to). Does `import-world` perform slower when some variables were stored as strings?
Comment: @SethTisue Good to know. I always use strings as well for readability, but I hadn't realised I had a good reason for not caring about the memory implications :)
Comment: @z5182 please open a new question on that
Answer: How big is your model? My understanding is that an agent attribute is minimum 8 bytes anyway (see https://github.com/NetLogo/NetLogo/wiki/Optimizing-NetLogo-Runs)
I can't think of a natural way to do this. However, if you really wanted to, this workaround would work: store the marital status as 0, 1, 2. Also store a global variable called marriage-status-map and use the item primitive. So it would look like this:
globals [ marriage-status-map]

turtles-own [ marriage-status ]

to testme
  clear-all
  set marriage-status-map ["single" "married" "divorced"]
  create-turtles 10
  [ set marriage-status random 3
    setxy random-xcor random-ycor
    set color blue
  ]
  ask turtles with [item marriage-status marriage-status-map = "single"] [set color red]
end

Comment: @z5182 You didn't mention it so I just wanted to check that you are aware of the profiler extension that makes runtime checks straightforward.
Comment: Thank you for your answer @JenB. This is certainly an option for me to consider. However, I should also test for the difference in runtime of the two methods (using to-report and yours). My model is quite large with 2GB+ in RAM usage (200k+ agents).
Comment: thanks for your suggestion of profiler I will check it out.


NoClassDefFoundError: QuerydslUtils

Question: Getting NoClassDefFoundError: org/springframework/data/querydsl/QuerydslUtils error.
I am using 1.13.6.RELEASE version of spring-data-commons.
The stack trace is as follows:
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/querydsl/QuerydslUtils
    at org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBRepositoryFactory.isQueryDslRepository(DynamoDBRepositoryFactory.java:142) ~[spring-data-dynamodb-5.0.2.jar:5.0.2]
    at org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBRepositoryFactory.getRepositoryBaseClass(DynamoDBRepositoryFactory.java:135) ~[spring-data-dynamodb-5.0.2.jar:5.0.2]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepositoryInformation(RepositoryFactorySupport.java:253) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:195) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    ... 29 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.data.querydsl.QuerydslUtils
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 37 common frames omitted

Comment: Are you using
com.github.derjust
spring-data-dynamodb
5.0.2
?
Comment: I am not sure whether you directly downloaded the jar and try using it. If you use Maven, it will automatically download the dependent jars like QuerydslUtils. I have checked the version spring-data-commons 2.0.1.RELEASE. It does have the class QuerydslUtils.
Comment: Yes I am using the 5.0.2 version of spring-data-dynamodb. I am using 1.5.6 Spring boot which is not compatible with 5.0.2 of spring-data-dynamodb
So its a compatibility issue,
Check the below link:
https://github.com/derjust/spring-data-dynamodb
Answer: As outlined by @himanshuraipur there is a clash of versions:
spring-data-dynamodb 5.0.2 is based on spring-data 2.0 / Spring 5.
But spring-boot 1.5.6 comes with spring-data 1.
Thus your only chance is to either update your spring-boot dependency or go back to spring-data-dynamodb 4.5 or 4.6.
On the project page there is a full compatibilty matrix
Note: I'm the maintainer of the spring-data-dynamodb project

NoClassDefFoundError: QuerydslUtils


higher order derivative in Sympy problem with dummy indecis

Question: How to get kth derivative of f(x) where k is also a dummy index in summation.
sym.diff(f,x,n) is interpreted as derivative of f with respect to both x and k not as kth derivative of f(x) which is what I want.
The problem I have is in this expression
sym.Sum((1/sym.factorial(k)*sym.diff(fun,x,k)*(x-a)**k),(k,0,10))

Any suggestions?
I want to some over kth derivatives as in taylor series, however, I don't know how to make sympy interpret k as number - order of the derivative (coming from the summation) and not a variable when it comes to the differentiation.
The problem:
how sum evaluates to zero
Mistake isn't inside the sum
Answer: I'm not sure I understand what you want but I guess you need to pass a tuple (x, k) like diff(f, (x, k)) rather than diff(f, x, k). Like this:
In [1]: import sympy as sym

In [2]: x, k, a = sym.symbols('x, k, a')

In [3]: fun = Function('f')(x)

In [4]: sym.Sum((1/sym.factorial(k)*sym.diff(fun,(x,k))*(x-a)**k),(k,0,10))
Out[4]:
  10
______
╲
 ╲
  ╲                k
   ╲           k  d
    ╲  (-a + x) ⋅───(f(x))
    ╱              k
   ╱             dx
  ╱    ───────────────────
 ╱              k!
╱
‾‾‾‾‾‾
k = 0

In [5]: _.doit()
Out[5]:
            10                      9                     8                     7                     6                     5
        10 d                    9  d                  8  d                  7  d                  6  d                  5  d
(-a + x)  ⋅────(f(x))   (-a + x) ⋅───(f(x))   (-a + x) ⋅───(f(x))   (-a + x) ⋅───(f(x))   (-a + x) ⋅───(f(x))   (-a + x) ⋅───(f(x))   (-a + x
             10                     9                     8                     7                     6                     5
           dx                     dx                    dx                    dx                    dx                    dx
───────────────────── + ─────────────────── + ─────────────────── + ─────────────────── + ─────────────────── + ─────────────────── + ───────
       3628800                 362880                40320                  5040                  720                   120

     4                     3                     2
 4  d                  3  d                  2  d
) ⋅───(f(x))   (-a + x) ⋅───(f(x))   (-a + x) ⋅───(f(x))
     4                     3                     2
   dx                    dx                    dx                   d
──────────── + ─────────────────── + ─────────────────── + (-a + x)⋅──(f(x)) + f(x)
  24                    6                     2                     dx

Comment: This case should probably be documented with an example in `diff`.
Comment: Thank you!! that solves it, sorry I didn't think of it.


How to target multiple datepicker in a form?

Question: I have a dynamic form with 4 datepicker inputs. How can I target these datepicker inputs to avoid past date after a first date is set?
Here is my code
$(function() {
    $( ".from" ).datepicker({
      onClose: function( selectedDate ) {
        $( ".to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( ".to" ).datepicker({
      onClose: function( selectedDate ) {
        $( ".from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });
  });

As you can see both inputs are affected when the user select one date. I want to target one each but as I mentioned my form is dynamic, the user can add 4.. 6.. 8 datepicker inputs.
Comment: Group your from and to dates which would make it easier to target.
Answer: From what I understand of your problem, your code is close, but you need to change how you are adding your options. They should use angle ({) brackets.
Try the following:
$(function () {
    $(".from").datepicker({
        onClose: function (selectedDate) {
            $("." + this.parentElement.className + " .to").datepicker("option", {
                "minDate": selectedDate
            });
        }
    });
    $(".to").datepicker({
        onClose: function (selectedDate) {
            $("." + this.parentElement.className + " .from").datepicker("option", {
                "maxDate": selectedDate
            });
        }
    });
});

JSFiddle
Edit
Another method is to put divs around (or use a special classname within the individual elements), and use that, along with the datepicker type, and change it that way. See the new code above to get an idea of what I mean.
Comment: Thank you! Yours is also working fine! I've just realised there are many ways to do it.
Comment: Still not working :(
Try selecting Work from and Work to dates then select Study dates. You will see that the code is not interpreting each input as unique.
Comment: Oh are you asking if you can have sets together? (for example, the study dates don't affect the work dates, but affect eachother?)
Comment: Exactly. This what I am trying to achieve here. I want to have an unique datepicker group for Study and another group for Work.
Comment: Also do you know if I can change the view format to show months and years only? I wanted to do something like this:  [link](http://i.stack.imgur.com/Ubqih.jpg)
Answer: If I've understood this correctly, you want N number of pairs of datepickers ("from" and "to"), which you need to tie together. Essentially, you need a way to go from a specific datepicker and identify only the one other datepicker that's tied to it. There are a number of ways you could do this, but I'd suggest wrapping your pairs in a containing HTML element (
) then doing the selectors relative to that. Something like this:

    Work from
    <input type="text" class="form-control date-picker from input-append minDate" placeholder="mm/yyyy"/>

    Work until
    <input type="text" class="form-control date-picker to input-append maxDate" placeholder="mm/yyyy"/>

    Study from
    <input type="text" class="form-control date-picker from input-append minDate" placeholder="mm/yyyy"/>

    Study until
    <input type="text" class="form-control date-picker to input-append maxDate" placeholder="mm/yyyy" />

Then you'd modify your jQuery code for the datepickers to look like this:
$(function() {
    $( ".from" ).datepicker({
        onClose: function( selectedDate ) {
            $(this).closest('div').find('.to').datepicker( "option", "minDate", selectedDate );
        }
    });
    $( ".to" ).datepicker({
        onClose: function( selectedDate ) {
            $(this).closest('div').find('.from').datepicker( "option", "maxDate", selectedDate );
        }
    });
});

The key change is this:
$(this).closest('div').find('.from')

In the function, this is the element of the datepicker that's just closed. .closest('div') traverses up the DOM tree until it finds the containing
 element, then .find('.from') will find the one element with the class from inside it, which is the one element that's linked to that specific to element.
Comment: Mate you saved our project! =D Thank you so much for your help. Working like a charm! And thank you all for the help!
Answer: $(datepicker1,datepicker2,datepicker3,...).datepicker({
    minDate:selectedDate1,
    maxDate:selectedDate2
})

Answer: You can use .nextUntil() and .prevUntil() and some additional methods to select only the next or previous input.
$(function() {
  $( ".from" ).datepicker({
    onClose: function( selectedDate ) {
      $(this).nextUntil('.to').andSelf().last().next().datepicker( "option", "minDate", selectedDate );
    }
  });
  $( ".to" ).datepicker({
    onClose: function( selectedDate ) {
      $(this).prevUntil('.from').prev().datepicker( "option", "maxDate", selectedDate );
    }
  });
});

JSFiddle
Answer inspired by the answer to a related question.


Getting an array of users that edited a page

Question: I am working on a user script for a Wikia community ( http://c.wikia.com ) and I need to get array of users (and possibly revision IDs) of a page. I have come up with the following code but cannot seem to make it work. Any help would be appreciated.
Code:
var revisions = [];
$.getJSON('/api.php', {
    action: 'query',
    prop: 'revisions',
    titles: mw.config.get("wgPageName"),
    rvprop: 'user',
    rvlimit: '50',
    format: 'json'
}, function (result) {
    for (var i = 0; i < 50; i++) {
        var revision = result.query.pages.page[i].revisions.user;
        revisions.push(revision);
    }
    alert(revisions);
});

Comment: What's wrong with it?
Comment: What errors (if any) are you getting?
Comment: The issue is that it isn't returning anything, just blank.
Comment: sounds like a problem with api.php or the parameters you are sending it (or not sending it)
Comment: Nt your case, but those with access to the wiki configuration can jst use (and enable if disabled) action=credits. https://www.mediawiki.org/wiki/Manual:Parameters_to_index.php#credits
Answer: The query result looks something like this:
{
  "query": {
    "pages": {
      "421588": {
        "pageid": 421588,
        "ns": 0,
        "title": "Community Central",
        "revisions": [
          {
            "user": "Mhadick"
          },
          {
            "user": "Nblonkenfeld"
          },
          …
        ]
      }
    }
  },
  …
}

You'll notice that pages is an object with property named after the page id of the current page "421588" (judging from your code, you might be looking at the XML version of the response, you have to look at the JSON). To work with that, you can use something like:
var users = [];

$.getJSON('/api.php', {
    action: 'query',
    prop: 'revisions',
    titles: mw.config.get("wgPageName"),
    rvprop: 'user',
    rvlimit: '50',
    format: 'json'
}, function (result) {
    var revisions = result.query.pages[mw.config.get("wgArticleId")].revisions;

    $.each(revisions, function(key, revision) {
        users.push(revision.user);
    });

    alert(users);
});


Utilising my GTX1050 for tensorflow/keras not allowed as due to WDDM mode

Question: I recently bought a computer with an NVIDIA GeForce GTX1050. I have been trying to use it with tensorflow and keras through a local jupyter notebook. I have got tensorflow-gpu and keras-gpu in my environment. I have all the correct versions of cuda and cudnn installed with all the necessary paths in my environment variables as per https://www.tensorflow.org/install/gpu. When I run the nvidia-smi command I get this:
output of nvidia-smi. When I look at output of nvidia-smi -q it says 'Not available in WDDM driver model'.
After doing some research, it seems all GeForce products support only WDDM, so how do people use their GeForce products with deep learning? I have seen countless youtube videos and forum posts with people claiming the use their GeForce GPU with tensorflow and keras. What am I missing?
Comment: Native environment often causes issues while using GPU. Try installing Anaconda and install all the dependencies in the condo environment and then try to run your code there. As conda installs all the additional dependencies of any package alongside automatically, I hope it fixes your problem.
Comment: @RishabP. this is what I have done from the start, no joy.
Answer: Are you concerned that the models are not running in your GPU. This SO question seems similar to what you have https://stackoverflow.com/a/44228331/8416255
Comment: That link says to switch to TCC mode which apparently you can't do with GeForce series GPU, that is my question.
Comment: @CharlieBaskerville I think the link says, tensorflow GPU still works, its just that you cannot monitor it on windows
Comment: I'm not sure it does. There is no speed up in computation time when trying to use the GPU which would suggest that it is not being used.
Comment: What's the result of this? https://stackoverflow.com/a/38019608/8416255


Session-scoped bean has dependency set to null when written in Kotlin

Question: Using spring boot 2.3.4, kotlin 1.3.72.
I've got a session-scoped bean that Spring is instantiating with a null dependency, which obviously results in a NPE when it is executed. I created a sample project to reproduce the behavior. The equivalent code works in Java. UPDATE: The below works if I only convert the MessageWriterService to Java.
Here's my configuration class:
@SpringBootApplication
class SessionScopeKotlinApplication {

    @Bean
    fun messageWriter() = MessageWriter()

    @Bean
    @SessionScope
    fun messageWriterSvc(writer: MessageWriter) = MessageWriterService(writer)

}

The MessageWriter and the MessageWriterService
class MessageWriter {
    fun write() = println("message written!")
}

open class MessageWriterService(private val writer: MessageWriter) {

    private var written = false

    fun writeIfNotWritten() {
        if (!written) {
            writer.write()
            written = true
        } else {
            println("** message already written, not writing again **")
        }
    }
}

And then I have a controller that calls the MessageWriterService:
@RestController
class MessageWriterController(private val writerService: MessageWriterService) {
    @GetMapping("/write")
    fun write() {
        writerService.writeIfNotWritten()
    }
}

As soon as I call the controller method, I get the stacktrace below (abbreviated). The point of failure is the call to the writer, which is actually null.
2020-10-13 07:37:41.919 ERROR 9184 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.example.sessionscopekotlin.MessageWriterService.writeIfNotWritten(SessionScopeKotlinApplication.kt:32) ~[main/:na]
    at com.example.sessionscopekotlin.MessageWriterController.write(SessionScopeKotlinApplication.kt:44) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]

Comment: It would help if you highlighted the line where the NPE occurs.
Answer: To me it seems that Spring can't autowire the Writer for you here:
@SpringBootApplication
class SessionScopeKotlinApplication {

    @Bean
    fun messageWriter() = MessageWriter()

    @Bean
    @SessionScope
    fun messageWriterSvc(writer: MessageWriter) = MessageWriterService(writer)

}

The solution for this is to call the bean function like this:
@SpringBootApplication
class SessionScopeKotlinApplication {

    @Bean
    fun messageWriter() = MessageWriter()

    @Bean
    @SessionScope
    fun messageWriterSvc() = MessageWriterService(messageWriter())

}

You should also use the prototype scope if you don't want the same Writer to be returned for each call.
Comment: Sure enough, that fixed it. I did the same style of autowiring in Java, and it worked. Weird that it doesn't in Kotlin. Anyway, thanks!
Comment: You can also use the `@Autowired` annotation I think.
Answer: Interesting finding. If you don't want to create new MessageWriter for every session the following approach could help:
@SpringBootApplication
class SessionScopeKotlinApplication {

    @Bean
    fun messageWriter() = MessageWriter()

}

@Service
@SessionScope
class MessageWriterService(private val writer: MessageWriter) {

    private var written = false

    fun writeIfNotWritten() {
        if (!written) {
            writer.write()
            written = true
        } else {
            println("** message already written, not writing again **")
        }
    }
}

So you basically switch from @Bean annotation to direct @Service declaration. But I can imagine some cases where you would like to use the @Bean annotation explicit.


Orange flame on a Rinnai furnace after propane conversion

Question: I have just installed a Rinnai hot air direct vent furnace. After converting the appliance to propane, I adjusted the gas pressures  with a manometer according to the manufacturers instructions. The flame is mostly blue with orange at the ends of the flames. I also have a plume of what looks like moisture coming out of the exhaust manifold.
Could I have adjusted the LPG pressure too high? The instructions call for 1.06 in/H2O at low manifold pressure and 3.8 in/H2O at high pressure. Can anyone suggest a solution? Thanks in advance, Jeffrey.
Comment: Hello, and welcome to Home Improvement. This may be better answered by the Rinnai support department. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: If I'm not mistaken, this requires proper pressure and airflow for exhaust and sometimes there is programming needed on the control boards or differnt nozzles and or flow regulators used. It's not burning clean it seems. Have to agree with @DanielGriscom since its brand new.
Comment: [What could be causing an orange flame on all appliances?](https://diy.stackexchange.com/questions/38026/what-could-be-causing-an-orange-flame-on-all-appliances)
Answer: This sounds normal. It sounds like you have the proper air fuel mix and the moisture is normal, I have had almost every home owner call be on a cold morning saying there furnace is smoking, it is actually the moisture and it shows up as a fog on cold mornings , sounds like things are just fine.
Comment: Does LPG burn more orange than LNG?
Comment: With proper air fuel mix they are very close but not the same btu's.
Comment: "The flame is mostly blue with orange at the ends of the flames." - that's normal, +1


Do you call a clockwise logic line still clockwise if it's rotated counter clockwise?

Question: Just like my last question, i have another terminology related question.
In my drawing app, the user can set a logic line which can detect other objects touching or passing the line and removing those objects if they do.
There are 3 settings to this line:

Touch (respond when objects touches line)
Clockwise (respond when objects pass the line clockwise)
Counter-clockwise (respond when objects pass the line counte-clockwise

The user can use the anchors of the line to move the line around as such:

Now, during testing... i stumbled upon a bit of a thinking error. If the user moves the other anchor around, the line effectively becomes a "COUNTER-clockwise line", but with the "Clockwise" settings.
Like so:

Is calling the options clockwise/counter-clockwise still a good idea if this kind of behavior is possible.
I thought of a few solutions to solve this like automatically change the setting from clockwise to counter-clockwise (which is basically already at a 0.00001 degree turn of the lower anchor) or making only the top anchor movable (which made working with the logic lines a lot more frustrating). But i think the main problem is just the labeling of the settings.
Comment: Your current UI is definitely confusing. It isn't clear that the drop-down even relates to the line, let alone what the cryptic word in it is talking about. Can you not demonstrate the property of the line object with some visual state of the line itself?
Comment: How can you pass a line in a clockwise direction? Or counter-clockwise, for that matter?
Comment: I'm going to guess that you mean passing from one side to the other? In that case surely you only need 2 options (touch and pass) with the direction of the arrow on the line determining which passing events you respond to.
Comment: The UI shown is just for this questions sake...the combobox is 1 part of the settings frame for this specific line.

The cryptic word defines if the arrow on the line will be shown on the right or left side of the line. However, if the user rotates the line, the value basically gets reversed.
Comment: Can the user set the values of the "origin" and "termination" points in your settings frame, or a value for the rotation of the line (based off one of those points)?
Comment: To add to @RedSirius, the user could click the arrow to reverse the direction of it when the 'pass' option is selected
Answer: Clockwise and counter-clockwise are definitely the wrong terminology here.
I think you will want to say:

Pass from above
Pass from the left
Pass from the right
Pass from below

The wording should change based on the angle of the line and the direction of the arrow. A line that is more horizontal will only have the options to select "above" and "below", whereas a line that is more vertical will only have the options to select "left" and "right".
Comment: So you are saying that the contents of the combobox should adapt in correlation of the angle of the line?

So if the user draws a line, then sets the line to "Pass from the left"... THEN rotates the line 180 degrees (which makes the arrow point from right to left now), the combobox should change to "Pass from the right".
Answer: From a UI point of view the automatic detection makes sense and, if possible, icons may be better, for example circle for touch and broken circles with arrows for clockwise, counter clockwise. I know I have to think about what counter clockwise means, and it's likely the user will have to work that out as well which breaks the flow of your interface.
From a UX point of view (UI not being UX as we all should know by now), I can't help wonder what the context is behind wanting this functionality. It's hard to recommend a better solution without some kind of scenario of use.
Comment: Here's a little context....

You've drawn a marble track and let the marbles go down some path. Now the user wants that something happens at a specific part of the track. So the user draws a "logic line" on that part.
Comment: Here's a little context:

You've drawn a marble track and let the marbles go down some path. Now the user wants that something happens at a specific part of the track. So the user draws a "logic line" on that part.

Now, the user only wants to affect the marbles crossing the line from the left to the right. So the user sets the logic line to CLOCKWISE.... i.e., only the marbles that pass the line in a clockwise matter will be affect by the logic line.

If the user wants to only affect the marbles going from right to left, the user sets COUNTER-CLOCKWISE.

Some users just rotated the line.
Comment: continuation:

This had the same effect, but the option was still set to CLOCKWISE.


How to pass URL parameters when redirecting to another URL?

Question: I'm using this html code to redirect to another URL when the page (www.dasinfobuch.de/links/Wizz) is invoked:

  <meta http-equiv="refresh" content="0; URL=http://184.108.40.206:8080/Wizard/Wizz">

However, when I use a URL parameter such as
www.dasinfobuch.de/links/Wizz?template=test

the parameter is not passed on to the redirected page. Is there a way to accomplish this (preferably in plain HTML)? (I'm new to Web programming.)
Comment: Not possible in plain HTML, but this would be much better done on server side using a 30x redirect (using a server side programming language or a Apache `Redirect` in a .htaccess file as shown [here](http://stackoverflow.com/questions/22567357/htaccess-redirect-url-with-parameters))
Comment: @Pekka웃 Ok, I'll look into that, thanks! But this would have to be done on the Server hosting www.dasinfobuch.de, right? I don't think I have this kind of access on that server (the servlet is running on a different sever).
Comment: Yes, that would have to be done on that server. If all you can access is the page source code your only option is to use JavaScript, which is less reliable (JS can be deactivated or may not be parsed at all, e.g. by bots like search engine crawlers).
Comment: You could also parse the `HTTP_REFERER` header on the receiving server (the 52.28.... one). That wouldn't be 100% reliable either, as clients can turn this offf, but relatively pain free
Comment: The referer has nothing to do with JavaScript, but is [another HTTP header field](https://en.wikipedia.org/wiki/HTTP_referer). It's the address of the resource that linked to the destination. Take a look inside `request.getHeader("referer")`.
Comment: How are you trying to read that variable?
Comment: I'm using a servlet and read via request.getParameter("template");
Comment: Yeah, I wanted to avoid JavaScript. But ok, most people don't turn it off... How do I "parse the HTTP_REFERER header"?
Answer: This is not possible using only a meta element that mimics the non-standard Refresh HTTP header field. Of course there are other ways.
If you've got something like a preprocessor, you can pass on the request to the HTML, like so:
<meta http-equiv="refresh"
      content="0; URL=http://184.108.40.206:8080/Wizard/Wizz?template=<%
           out.print(request.getParameter("template")) %>">

Another (client-side) way is to redirect using JavaScript:
document.location.href = 'http://184.108.40.206:8080/Wizard/Wizz' + document.location.search;

Note that this will carry over the entire query string, not just the template parameter and its argument. If that's a problem, it's easy to get only the desired string from location.search.
Comment: @lukas.coenig: Don't worry and take your time. It's definitely a solvable problem with multiple approaches. If it still doesn't work, providing an actual (servlet) code sample might be helpful to all.
Comment: Thanks, I'll look into that... As I said, I'm new to web programming, so it might take a while :-) (Ok, the first idea should be easy to test...)
Comment: The first thing didn't work. Obviously I don't have a preprocessor available... The result is just:
http://184.108.40.206:8080/Wizard/Wizz?template=%3C%%20%20%20%20%20%20%20%20%20%20%20out.print(request.getParameter(
Comment: If it's a servlet, that probably means you use JavaServer Pages, which means that your HTML code might be processed, which allows you to include data from the request (like a query string) in the otherwise static HTML contents, using delimiters like `<%…%>`. As stated above, more information on your part is necessary, like how the page at `www.dasinfobuch.de/links/Wizz` is being generated and delivered…
Comment: I'm using a servlet, but without JSP - so far, on the target server site (which is running a Tomcat8). The page www.dasinfobuch.de/links/Wizz is static, I can put there whatever I want, and I need it only once (or a "finite" number of times :-)), but the server is just a standard web hosting server (by 1und1, Germany) which is not very flexible. So far, I've done all the programming on the Tomcat, nothing on the client side or the other server.


Twitter Bootstrap error when running 'bootstrap:themed', with Mongo

Question: This occurs when I try to run rails g bootstrap:themed Associations in my terminal:
C:/Users/ruby/.pik/rubies/Ruby-193-p327/lib/ruby/gems/1.9.1/gems/twitter-bootstrap-rails-2.1.9/lib/generators/bootstrap/themed/themed_generator.rb:87:in `block in retrieve_columns': undefined method `columns' for Association:Class (NoMethodError)

It just can't seem to work, I've tried many ways, searched everywhere, never succesful. I'm using Mongo.
Answer: I just got exact same error. I created two identical project - one with mongoid and one without. I only get the error on the mongoid project.
Found this workaround that seems to solve the problem:
Remove references to ActiveRecord (around line 87) in the file:
/home/ubuntu/.rvm/gems/ruby-1.9.3-p327/bundler/gems/twitter-bootstrap-rails-b8b7eb22614a/lib/generators/bootstrap/themed/themed_generator.rb

I changed ...
  def retrieve_columns
    if defined?(ActiveRecord)
      rescue_block ActiveRecord::StatementInvalid do
        @model_name.constantize.columns
      end
    else
      rescue_block do
        @model_name.constantize.fields.map {|c| c[1] }
      end
    end
  end

to this ...
  def retrieve_columns
      rescue_block do
        @model_name.constantize.fields.map {|c| c[1] }
      end
  end

To get the views working I needed to make sure that my model class had a created_at field that wasn't nil (alternatively edit the generated views).
Hope this helps.
PS: Wow  ... it seems you've got twitter-bootstrap-rails working on windows - I didn't know that was possible!
Comment: Cool - good to hear. I'll send the link to twitter-boostrap-rails maintainers so they can find a permanent solution independent of ActiveRecord.
Comment: Yeah heheh now I'm using Ubuntu too... I actually got it to work by downgrading twitter-bootstrap-rails to '2.0.2', but maybe it isn't a permanent fix so I'll try your fix! Thank you very much!


Surface inside cylinder $y_1^2+y_2^2=r^2$ using parametrisation

Question: The question is

Let $r>0$. Let S⊂ $R^3$ the surface given by $y_1y_2-ry_3=0$. Determine the area of the portion of S inside the cylinder given by $y_1^2+y_2^2=r^2$.

In class we saw a formula to calculate the area of parametric surfaces (the one with the cross product). The problem is, I don't have a parametrisation of S. And to be very honest, I have no idea how it's done. I thought maybe cylindrical coordinates would help? I also tried isolating r to see if it could help in any way. How do I approach a question like this? We didn't see any examples in class and I am very confused.
Answer: You need to find surface area of the hyperbolic paraboloid $z = \frac{xy}{r}$, inside the cylinder $x^2+y^2 = r^2$.
The formula for the surface area is given by,
$S = \displaystyle \iint_A \sqrt{1+ \bigg(\frac{\partial z}{\partial x}\bigg)^2 + \bigg(\frac{\partial z}{\partial y}\bigg)^2} \ dA$
$ = \displaystyle \iint_A \sqrt{1+ \frac{x^2}{r^2} + \frac{y^2}{r^2}} \ dA$
where $A$ is the projection of the surface in $XY$ plane and $dA = dx \ dy$.
Converting to polar coordinates,
$x = \rho \cos \theta, y = \rho \sin \theta, 0 \leq \rho \leq r, 0 \leq \theta \leq 2\pi$.
$S = \displaystyle \frac{1}{r}\int_0^{2\pi} \int_0^r \rho \sqrt{\rho^2 + r^2} \ d\rho \ d\theta = \displaystyle \frac{2 \pi}{r} \int_0^r \rho \sqrt{\rho^2 + r^2} \ d\rho $
To evaluate the integral, you can substitute $\rho^2 + r^2 = t, \rho d\rho = \frac{1}{2} dt$.
Can you take it from here?
Comment: See if this helps https://en.wikipedia.org/wiki/Surface_integral
Comment: thanks a lot! how do you get the formula for the surface area tho? i didn't quite get that
Comment: you can also parametrize as $C(\rho, \theta)$ and then find $|C'_{\rho} \times C'_{\theta}|$ and integrate.


How to define cut set with Edmonds Karp Impl?

Question: I'm using JGraphT, and I'm using EdmondsKarpMFImpl.
The question is: How to define the whole set of edges what is 'participate' in min-cut.
I tried to use the  getCutEdges method, but it only returns 1 edge.
I have the following graph:
(all the edges has a weight value(1) and a residual capacity value(10))
public SimpleDirectedWeightedGraph generateAbilene(){

        Supplier<Integer> vSupplier3 = new Supplier<Integer>() {

            private int id = 1;

            @Override
            public Integer get() {
                return id++;
            }
        };

        SimpleDirectedWeightedGraph exGraph3 =
                new SimpleDirectedWeightedGraph<Integer, MyDefaultWeightedEdge>(vSupplier3, MyUtil.createDefaultWeightedEdgeSupplier());

        exGraph3.addVertex(1);
        exGraph3.addVertex(2);
        exGraph3.addVertex(3);
        exGraph3.addVertex(4);
        exGraph3.addVertex(5);
        exGraph3.addVertex(6);
        exGraph3.addVertex(7);
        exGraph3.addVertex(8);
        exGraph3.addVertex(9);
        exGraph3.addVertex(10);
        exGraph3.addVertex(11);

        exGraph3.addEdge(1,2);
        exGraph3.addEdge(1,7);
        exGraph3.addEdge(2,3);
        exGraph3.addEdge(3,4);
        exGraph3.addEdge(4,5);
        exGraph3.addEdge(6,7);
        exGraph3.addEdge(10,7);
        exGraph3.addEdge(7,8);
        exGraph3.addEdge(8,5);
        exGraph3.addEdge(8,9);
        exGraph3.addEdge(8,11);
    return exGraph3;
}

And with that method I only get the first 2 edge(1-2 & 1-7) between the Source node (1) and the Sink node (5)
I want to retrieve all the edges in the min cut.
For example in the case above it should return:
1-2,
1-7,
2-3,
7-8,
3-4,
8-5,
4-5
(about the order of the edges I do not care)
The Graph looks like this:
Comment: Could you provide a [MWE](https://stackoverflow.com/help/minimal-reproducible-example)? Your code only shows the graph, but not how you compute the minimum cut.
Answer: I think you are misinterpreting the definition of a minimum cut. A (weighted) min cut is a partitioning of the vertices in two disjoint subsets (say S and T) such that the sum of the weights of edges crossing the partition is minimum. In your case, you are specifically asking for a minimum s-t cut, which is a specific case of a minimum cut: in the minimum s-t cut, you require that the source vertex (s) is a member of S, and the sink vertex t is a member of T. Observe that the more general problem of finding a minimum cut in the graph could yield a solution where both vertices s and t are in the same partition.
Looking at your graph, a minimum s-t cut with s=1 and t=5, would be: S={1,2,6,7,10} and T={3,4,5,8,9,11}. The total weight of the edges ((2,3),(7,8)) crossing these partitions is 2, so this cut has value 2. Similarly, you can identify other s-t cuts in this graph with the same value.
Now the maximum flow min cut theorem tells us the relation between a cut and a flow. If we were to compute a max s-t flow in your graph, with s=1 and t=5, the max flow min cut theorem tells us that we cannot send more than 2 units of flow from s to t. An example of a max flow in this graph: we send 1 unit of flow on the path 1-7-8-5 and 1 unit on the path 1-2-3-4-5 resulting in a total flow of 2.
So what you seem to be looking for, is not a solution to the min cut problem, but a solution to the max flow problem. In particular, you want to compute which edges in the max flow problem have a positive flow value. Naturally, you can use JGraphT to get these results. Here's a cleaned-up version of your example:
public static void maxFlowMinCutExample(){
    Graph<Integer, DefaultWeightedEdge> graph =
            new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
    Graphs.addAllVertices(graph, Arrays.asList(1,2,3,4,5,6,7,8,9,10,11));

    //NOTE: by default, edges in jgrapht have a weight of 1.0. You would invoke graph.setEdgeWeight(.)
    //to change the edges' weight.
    graph.addEdge(1,2);
    graph.addEdge(1,7);
    graph.addEdge(2,3);
    graph.addEdge(3,4);
    graph.addEdge(4,5);
    graph.addEdge(6,7);
    graph.addEdge(10,7);
    graph.addEdge(7,8);
    graph.addEdge(8,5);
    graph.addEdge(8,9);
    graph.addEdge(8,11);

    //Calculate a Minimum Cut:
    minCut(graph, 1, 5);
    //Calculate a max flow:
    maxFlow(graph, 1, 5);
}

public static void minCut(Graph<Integer, DefaultWeightedEdge> graph, Integer source, Integer sink){
    MinimumSTCutAlgorithm<Integer, DefaultWeightedEdge> mc = new EdmondsKarpMFImpl<>(graph);
    System.out.println("Minimum s-t cut weight: "+mc.calculateMinCut(source, sink));
    System.out.println("Source partition S: "+mc.getSourcePartition());
    System.out.println("Sink partition T: "+mc.getSinkPartition());
    System.out.println("Cut edges (edges with their tail in S and their head in T): "+mc.getCutEdges());
}

public static void maxFlow(Graph<Integer, DefaultWeightedEdge> graph, Integer source, Integer sink){
    MaximumFlowAlgorithm<Integer, DefaultWeightedEdge> mf = new EdmondsKarpMFImpl<>(graph);
    MaximumFlowAlgorithm.MaximumFlow<DefaultWeightedEdge> flow = mf.getMaximumFlow(source, sink);
    System.out.println("Max flow value: "+flow.getValue());
    System.out.println("Edges with positive flow:");
    for(DefaultWeightedEdge edge : graph.edgeSet())
        if(flow.getFlow(edge) > 0)
            System.out.println("Edge: "+edge+" value: "+flow.getFlow(edge));
}

The output of the above code:
Minimum s-t cut weight: 2.0
Source partition S: [1]
Sink partition T: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Cut edges (edges with their tail in S and their head in T): [(1 : 2), (1 : 7)]
Max flow value: 2.0
Edges with positive flow:
Edge: (1 : 2) value: 1.0
Edge: (1 : 7) value: 1.0
Edge: (2 : 3) value: 1.0
Edge: (3 : 4) value: 1.0
Edge: (4 : 5) value: 1.0
Edge: (7 : 8) value: 1.0
Edge: (8 : 5) value: 1.0


Find all positive integers $n$ s.t. $3n-2\mid n^{3n-2}-3n+1$

Question: Find all positive integers $m$ such that $3n-2\mid n^{3n-2}-3n+1$.
The statement is equivalent to $$3n-2\mid n^{3n-2}-3n+1+3n-2=n^{3n-2}-1$$
Which means $$n^{3n-2}\equiv 1\pmod{ 3n-2}$$
I don't know how to complete it from here.
Comment: And if, after studying that link, you can solve the problem, please write it up and post an answer.
Comment: Using [Approach0](https://approach0.xyz/search/?q=OR%20content%3A%243m-2%5Cmid%20m%5E%7B3m-2%7D-3m%2B1%24&p=1), I found the AoPS thread [Problem 3 of Fourth round](https://artofproblemsolving.com/community/c6h1711443p11036795). I believe you'll find the approach used by [UK2019Project](https://artofproblemsolving.com/community/user/394622) in message #$3$ to be most useful (note that there's a problem with the proof given in message #$2$).
Answer: First note that $d=\gcd(3n-2,n)=\gcd(n,2)=1$ or $2$
If $d=2$, then $n$ should be even, thus $3n-2$ is even as well but $n^{3n-2}-1$ is odd. Hence we cannot have $3n-2\mid n^{3n-2}-1$. So $d=1$ and $n$ is odd.
Let $p$ be the smallest prime divisor of $3n-2$, by Fermat we have $$n^{p-1}\equiv 1\pmod p$$ Hence $$n^{(3n-2,p-1)}\equiv 1 \pmod p$$
Assume that $s=\gcd(3n-2,p-1)>1$ so by definition $s\mid 3n-2 $ and $s\mid p-1$, the latter implies $s\le p-1$ and because of the minmality of $p$ we have (from the former) $p< s$. Combining them we'll get $$s+p+1\le p-1+s \implies 1\le -1$$ A contradiction so actually $s=1$, hence $p\mid n-1$ but that would imply $p\mid 1$. so $n=1$.
Comment: Why $n^{(3n-2,p-1)}\equiv1\pmod p$?
Comment: $p\mid 3n-2\mid n^{3n-2}-1$ This was derived in the OP
Comment: $n^{3n-2}\equiv 1 \pmod p$ and $n^{p-1}\equiv 1\pmod p$ Now use bezout.
Comment: But why $n^{3n-2}\equiv1\pmod p$?


Terraform create multiple resources using for_each and jsondecode

Question: I want to create multiple resource(GCP's multiple cloudSQL instances) and this is what I have:
locals {
  psql_settings = [
    { "name" : "psql1", "location" : "us-central1", "zone" : "us-central1-c" },
    { "name" : "psql2", "location" : "us-east1", "zone" : "us-east1-b" }
  ]
}

I have to use them in json format because this will be stored in consul for dynamic changes.
Using this locals value, how I can create multiple resources. I am trying:
module "postgresql-db" {
  depends_on = [
    module.vpc
  ]
  source               = "../modules/postgres"
  for_each             = local.psql_settings[0]
  name                 = each.value.name
  random_instance_name = true
  database_version     = "POSTGRES_13"
  project_id           = "xyz-project
  zone                 = each.value.zone
  region               = each.value.location
...
...

Answer: It should be:
  for_each   = {for idx,val in local.psql_settings: idx => val}

The code changes your list of maps, into map of maps, which is required by for_each.


Django NoReverseMatch at /sitemap.xml error for static views

Question: I followed the instruction on django documentation, but I am getting this error when trying to create the sitemap.xml for my app. (also the similar questions on stackoverflow were not describing my case)

The html pages that I would like to add to the sitemap are not based on any models, but they have some forms in their footers. (That's why the urls don't contain "as_view()".
I have also added
INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'django.contrib.sitemaps',
    '''
]

to settings.py file.
Here are more details:
App --> main
main/urls.py
from django.urls import path
from . import views

app_name = 'main'

urlpatterns = [
    path('', views.HomeView, name='homepage'),
    path('about/', views.AboutView, name='about'),
    path('contact/', views.Contact, name='contact'),
]

main/sitemap.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse

class StaticViewSitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.9

    def items(self):
        return ['homepage','about','contact']

    def location(self, item):
        return reverse(item)

Project --> dcohort
dcohort/urls.py
from argparse import Namespace
from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap
from main.sitemaps import StaticViewSitemap
from django.conf import settings
from django.conf.urls.static import static

sitemaps = {
    'staticviews': StaticViewSitemap,
}

urlpatterns = [
    path('', include('main.urls', namespace='main')),
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
]

Comment: [include](https://docs.djangoproject.com/en/2.1/topics/http/urls/#including-other-urlconfs) dcohort urlpatterns into main urlpatterns
Comment: @IvanStarostin "dcohort" is my project. "main" is an app. I think I should import the app urlpatterns into project. Am I right?
Answer: I finally figured the problem. I should have appended the app name to the page url name.
The main/sitemap.py would be:
from django.contrib.sitemaps import Sitemap

from django.urls import reverse

class StaticViewSitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.9

    def items(self):
        return ['main:homepage','main:about','main:contact']

    def location(self, item):
        return reverse(item)


Pentax PocketJet 3 Plus - Add printer

Question: I have a Pentax PocketJet 3 Plus that I want to use with my linux machine but I can't find a linux driver, only windows one. Is there anything that I can do to make it work or should I just forget this idea?
This is what I get from dmesg:
<code>[ 5562.920208] usb 2-3.4: new full-speed USB device number 17 using ehci-pci
[ 5563.014188] usb 2-3.4: New USB device found, idVendor=0a17, idProduct=3406
[ 5563.014195] usb 2-3.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 5563.014198] usb 2-3.4: Product: PocketJet3PlusB
[ 5563.014201] usb 2-3.4: Manufacturer: PENTAX
[ 5563.014204] usb 2-3.4: SerialNumber: 54027
[ 5563.015492] usblp 2-3.4:1.0: usblp1: USB Unidirectional printer dev 17 if 0 alt 0 proto 1 vid 0x0A17 pid 0x3406
</code>
Answer: You can find drivers for the printer
here.
A detailed instruction on how to install it is included.

Pentax PocketJet 3 Plus - Add printer


How to find the value inside a span using jquery?

Question: I need to find the value inside the each span when clicking on the delete button. Any help should be appreciated.When i click on the delete link i need to get back the username,projectname and module in raw.Example when i click on delete button near mysqlclient i need aasttest, mysite and mysql client as output.

<?php require_once 'cms_class.php';
$dj = new DCMSI();?>
<?php
$modules = $dj->view_user_modules(); ?>
<?php if(!$modules):?>
<?php echo ""; ?>
<?php else:?>

user modules

module	project	module

<?foreach ($modules as $key =>$value):?>

<?php echo $value['username'];?>
<?php echo $value['project'];?>
<?foreach ($value['modules'] as $key =>$value):?><?php echo $value['module']?>            delete
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif;?>

Comment: `.text()` is what you are looking for.
Comment: .text() will provide all the data in a row. But i need when i click on delete button near mysqlclient it var module will return mysqlclient.
Answer: Change your table and add a class to anchor tag.
 I have added class deldata

module	project	module

<?foreach ($modules as $key =>$value):?>

<?php echo $value['username'];?>
<?php echo $value['project'];?>
<?foreach ($value['modules'] as $key =>$value):?><?php echo $value['module']?>            delete
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif;?>

Comment: Thank you.. But exactly i need output mysqlclient when i click on a delete link near mysql client but i got mysqlclient but i make the changes in code you specified here.I got this output.This is not i am expecting.
django-bootstrap3   django-filter django-xadmin django-grappelli
Comment: can you give me outputted html ? so that i can look at it
Comment: mysqlclientdjango-bootstrap3django-filterdjango-xadmindjango-grappelli
Comment: no no..please inspect your browser and copy all code from  to  and then give me that code or make a fiddle and send me link
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126437/discussion-between-nidhin-and-rajesh-patel).
Answer: You could so something like this.

$(document).ready(function() {

  $("table").on("click", "tr", function(event) {
    var obj = {};
    obj.raw = $(event.target).siblings("span").html().trim();

    obj.module =
      $(event.currentTarget).find(".moduleName").html().trim();

    obj.project = $(event.currentTarget).find(".projectName").html().trim();
    console.log(obj);
  });

});
td,
th {
  border: 1px solid black;
}

      Module
      Project
      Module

      assttest

      myssite

          mysql
          delete

          django-filter
          delete

      assttest

      newsite

          Test Module
          delete


Issue with .ConfigureKestrel() method in .net Core

Question: I'm trying to create a very simple API with .net Core, and am exploring Kestrel. I am following the directions on this MS tutorial: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2
However, when I try to call the ConfigureKestrel method, Visual Studio tells me that "IWebHostBuilder does not contain a definition for 'ConfigureKestrel()' and no accessible extension method for ConfigureKestrel accepting a first argument of the type 'IWebHostBuilder' could be found (are you missing a using directive or an assembly reference?)"
I can't find any info on this, and I'm fairly sure I'm using the right libraries. Any help would be greatly appreciated - code is included:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace WebApplication2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();

        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel((context, options) =>
        {
            // Error with ConfigureKestrel method above
        });
    }
}

Comment: This is pretty sure an extension method from a namespace you do not import.
Comment: It's probably Microsoft.AspNetCore.Hosting or Microsoft.AspNetCore.Server.Kestrel
Comment: Even while using both of those namespaces it still doesn't seem to resolve the error.
Answer: I have created a sample application from scratch and this compiles:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureKestrel((a, b) => { });
    }
}

Can you check if this example works for you?
Please also check that you have the latest version of .Net Core, perhaps it was changed? The documentation is 2.2
Comment: My issue is that I was running 2.1 - thanks for the answer!
Answer: Found the VS2017 ASP.NET Core Web Application -> API running 2.1 does not have the ConfigureKestrel. However you can pass a KestrelServerOptions Action into UseKestrel instead which may give you the control your after. It overrides the settings from CreateDefaultBuilder.
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>().UseKestrel(options => options.Listen(IPAddress.Loopback,60000));

Incidentally I just found if you start with a plain .NetCore console app, then add...
    Microsoft.AspNetCore
    Microsoft.AspNetCore.Mvc

This gives you a (fairly minimalist) project running AspNetCore 2.2 instead of 2.1
Comment: I'm kind of curious now... if you used the KestrelServerOptions Action with 2.2 would it win or would the values  in the ConfigureKestrel Method win?


Change postfix name from "localhost" to something meaningful?

Question: I run postfix my servers to allow websites to send email. I'm using it as a drop-in for sendmail proper.
When an email is sent the HELO string seems to contain localhost. This wouldn't be a problem except that one of my clients has just said that an email was returned to them from a spam blocker saying that localhost cannot feature inside the HELO string. Awesome.
So I edited /etc/mailname to be my main domain name. And I edited /etc/postfix/main.cf so that:
smtpd_banner = ESMTP $mail_name

Yet this is what I see in the header of a sent email (after restarting postfix):
Delivered-To: email@example.com
Received: by 22.214.171.124 with SMTP id bi10csp117521wjc;
        Tue, 2 Apr 2013 07:24:18 -0700 (PDT)
X-Received: by 10.68.22.168 with SMTP id pt8mr24540246pbb.10.1364912657736;
        Tue, 02 Apr 2013 07:24:17 -0700 (PDT)
Return-Path: <firstname.lastname@example.com>
Received: from localhost (example.com. [188.8.131.52])
        by mx.google.com with ESMTP id l6si2328296pao.283.2013.04.02.07.24.16;
        Tue, 02 Apr 2013 07:24:17 -0700 (PDT)

I've subbed my domain with example.com.
What do I need to edit to quash the evil reign of localhost?!
Answer: Hurrrrrr.
I've just noticed that in /etc/postfix/main.cf there was a line that read:
myhostname = localhost

I've changed that to :
myhostname = example.com

And restarted. All is fixed.
Comment: I am trying this on Fedora 16.04 and even after a restart this does not work. I have set both `hostname` and `myorigin` to a real domain and the "evil regin" of localhost continues.  Any ideas?
Answer: What worked for me was to add smtp_generic_maps to the /etc/postfix/main.cf:
smtp_generic_maps = hash:/etc/postfix/generic

Create the /etc/postfix/generic file if it does not exist. Say you want to replace root@localhost, then do:
root@localhost email@example.com

Add it to configuration and restart
 sudo postmap /etc/postfix/generic
 sudo service postfix restart

References: https://www.cyberciti.biz/tips/howto-postfix-masquerade-change-email-mail-address.html


What colors gets bonus vs other colors?

Question: When I am playing I can see that some colors do half damage to some colored enemies and other colors do double damage.
What is a complete list of what bonus/weakness each color has?
Answer: How damage works:

If the color is vulnerable to the attack's color, the damage is
doubled;
If the color is resistant to the attack's color, the damage is
halved;
If the color is neutral to the attack's color, the damage is exactly
what it said on the tin.

How the colors stack up:

Red is vulnerable to blue and resistant to green. It is neutral to
itself, gold, and silver;
Blue is vulnerable to green and resistant to red. It is neutral to
itself, gold, and silver;
Green is vulnerable to red and resistant to blue. It is neutral to
itself, gold and silver;
Gold is vulnerable to silver. It is neutral to all other colors;
Silver is vulnerable to gold. It is neutral to all other colors.

What colors gets bonus vs other colors?


SetItem method in JS

Question: Recently I've been building todolist with javascript using localstorage. So idea was simple to store the lists in localstorage using number as key and listItem as value. When I tried to save a listItem the key was fine but value was the same as key it was number. Only when I appended "list" string to the key value everything started to work fine. So the question is why did it happen? Why?
Here is the code example:
DID NOT WORK (THE VALUE OF INPUT WAS NUMBER EQUAL TO THE KEY):
let key = Object.keys(localStorage);
key.length === 0 ? key = 1 : key = key.length + 1;

btn.addEventListener("click", () => {
    const inputValue = document.querySelector(".textarea").value;
    localStorage.setItem(key, inputValue);
    location.reload();
});

DID WORK:
let key = Object.keys(localStorage);
key.length === 0 ? key = "list1" : key = "list" + (key.length + 1);

btn.addEventListener("click", () => {
    const inputValue = document.querySelector(".textarea").value;
    localStorage.setItem(key, inputValue);
    location.reload();
});

P.S. I'm sorry for my poor English.
Answer: Simple answer, the key parameter of localStorage.SetItem should be a string.
You can use the first solution if your replace line 6 with:
localStorage.setItem(key.toString(), inputValue);

Also, I suggest you don't change your variables in the parts of your ternary expression.
You should replace line 1 with:
key = key.length === 0 ? 1 : key.length + 1;

But actually, you don't even need a ternary, you can replace it with
key = key.length + 1;

Another suggestion, you should evaluate "key" inside the event. So the whole code would look like this:
btn.addEventListener("click", () => {
    const key = Object.keys(localStorage).length
    const inputValue = document.querySelector(".textarea").value;
    localStorage.setItem(key, inputValue);
    location.reload();
});

SetItem method in JS


SQL Table "Pointer"?

Question: Using SQl Server 2000 I have a stored procedure that joins 2 tables and then returns the data. I want this sp to be able to do this for whatever table name I pass into it, otherwise I'll have the exact same code with the exception of the table name 20 or so times in a giant if statement. Basically, how do I use a variable to point to a table, or is that allowed? Thanks.
Answer: You need dynamic SQL, start here The Curse and Blessings of Dynamic SQL to learn how to do it correctly so that nobody drops your tables or does anything else possible with SQL Injection
Answer: Try building the SELECT as a string and then calling EXEC and passing the string.
e.g.
declare @sql varchar(500)
set @sql = 'select whatever from ' + @tableName
exec @sql

Answer: One proc to do anything is usually a bad bad idea. 20 possible tables I might need to go to depending on the circumstances almost always indicates a database design that is bad. Read the article Denis posted on the curses and blessings of dynamic SQL.
Comment: There are certain columns in every table that are consistent, and that is what I am pulling. Would it be better to have 20 if statements?
Comment: If I had five columns that were the same in 20 tables, I would pull them out to a separate parent table. That's what I mean about your database design being bad.
Comment: Possibly, but it wouldn't work with how I'm displaying the data and updating it.

SQL Table "Pointer"?