text:
Q: How to get the class prototype on the base of its name? How to get the class prototype on the base of its name?
This is my attempt:
// Environment detection (Browser or Node.js)
const isBrowser = new Function('try { return this === window } catch(e){ return false}')
// or
const isNode = new Function('try { return this === global }catch(e){ return false }')

// Get the window or global object
const getRoot = function(){
  if (isBrowser()){
    return (new Function('return window'))()
  }
  else{
    return (new Function('return global'))()
  }
}

// This is my class
class A {
  constructor(name,age){
    this.name = name
    this.age = age
    this.typeName = this.constructor.name
  }

  print(){
    return `${this.name}, ${this.age}`
  }
}

// Some JSON object (for example it is an DTO-object
// that I got from server or client). Each object has
// typeName property.
const obj = {name: 'Bob', age: 30, typeName: 'A'}

// I need to cast JSON-object to necessary type.
// I expected to get the class prototype on the base of its name

const root = getRoot() // window or global

// get class A
const _class = root[obj.typeName] // Oops... It is undefined

Object.setPrototypeOf(obj,_class.prototype)

console.log(obj.print())

UPD
I solved the problem:
const _proto = eval(`${obj.typeName}.prototype`);
Object.setPrototypeOf(obj,_proto)


text:
Q: How to solve if an integer has an integer root? I need to solve for any root of degree n that it has an integer root. My initial idea was to find the approximate root using Newton's method, however, would the power function not give us the maximum accuracy that can be expressed by the machine's floats?
function hasIntegerRoot( $integer, $degree ) {
    if( $degree == 0 || $degree == 1 ) return true;

    $r = pow( $integer, 1/$degree );

    //get nearest integer
    $n = round($r);

    //solve n^x
    $answer = pow( $n, $degree );

    return $answer == $integer;
}

I have two questions:
Does the power function solve sufficiently close to the integer root such that rounding the float will never return the wrong integer root? This would require it to be off by 0.5, which intuitively I could not imagine happening, but I have no arduous proof.
Secondly, does the return statement require decimal math? The issue is that for sufficiently large $integer and $n, PHP will use float. This is desirable in that it will not overflow large integers; however, it leaves use with floating point math, which inherently has inaccuracies. Would those inaccuracies affect my algorithm though?
Again, intuitively I feel like the constraints that $integer is an integer and that the root $n must be an integer avoids any floating point math issues. The math would never involve decimals. However, I have no way to absolutely prove the intuition.

A: I woudn't rely on pow() being accurate enough for this, but you could certainly start with pow(...,1/degree) and then walk $n up or down until $n**$degree matches or crosses $integer.  (But implement ** degree yourself, since internally it uses pow())
pow() is an approximation that doesn't always return the closest possible value to the exact result

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clarification for non-answers One of my flags for "non-answer" was declined and I was wondering if I misunderstood what "non-answer" means. I saw someone post an answer that was just a block of code, with nothing in it that was even the slightest related to the question, it was just a random block of code with no explanation. Should I have not used the "not an answer" tag even though the description explicitly says that it should be used when answers "do not attempt to answer the question"?

A: Can you say for sure the poster did not want to answer the question? Then it deserves a Not an answer flag. Examples:

*

*Me too

*Thanks

But if it is just a bad answer (of low quality or other issues) then downvote it.
If you need programming inside knowledge to see if the answer is an answer or not, then don't flag for NAA.

A: A block of code is almost certainly an answer on a coding site.  It might be a bad answer, but it is still an answer.  The only way it might not be an answer is if the OP posted the code to the wrong question, but that doesn't happen very often.
When in doubt, flag with a custom explanation instead of "not an answer," and explain why you think the answer is harmful.  Not an Answer flags are for things like "Thanks," "Any update?", questions posted as answers, and attempts to communicate with other users.
See Also
How do I properly use the "Not an Answer" flag?


text:
Q: SQL 2008 tables transfer I have two different database with different tables in the same SQL 2008.

*

*Access Control DB with 5000 Employee.

*TimeTrack DB.

How can I transfer the complete from Access Control DB to TimeTrack DB.
Please see attached tables.
Thanks and Best Regards.
Muhsin Jiwari
Baghdad - Iraq
1- [Access Control].[dbo].[TEmployee] Tables.


text:
Q: Duplicate definition of category in app when using modular headers, Objective-C & Swift in private pod With the introduction of Cocoapods v1.5 allowing Swift static libraries, I've been trying to convert my private pods (originally just Objective-C) to include Swift. I've managed to do this, but I'm left with a warning "Duplicate definition of category" for all categories in the pod.  It may be that I'm doing something rather stupid as modular headers are new to me.
I have two private pods, one is a shared library for development, and the other a shared library for tests. For brevity, I've removed some targets and pod references in the Podfile below.
I have noticed that the number of warnings can go up or down depending upon how I import code from the private pod in the app. Traditionally I have just used: #import "Class.h". Now, when I have tried to use @import ;, the warnings have gone up. Once when I used #import they went down. But not every time.
If I use #import  instead of #import "SomeClass.h",
 76 more warnings appear.
What am I doing wrong?
What I am finding is that if a category header file is only referred to via a .m file, the warning goes away.
source 'https://privatepod.url.com/git/my_podspec'
source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '9.0'

use_modular_headers!
inhibit_all_warnings!

def test_pods
  pod 'M13ProgressSuite', '~> 1.2',  :inhibit_warnings => true
  pod 'AimpTestKit', :path => '../aimptestkit',  :inhibit_warnings => false
  pod 'Quick', :inhibit_warnings => true
  pod 'Nimble',  :inhibit_warnings => true
end

def common_pods
    pod 'M13ProgressSuite', '~> 1.2',  :inhibit_warnings => true
    pod 'HockeySDK', :subspecs => ['AllFeaturesLib'],  :inhibit_warnings => true
    pod 'AimpKit', :path => '../aimpkit',  :inhibit_warnings => false
end

target 'free_app' do
    common_pods
    target 'free_app Tests' do
        inherit! :search_paths
        test_pods
    end

end

target 'paid_app' do
    common_pods
    target 'PaidAppTests' do
        inherit! :search_paths
        test_pods
    end
end

target 'LogicTests' do
    #no host app
    inherit! :search_paths
    common_pods
    test_pods
end

This is the podspec for the shared library (again I've removed some superfluous stuff for brevity):
{
    "name": "AimpKit",
    "version": "3.0.1",
    "summary": "AimpKit library",
    "static_framework": true,
    "platforms": {
        "ios": "9.0"
    },
    "source": {
    "git": "https://privatepod.url.com/git/my_podspec",
    "branch": "master"
  },
    "source_files": "aimpkit/**/*.{h,m,swift}",
    "resources": "resources/**/*.{xib,xcassets,storyboard,bundle,png,mp4}",
    "requires_arc": [
       "aimpkit/arc/**/*.{h,m,swift}"
  ],
     "frameworks": [
        "CFNetwork",
        "Foundation",

    ],
    "dependencies": {

    "HockeySDK/AllFeaturesLib": [

    ],

  }

}

A: The key to fixing this was to ensure that in class headers did not refer to a category header. Thus a class did not in its .h file import a category header. Moving all those category header file imports (big job) to the .m of each class file resolved this issue.
Also, had the issue that named categories declared inside a class header were also declared duplicate. Presumably because the class header was being invoked by other headers and the category definition in the class was being seen multiple times. The resolution here was to remove the name from the category definition.
All the category header files are referenced within a framework header (e.g ) surrounded by conditional statements so only parsed once (e.g #ifndef AimpKit_h #define AimpKit_h #endif).


text:
Q: Insert values from FORM to DB using AJAX on october cmd I'm trying to get form data and put it into the database using ajax.
I'm missing the DB insert part.
Couldn't find appropriate documentation on this one.
Please advice.
(it is a very basic usage. basic form, ajax and db)
Thank

A: You can see here the tutorial http://www.tutorialspoint.com/ajax/ajax_database.htm


text:
Q: How can time dilation make two photons move at the speed of light? So I'm goin down the highway at 25mph and there's a photon moving the same direction I am (ridden by Klaus) and a photon moving the opposite direction (ridden by Steff). I know Klaus and Steff have to be moving at the speed of light from my perspective, but how does time dilate for this to happen? It seems like Steff needs to slow down and thus time needs to speed up for me, but Klaus needs to speed up and thus time needs to slow down for me. How is time dilation able to make Klaus and Steff both appear to be moving at the speed of light from my perspective?
Sorry for good illustration

A: Time dilation is one of the consequences of a constant speed of light and not the cause for it.
If we assume $c$ to be constant and then move at some photons emitted towards us, one would think that the velocity of these photons would be greater than $c$. So in order to still have them moving at $v=c$, time "has to" slow down by just the factor that their velocity is $c$.
Of course this is not the actual cause for why time dilation happens, but it might give you some intuitive understanding.


text:
Q: JavaScript: check if date A is at most 3 times earlier/late than date B I have to write a JavaScript function that checks if two dates (formatted dd/MM/yyyy) make a time interval of at most 3 months.
I can retrieve the two values from two textboxes (no need to check formatting, I have been given a calendar control that automatically formats the date correctly).
I have almost no experience with JavaScript. Can you help me?
Examples:
15/2/2011, 13/2/2011 -> return true
6/1/2011, 5/10/2010 -> return false
I already check that date A is later than date B (the calendar does it for me)

A: You can find difference between two dates and return value accordingly.
function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // check converting back to days and return
    return (Math.round(difference_ms/ONE_DAY) >90);
}

If you are unable to check or parse date correctly then you should use
    var x=txtDate1.split("/");   //Here txtDate1 and txtDate2 are values from your textbox
    var y=txtDate2.split("/");
  //date format(Fullyear,month,date)

    var date1=new Date(x[2],(x[1]-1),x[0]);
    var date2=new Date(y[2],(y[1]-1),y[0])

A: No need for a ton of code:
function days_between(date1, date2) {
    return Math.round(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)) > 90;
}

date1 and date2 are Date objects e.g.
 var date1 = new Date('mm/dd/yyyy');


text:
Q: Firebase returns null value for a particular child even if it exists I have a class ComRec which stores certain commission values. In the calculator I input some values and perform some operations then store it under particular user in firebase. Then I create a pdf table with the values from ComRec object. But my problem is the member "koil" shows the value null even if it is present in the ComRec object.
public class ComRec {
private Double freeRation;
private Double npnsRice;
private Double npsRice;
private Double phhRice;
private Double aayRice;
private Double npnsWheat;
private Double phhWheat;
private Double aayWheat;
private Double atta;
private Double total;
private Double koil;
private Double sugar;
private Double totalCommission;

public ComRec(){

}

public ComRec(Double freeRation, Double npnsRice, Double npsRice, Double phhRice, Double aayRice, Double npnsWheat, Double phhWheat, Double aayWheat, Double atta, Double total, Double koil, Double sugar , Double totalCommission) {
    this.freeRation = freeRation;
    this.npnsRice = npnsRice;
    this.npsRice = npsRice;
    this.phhRice = phhRice;
    this.aayRice = aayRice;
    this.npnsWheat = npnsWheat;
    this.phhWheat = phhWheat;
    this.aayWheat = aayWheat;
    this.atta = atta;
    this.total = total;
    this.koil = koil;
    this.sugar = sugar;
    this.totalCommission = totalCommission;

}

User class
public class User {
private String UID;
private String ardNo;
private String email;
private String serialKey;
private String taluk;
private ComRec C;

public User(){

}

public User(String UID, String ardNo, String email, String serialKey,String taluk) {
    this.UID = UID;
    this.ardNo = ardNo;
    this.email = email;
    this.serialKey = serialKey;
    this.taluk = taluk;
    this.C = null;
}
public User(String UID, String ardNo, String email, String serialKey,String taluk,ComRec C) {
    this.UID = UID;
    this.ardNo = ardNo;
    this.email = email;
    this.serialKey = serialKey;
    this.taluk = taluk;
    this.C = C;
}

public String getUID() {
    return UID;
}

public void setUID(String UID) {
    this.UID = UID;
}

public String getArdNo() {
    return ardNo;
}

public void setArdNo(String ardNo) {
    this.ardNo = ardNo;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getSerialKey() {
    return serialKey;
}

public void setSerialKey(String serialKey) {
    this.serialKey = serialKey;
}

public String getTaluk() {
    return taluk;
}

public void setTaluk(String taluk) {
    this.taluk = taluk;
}

public ComRec getComRec() {
    return C;
}

public void setComRec(ComRec c) {
    C = c;
}

}
This is my firebase data, You can see koil = 172.5:

All the other members gives correct value but koil

This is how initialise ComRec object by taking it from User class

A: Base on your database structure you can use this to get the Koil
  DatabaseReference reff = FirebaseDatabase.getInstance().getReference("User");
    reff.child(user.getUid()).child("comRec").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                ComRec com = snapshot.getValue(ComRec.class);
                Double Koil = com.getkoil();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });


text:
Q: "Compile Error" with array-reference this is my first post on here, so please be gentle if I missed anything or screwed up.
I've been working on an Excel-Tool in Excel 2010 and am currently testing if it also works in Excel 2013.
Most of it works all fine, but I got one small Problem that confuses me. When I open the file in 2013, enter some data and test it, it runs smoothly; but when I go back to 2010 to use the same file I get the message "Compile Error: Can't Find Project or Library."
Option Explicit

Private Sub Label1_Click()

If Application.Sum([ci_pke_cfbiat]) < 0 Then
     MsgBox ("With the current numbers, Excel won't be able to calcualte a   valid IRR.")
End If

Call IRRcalculation(Me.Name)

Call Paybackcalculation(Me.Name)

End Sub

The highlighted part of the code after I hit the "debug" button is the array reference "[ci_pke_cfbiat]". Now I already did some research on that matter and looked into the references on both 2010 and 2013, and found that under Excel 2010 it says "MISSING: Microsoft PowerPoint 15.0 Object Library". When I deactivated that reference all works as it is supposed to. What I don't understand is why a PowerPoint-Library would cause a problem for my array-references?
Also, is there some "easy" way to solve this problem; easier than manually turning that library off everytime I open a file from 2013 in 2010? I already tried some things in the code like using "VBA." instead of "Application." and similar, but that didn't work.
Again sorry if I did anything wrong, and I hope this topic hasn't been discussed somewhere else already; I couldn't find anything related that was really helpful. Thanks in advance!


text:
Q: Margin layout programmatically is not working can somebody solve my problem (there is no margin/space for vertical menu) ? see my code link http://pastebin.com/zzdY3QQR

A: Try this..
LinearLayout menuvertical = (LinearLayout) findViewById(R.id.menuvertical);
    for (int i = 0; i < arrseparate.size(); i++) {
        TextView menucategory = new TextView(getBaseContext());

        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        llp.setMargins(50, 0, 0, 0);
        menucategory.setText(arrseparate.get(i).toString());
        menucategory.setTextSize(25);
        menucategory.setTextColor(Color.WHITE);
        menucategory.setBackgroundResource(R.layout.bordermenu);
        final int j = i;
        menucategory.setGravity(Gravity.CENTER_HORIZONTAL);

        if (j != 0) {
            menucategory.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    OtherClass.setCategory(arrseparate.get(j).toString());

                    Global.MainActivity.finish();
                    Intent MyIntent = new Intent(getBaseContext(),
                            ViewProduct.class);
                    startActivity(MyIntent);
                }
            });
        }
        menuvertical.addView(menucategory, llp);
    }


text:
Q: How do I streaming tweets in real time to discord? I'm using twitter API so, I can stream tweets to my discord channel.
However, I notice a few things:

*

*When I turn on the script, it shows me past tweet, I just want real time tweets being sent out.

*Some of the tweets includes retweets and replies and as a result, I would like to filter them.

My Objective is to stream tweets in real time and send those tweet to discord, but I just want the text contents of the tweets and nothing else.

const dest = '####################';

const stream = twitterClient.stream('statuses/filter', {
  follow: '#######', // Twitter ID
});

stream.on('tweet', tweet => {
  const twitterMessage = `${tweet.text}`
  client.channels.cache.get(dest).send(twitterMessage);
  return false;
});

A: If you want to filter the tweets then have a look to the Twitter  API documentation. https://developer.twitter.com/


text:
Q: Search Array and Set Environment Variables My Postman response body is this:
{
"jobs": [
    {
        "id": "00d21be0",
        "name": "IT Department"
    },
    {
        "id": "h27da349",
        "name": "Car Sales"
    },
    {
        "id": "5d2db4125",
        "name": "Grocery Clerk"
    },
    {
        "id": "65cd0cc1d",
        "name": "Accounting Department"
    },
    {
        "id": "8462284587",
        "name": "Nurse"
    },
    {
        "id": "9fe2ff9ee4",
        "name": "Astronaut"
    },
    {
        "id": "f40cb44799",
        "name": "Phone Operator"
    },
    {
        "id": "f4e0483257",
        "name": "Project Leader"
    }
]

}
What I would like to do is parse this response and set an Environmental Variable for id's associated with Nurse, Astronaut, and Grocery Clerk.  The rest of the info I do not need.  I cannot use the array [number] because its not a guarantee they come in the same order on other systems.
Is JSON.stringify response body the way to go? How do I pull those values?
My Postman test so far is:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentalVariable("jobs", JSON.stringify(jsonData));

A: What you can do is parse your json body with a loop and, when you hit the names you want, you set a global variable with the corresponding id, like :
// get the response body
var jsonData = JSON.parse(responseBody);
// init counter
var loop_count = 0

for (count = 0; count < jsonData.jobs.length; count++)
{
    if (jsonData.jobs[count].name == "Nurse")
    {
        var job_id = jsonData.jobs[count].id;
        postman.setEnvironmentalVariable("env_nurse", job_id);
    }
}

This is the principle.
You can do if/else for the different names you want to catch but I don't recommend it (use an array that you can expand easily).
Same thing for the environment variable name, instead of hard coding, try to generate it with respect to your element name.


text:
Q: Using copy with whitespace in batch file I have a script to copy file in batch file:

*

*copy C:\File\text.txt C:\FileCopy\text.txt
--> It's ok. But when I use

*copy C:\File\text.txt C:\File Copy\text.txt
--> It doesn't work because "File Copy" has whitespace. The system can not find the patch specified.

A: Use quotation marks:
copy "C:\File\text.txt" "C:\File Copy\text.txt"

A: Use double quotes
copy "C:\File\text.txt" "C:\File Copy\text.txt"

check


text:
Q: How to share an existing dynamic array within Linux POSIX model in c language? I have very big quickly growing (realloc, tcmalloc) dynamic array (about 2-4 billion double). After the growth ends I would like to share this array between two different applications. I know how to prepare shared memory region and copy my full-grown array into it, but this is too prodigally for memory, because I must to keep source and shared destination array at the same moment. Is it possible to share already existing dynamic array within POSIX model without copying?
EDITED:
Little bit explanation.
I am able to use memory allocation within POSIX model (shm_open() and others) but if I do it, I have to reallocate already shared memory segment many times (reading digits row by row from database to memory). It is much more overhead in comparison with simple realloc().
I have one producer, who reads from database and writes into shared memory.
I can't know beforehand how many records are present in the database and therefore I can't know the size of the shared array before the allocation. For this reason I have to reallocate big array while producer is reading row by row from database. After the memory is shared and filled, another applications  reads data from shared array. Sometimes size of this big shared array could be changed and be replenished with new data.

A:
Is it possible to share already existing dynamic array within POSIX model without copying?

No, that is not how shared memory works. Read shm_overview(7) & mmap(2).
Copying two billion doubles might take a few seconds.
Perhaps you could use mremap(2).
BTW, for POSIX shared memory, most computers limit the size of the of the segment shared with shm_open(3) to a few megabytes (not gigabytes). Heuristically the maximal shared size (on the whole computer) should be much less than half of the RAM available.
My feeling is that your design is inadequate and you should not use shared memory in your case. You did not explain what problem you are trying to solve and how is the data modified
(Did you consider using some RDBMS?). What are the synchronization issues?
Your question smells a lot like some XY problem, so you really should explain more, motivate it much more, and also give a broader, higher-level picture.


text:
Q: Spring webserver how to share file in folder How can I share file in folder using Spring eg. /tmp/file.mp4. that it is accessible from the IP? Like this 10.11.14.122/file.mp4

A: Your question is need spring-boot to serve your static files. You just need to configure the path in Override addResourceHandlers, full code:
@SpringBootApplication
public class TmpApplication extends WebMvcConfigurerAdapter {

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/tmp/**").addResourceLocations("file:///./myfolder/")
                .setCachePeriod(0);
    }
}

There is a document: boot-features-spring-mvc-static-content


text:
Q: Limiting the touch area in the navigation barbutton item? In iphone i  have known that the navigationbarbutton touch has also some extension under the navigation bar.But i need to limit the userinteraction to only a certain limit.Can i able to do that.Can anybody help me ?

A: Implement a tap gesture recognizer and set your controller as delegate. Then implement:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

   // [touch locationInView] -> gives the point where the user touched
   // If the touch point belongs to your frame then return YES
   // else return NO

}

A: You can implement a custom navigation bar yourself with hidden navigation bar "engine" behind and have the buttons on the custom navbar with the required custom behavior/visuals.
This also can be useful if you want to implement gesture logic (pan) to switch navigation pages.
AppDelegate.h:
@property (strong, nonatomic) UINavigationController *navigationController;

AppDelegate.m:
YourMainViewController *yourmainViewController = [[YourMainViewController alloc] init];
_navigationController = [[UINavigationController alloc] yourmainViewController];
[_navigationController setNavigationBarHidden:TRUE];
[self.window setRootViewController:_navigationController];
[self.window makeKeyAndVisible];

YourMainViewController.m:  implement your view with custom navigation image and added buttons for navigation either using Interface Builder or programatically. For example programatically create your view:
- (void)loadView {
...
    UIImageView *tmp_mynavbar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CustomNavBG.png"]];
    tmp_mynavbar.frame = CGRectMake(0, 0, 320, 44);
    [self.view addSubview:tmp_mynavbar];
    UIButton *tmp_addbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    tmp_addbutton.frame = CGRectMake(260, 10, 40, 20);
    [tmp_addbutton setTitle:@"Add" forState:UIControlStateNormal];
    [tmp_addbutton setBackgroundImage:[UIImage imageNamed:@"CustomNavAddBtn.png"] forState:UIControlStateNormal];
    [tmp_addbutton addTarget:self action:@selector(pressedbuttonAddItem:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tmp_addbutton];

// create button with the required size, user interaction area (add image then add transparent button with different size, etc)
// also add a back button
...
}

then implement custom navigation button behavior (the add/next button and also the back button)
-(void) pressedbuttonAddItem:(id) sender {
    AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication] delegate];
    DetailViewController *detailViewController = [[DetailViewController alloc] init];
    [[app navigationController] detailViewController animated:YES];
}

-(void) pressedbuttonBack:(id) sender {
    AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication] delegate];
    [[app navigationController] popViewControllerAnimated:YES];
}


text:
Q: Find array subscript and value which is same I have a sorted array of n elements. The values can be negative or positive.
The specialty of this array is that out of n elements, there is 1 particular element where a[x]=x and the rest of the data does not satisfy the condition.
Is there any better way to find such an 'x' apart from looping the entire array.
Suppose my array is [-2999,-33,0,2,4,67,654]
Here a[4]=4 and the rest does not match such a criterion..

A: Since the array is already sorted, you can use binary search which is O(lgn) to find the element.
You can also ignore all negative valued elements because an index cannot be negative.
http://en.wikipedia.org/wiki/Binary_search_algorithm

A: you can use this. This is O(N).
for(i=0;i<MAX;i++){
    if(i==array[i]){//do something}
}

If the array is sorted in descending order use
for(i=MAX-1;i>=0;i11){
    if(i==array[i]){//do something}
}

Here MAX is size of array


text:
Q: How to create a "Clustergram" plot ? (in R) I came across this interesting website, with an idea of a way to visualize a clustering algorithm called "Clustergram":

(source: schonlau.net)
I am not sure how useful this really is, but in order to play with it I would like to reproduce it with R, but am not sure how to go about doing it.
How would you create a line for each item so it would stay consistent throughout the different number of clusters?
Here is an example code/data to play with for potential answer:
hc <- hclust(dist(USArrests), "ave")
plot(hc)

A: Update: I posted a solution with a lengthy example and discussion here.  (it is based on the code I gave bellow).  Also, Hadley was very kind and offered a ggplot2 implementation of the code.
Here is a basic solution (for a better one, look at the "update" above):
set.seed(100)
Data <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
              matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(Data) <- c("x", "y")

# noise <- runif(100,0,.05)
line.width <- rep(.004, dim(Data)[1])
Y <- NULL
X <- NULL
k.range <- 2:10

plot(0, 0, col = "white", xlim = c(1,10), ylim = c(-.5,1.6),
     xlab = "Number of clusters", ylab = "Clusters means",
     main = "(Basic) Clustergram")
axis(side =1, at = k.range)
abline(v = k.range, col = "grey")

centers.points <- list()

for(k in k.range){
    cl <- kmeans(Data, k)

    clusters.vec <- cl$cluster
    the.centers  <- apply(cl$centers,1, mean)

    noise <- unlist(tapply(line.width, clusters.vec,
                           cumsum))[order(seq_along(clusters.vec)[order(clusters.vec)])]
    noise <- noise - mean(range(noise))
    y <- the.centers[clusters.vec] + noise
    Y <- cbind(Y, y)
    x <- rep(k, length(y))
    X <- cbind(X, x)

    centers.points[[k]] <- data.frame(y = the.centers , x = rep(k , k))
#   points(the.centers ~ rep(k , k), pch = 19, col = "red", cex = 1.5)
}

require(colorspace)
COL <- rainbow_hcl(100)
matlines(t(X), t(Y), pch = 19, col = COL, lty = 1, lwd = 1.5)

# add points
lapply(centers.points,
       function(xx){ with(xx,points(y~x, pch = 19, col = "red", cex = 1.3)) })


text:
Q: ~2 Hours after a large insert SQL Server gets "I/O requests taking longer than 15 seconds to complete" This problem has been haunting me for a while but I actually fixed the queries that caused the problems (after I finally found them) but i'm curious if it's an SQL Process that's the underlying problem our that our raidcontrollers are shit or what the problem truely is. So here's the scenario that's been bothering us.
@ 11:10~ and 01:10~ the server would give these IO errors, even through Remote desktop the servers would fail, management studio would give timeouts, everything would point towards imminent failure of the cluster.
(The servers are identical, we run Windows Server 2012 standard, clustered in an AlwaysOn running SQL Server 2012 Enterprise edition).
Around 5-15 minutes later, the servers would come back to live (without anything in the eventlogs except for the Event ID 833 which is the "well known": SQL Server has encountered 16870 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [E:\XXXXXXXX.mdf] in database [XXXXX] (10).  The OS file handle is 0x0000000000001284.  The offset of the latest long I/O is: 0x0000041fb3c000).
Now I was running profilers to find out which queries were running, doing anything I could to figure out what would cause the servers to just freeze up and refuse to service properly. The event log aims towards a specific Database to I searched in that direction and yesterday I found a table that looked odd to me.
The specific table was 11 gigs large, had indexes worth 23 gigs (haven't looked into those yet but that seemed wrong to me) and had 80 million records. Considering the table should hold around 2 million and be growing relatively slowly this sparked my interested and I found three stored procedures which fill this table.
All three storedprocedures had flaws which made them insert not a few hundred records but over 500.000 each time they ran. (These are now fixed so the issue doesn't present itself but I feel there is an underlying problem here).
These stored procedures would run @ 09:00 and 23:00 (excatly 2 hours before the problems occurred). The procedures themselves would take around 5 minutes to run to completion.
Now I'm wondering why it would take the servers two hours to start dying on me after the actual storedprocedures in question would already have been done. I don't run any index maintenance at that point, or anything else for that matter (it's the first thing I checked for). For all I know nothing runs @ the specific times. Could it be SQL Server does some 'self maintenance' and notices that some indexes need to be defragmentated or something even if I haven't asked for any such thing?
Could it be our raidcontrollers (or even the SSD's that are connected to them) that are flawed and after A LOT of activity decide to show signs of degration after 2 hours?
I simply can not explain this behavior and I'm worried our production servers might be unreliable (which would suck since they're around 4 months old). Now i've fixed this issue last evening, and for 24 hours we haven't had this problem (I wouldn't call it 'resolved' unless it's been stable for multiple days) but I'm still very curious what the hell my servers are doing.

A: BOL refers to 833 event ID as :

This problem can be caused system performance issues, hardware errors, firmware errors, device driver problems, or filter driver intervention in the IO process.

What it means is that

*

*SQL server is doing more I/O's that what the disk subsystem can handle.

*There could be some rogue process running on the system that is saturating the disks with all the I/O requests.

Below is the approach I would follow:
Troubleshoot using Wait Statistics - DMV's
WITH [Waits] AS
    (SELECT
        [wait_type],
        [wait_time_ms] / 1000.0 AS [WaitS],
        ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],
        [signal_wait_time_ms] / 1000.0 AS [SignalS],
        [waiting_tasks_count] AS [WaitCount],
        100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() AS [Percentage],
        ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats
    WHERE [wait_type] NOT IN (
        N'CLR_SEMAPHORE',    N'LAZYWRITER_SLEEP',
        N'RESOURCE_QUEUE',   N'SQLTRACE_BUFFER_FLUSH',
        N'SLEEP_TASK',       N'SLEEP_SYSTEMTASK',
        N'WAITFOR',          N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
        N'CHECKPOINT_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH',
        N'XE_TIMER_EVENT',   N'XE_DISPATCHER_JOIN',
        N'LOGMGR_QUEUE',     N'FT_IFTS_SCHEDULER_IDLE_WAIT',
        N'BROKER_TASK_STOP', N'CLR_MANUAL_EVENT',
        N'CLR_AUTO_EVENT',   N'DISPATCHER_QUEUE_SEMAPHORE',
        N'TRACEWRITE',       N'XE_DISPATCHER_WAIT',
        N'BROKER_TO_FLUSH',  N'BROKER_EVENTHANDLER',
        N'FT_IFTSHC_MUTEX',  N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
        N'DIRTY_PAGE_POLL',  N'SP_SERVER_DIAGNOSTICS_SLEEP')
    )
SELECT
    [W1].[wait_type] AS [WaitType],
    CAST ([W1].[WaitS] AS DECIMAL(14, 2)) AS [Wait_S],
    CAST ([W1].[ResourceS] AS DECIMAL(14, 2)) AS [Resource_S],
    CAST ([W1].[SignalS] AS DECIMAL(14, 2)) AS [Signal_S],
    [W1].[WaitCount] AS [WaitCount],
    CAST ([W1].[Percentage] AS DECIMAL(4, 2)) AS [Percentage],
    CAST (([W1].[WaitS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgWait_S],
    CAST (([W1].[ResourceS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgRes_S],
    CAST (([W1].[SignalS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgSig_S]
FROM [Waits] AS [W1]
INNER JOIN [Waits] AS [W2]
    ON [W2].[RowNum] <= [W1].[RowNum]
GROUP BY [W1].[RowNum], [W1].[wait_type], [W1].[WaitS],
    [W1].[ResourceS], [W1].[SignalS], [W1].[WaitCount], [W1].[Percentage]
HAVING SUM ([W2].[Percentage]) - [W1].[Percentage] < 95; -- percentage threshold
GO

Look at the pending I/O's
SELECT database_id
    ,file_id
    ,io_stall
    ,io_pending_ms_ticks
    ,scheduler_address
FROM sys.dm_io_virtual_file_stats(NULL, NULL) t1
    ,sys.dm_io_pending_io_requests AS t2
WHERE t1.file_handle = t2.io_handle

Below are PERFMON counters that will help you:

*

*Avg. Disk sec/Transfer => Time taken to perform the I/O operation

*Disk Bytes /sec  => Total reads and writes to disk per second in bytes.

*Process:IO Data Bytes/Sec => Total reads and writes to disk per second in bytes by each process.

*Buffer Manager: Page Read/sec + Page Writes/sec =>Total reads and writes to disk per second in bytes by SQL Server process.

Also, sometimes such errors can also occur when a different Power Management scheme is selected for the server. So better check your Windows Power Plan setting, and make sure you are using the High Performance Power Plan.

All three stored procedures had flaws which made them insert not a few hundred records but over 500.000 each time they ran. (These are now fixed so the issue doesn't present itself but I feel there is an underlying problem here).

If you are inserting a huge amount of data, then you need to refer to The Data Loading Performance Guide to cater your server for such operations e.g. enabling trace flag 610.
Note: Others have mentioned that Auto Update Stats might be causing it, which is also worth looking at, but I would primarily concentrate on finding out rouge process that is causing lots of Disk I/Os and checking the storage subsystem to see if all the divers, etc are up-to-date and is configured correctly.
Good reading links :

*

*I/O requests taking longer than 15 seconds to complete on file

*Troubleshooting SQL Server I/O requests taking longer than 15 seconds - I/O stalls & Disk latency

*Event ID 833: I/O requests taking longer than 15 seconds

A: I might be teaching my grandmother to suck eggs here. If so, apologies.
DMVs (http://technet.microsoft.com/en-us/library/ms188754.aspx) could help you rule out a lot of things inside the RDMS. At the very least you'll be able to see what is running when and where... assuming the DBAs let you have access.
If the RDMS turns out not to be the culprit, you could look at enabling some PerfMon perf counters or event collectors to see if you can identify any driver or app that may be hitting your OS (http://technet.microsoft.com/en-us/library/cc749249.aspx).

A: You mention that the stored procedures should be done.  My guess is that without any transaction marshaling the data is accumulated and then finally committed about 2 hours later.
You mention you ran profiler, but I would look at Adam Machanic's sp_whoisactive at http://whoisactive.com/
It will give you all sorts of information.

A: If you are using auto-update statistics, the update wouldn't occur until a query attempts to use them. So you can have this large insert that would exceed a threshold, but then occur 2 hours later when a query that would use them is run. You could then experience long I/O requests or timeouts while they wait for the statistics to be updated. In addition, after statistics are updated the queries will recompile which also adds overhead.
You have options to change this behavior but any that you choose will have consequences that must be considered as well.
https://msdn.microsoft.com/en-us/library/ms190397.aspx#UpdateStatistics


text:
Q: Is $ U = \{f(x)| f(x) \in P_{3}, \operatorname{deg} f(x) = 3\}$ a subspace of $P_{3}$? Given : $ U = \{f(x)| f(x) \in P_{3}, \operatorname{deg} f(x) = 3\}$
Does: U is a subspaces of $P_{3}$
I think the answer is yes. But in my textbook, they say no. And explain that zero is not in set, and scalar multiplication and addition are not closed under U.
Please explain for me.
Thanks :)

A: $U$ is not closed under addition.  For example, take $x^3$ and $-x^3$.  Adding these gives the polynomial $0$, which does not have degree $3$, whence $0\notin U$.


text:
Q: GRE percentage problem (Tricky)
The number of television sets sold by Store R last month was approximately what percent less than the number of television sets sold by Store T last month?
The answer is 56 percent, which I have no idea how it's solved. I just get 25 percent by finding the percentage change from $40$ to $50$. Not sure how the answer is 56 percent. Any thoughts would be greatly appreciated.

A: As the number of units of products sold by the stores is given in the second graph, we should not look at the data from the first and proceed the calculation.
Note that the number of units sold are expressed as a percentage of number of units in stock, based on data from the first graph.
Number of units sold by store $R = 50$% of units in stock$_{R} = \frac {1}{2}\times 40 =20$
Number of units sold by store $T = 90$% of units in stock $_{T} = \frac {9}{10}\times 50 =45$
Now, $$\text {percentage change} = \frac {45-20}{45} \times 100 $$ $$= \frac {5}{9} \times 100 = 55.55 \text {  percent  } \approx 56 \text {  percent  } $$
Hope it helps.


text:
Q: Can devices without Compass/Magnetic sensor support AR? I was trying out the sample Android augmented reality app found here.
 It works fine on devices with a magnetic sensor. But it doesn't work in devices with only Accelerometer, which does not have a  Compass/ Magnetometer sensor.
I debugged the code and what I can see is only devices with magnetic sensor gives proper values as the device rotates. Devices with only Accelerometer does not calculate values like azimuth
 and therefore it does not respond to the device rotation and movement.
So since I don't have much knowledge about AR implementation, I just wanted to ask a simple question.
 Can AR be implemented only in devices with Compass/ Magnetometer?
devices with only Accelerometer sensor will not support AR in Android?

A: Augmented Reality can be implemented in different types.

*

*Marker-Based AR (Recognition based AR)

*QR Based AR

*Location Based AR

*Projection Based AR

The example which you checked is under location Based AR.
For Location Based AR App uses

*

*the camera view

*the user's location

*and other device sensors, especially a compass (accelerometer and gyroscope can also be useful)

For more example try using Vuforia Sdk you will get more information on Vuforia Developer Site.


text:
Q: modal con vueJS se muestra, pero no puedo hacer nada Estoy creando una ventana modal con vueJS, que ya he creado en un componente anterior...
El modal, se crea perfectamente, al hacer click en el botón, se muestra, pero se queda debajo del fade y no puedo hacer click en el ni hacer nada... No se que está fallando la verdad.
Adjunto código de mi componente vue
    <template>

                Código de asistencia.
                <input type="text" v-on:keyup="codigoAsistencia" id="codigoAsistencia" placeholder="Código" class="form-control" >
                Cliente.
                <input type="text" v-on:keyup="buscarUsuario" id="nombreCliente" placeholder="Cliente" class="form-control" >
                Estado.

                <select @change="buscarEstado($event)" class="form-control">
                    <option value="en_proceso">En proceso</option>
                    <option value="finalizada">Finalizada</option>
                </select>

                Fecha de inicio.
                <input type="date" id="fechaInicio" placeholder="Fecha Inicio" class="form-control">
                Fecha fin.
                <input type="date" v-on:change="buscarFecha" id="fechaFin" placeholder="Fecha Fin" class="form-control">

                            Código
                            Fecha
                            Usuario
                            Estado
                            Tiempo empleado actuación
                            Actuaciones

                            {{data.codAsistencia}}
                            {{data.fecha}}
                            {{data.nombre}}

                                <select @change="cambiarEstado(data.codAsistencia, $event)">
                                    <option value="0" selected>{{data.estado}}</option>
                                    <option value="en_proceso">En proceso</option>
                                    <option value="finalizada">Finalizada</option>
                                </select>

                            {{data.tiempoEmpleado}}
                            Actuaciones

                            <button type="button" class="close" data-dismiss="modal">
                                ×
                            </button>

                                Fecha
                                Tiempo Empleado
                                Bono
                                Tiempo Contratado
                                Tiempo Restante

                                        {{ data.fecha }}
                                        {{ data.tiempoEmpleado }}
                                        {{ data.bono }}

                                        {{ data.tiempoRestanteBono }}
                                        <input type="hidden" id="asistencia" v-model="data.codAsistencia">

                                <button type="button" class="btn btn-primary" @click="iniciarActuacionConActuaciones">Iniciar Actuacion</button>
                                <button type="button" class="btn btn-primary" @click="detenerActuacionConActuaciones">Detener Actuacion</button>

                            0:0

</template>


text:
Q: PHPMailer: duplicate email I am using OPHPMailer to send a form in the meantime, when sending this image appears and the email is duplicated in my inbox.
I'm using Yahoo Mail
PHP send

A: <?php
date_default_timezone_set('America/Sao_Paulo');

require_once('src/PHPMailer.php');
require_once('src/SMTP.php');
require_once('src/Exception.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$nome = isset($_POST['nome']) ? $_POST['nome'] : 'Não informado';
$telefone = isset($_POST['telefone']) ? $_POST['telefone'] : 'Não informado';
$email = isset($_POST['email']) ? $_POST['email'] : 'Não informado';
$assunto = isset($_POST['assunto']) ? $_POST['assunto'] : 'Não informado';
$mensagem = isset($_POST['mensagem']) ? $_POST['mensagem'] : 'Não informado';
$data = date('d/m/Y H:i:s');

if($email && $mensagem ) {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = 1;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'ssl';
    $mail->Host = 'smtp.mail.yahoo.com';
    $mail->Port = 465;
    $mail->Username = 'Email hidden for security';
    $mail->Password = 'Password hidden for security';

    $mail->ClearAllRecipients();
    $mail->setFrom('Email hidden for security');
    $mail->addAddress('Email hidden for security');

    $mail->isHTML(true);
    $mail->Subject = $assunto;
    $mail->Body = "Nome: {$nome}

                Telefone: {$telefone}

                Email: {$email}

                Mensagem: {$mensagem}

                Data/hora: {$data}";
    if($mail->send()) {
        echo 'Email enviado com sucesso';
    } else {
        echo 'Email nao enviado';
        }
}


text:
Q: Why doesn't my servo control work? Basically I'm trying to control a servo with two push buttons (one for forward and one for backward). However, my code doesn't work and I am not sure why. Essentially I used the Sweep and Button examples to make this code. However, it doesn't seem to be working unless something is wrong with my hookup.

#include <Servo.h>

Servo servoOne;
int servoOnePos = 0;
const int buttonUpPin = 13;
const int buttonDownPin = 12;
int buttonUpState = 0;
int buttonDownState = 0;

void setup() {
  servoOne.attach(11);
  pinMode(buttonUpPin, INPUT);
  pinMode(buttonDownPin, INPUT);
}

void loop() {
  buttonUpState = digitalRead(buttonUpPin);
  buttonDownState = digitalRead(buttonDownPin);
  if (buttonUpState == HIGH) {
    for (servoOnePos < 180; servoOnePos += 1;) {
      servoOne.write(servoOnePos);
      delay(15);
    }
  } else if (buttonDownState == HIGH) {
    for (servoOnePos <= 180; servoOnePos = servoOnePos - 1;) {
      servoOne.write(servoOnePos);
      delay(15);
    }
  }
}

A: #include <Servo.h>

Servo servoOne;

int pos = 90;
const int maxDeg = 160;
const int minDeg = 5;

const int buttonUpPin = 13;
const int buttonDownPin = 12;

const int leftPin = 3;
const int rightPin = 2;

int leftPressed = 0;
int rightPressed = 0;

void setup()
{
  servoOne.attach(11);
  pinMode(buttonUpPin, INPUT);
  pinMode(buttonDownPin, INPUT);
}

void loop()
{
leftPressed = digitalRead(leftPin);
rightPressed = digitalRead(rightPin);

 if(leftPressed){
   if(pos < maxDeg) {
     pos += 3;
   }
    servoOne.write(pos);
 }
 if(rightPressed){
   if(pos > minDeg) {
     pos -= 3;
   }
     servoOne.write(pos);
   }
  delay(15);
}


text:
Q: User needs to login twice We're currently sampling High Sierra 10.13.1 on a few machines in the office. One of the users is getting a strange issue after a password reset.
When she reboots she's prompted for a password as usual; using the new one doesn't work. Entering the old one we get the grey progress bar, and after a while a second login-screen appears, at which she then has to enter the new password.  How do we fix this? This kind of 2FA is quite undesirable.
Cheers,
Tink

A: It sounds like the FileVault encrypted drive is allowing the old password (first login) to unlock the drive. But, instead of automatically logging in as the same user, the password reset is causing the second login.
You will need to login to an local admin user and remove the user's ability to decrypt the drive on the command line...
sudo fdesetup remove -user username

Then add the user back in using...
sudo fdesetup add -usertoadd username

Or, with macOS High Sierra, you can use the "Enable Users" button located in System Preferences -> Security -> FileVault.
I do not know if this is normal after a password reset, but you may want to confirm that your password reset procedure is correct.


text:
Q: XCode 8 autolayout preview shows a broken UI while it is working well on phones I'm using XCode 8 and storyboard to make my UI but I am experiencing some strange issues with autolayout.
In fact, I tried something simple : centering a UILabel in my UI :

It looks good here. And to preserve the UI design, I added two constraints, like this :

with another one for the spacing between the UILabel and the "Sign In" button.
And when I build this view in an iPhone 7, iPad etc, it looks pretty good. However, when I switch the phones in the storyboard, the UILabel is moved and it doesn't look good :

So my question is : is there an issue with the preview in XCode 8? Or is it just a normal behaviour?
Thanks!

A: The orange labels in the preview mean that the label is not in its final location. You can force xcode to refresh by clicking the update frames button at the bottom of the screen, next to the constraints tie-fighter icon.


text:
Q: writing audio signal to file using 16 bit per sample (LSB,MSB) in Matlab could you help me with generation audio signal with such a parameters:

*

*sample rate = 8000 Hz,

*mono,

*16-bits per sample.

I need write samples to file without any header, in little-endian representation with sign (LSB,MSB). E.g. if sample has value 32767 (it is maximum in this representation) then it will be saved as 0xFF7F.
This signal should contain couple of tones. I have such a code for generating tones:
 frequency = 2000;
 duration = 2;
 amplitude = 1;
 sampleFreq = 8000;

t = linspace( 0, duration, duration * sampleFreq );
s = amplitude * sin( 2 * pi * frequency * t ) + amplitude * sin( 2 * pi * frequency/2 * t ) + amplitude * sin( 2 * pi * frequency*2 * t );

It creates vector (mono) with 8000 Hz sample rate. But I don't know how to write samples in 16-bits with LSB,MSB convention.
Regards.

A: you can either use wavewrite or audiowrite.
wavwrite(s,filename) writes the data stored in the variable s to a WAVE file called filename. The filename input is a string enclosed in single quotes. The data has a sample rate of 8000 Hz and is assumed to be 16-bit.
If there an endianess issue, you can format the  big-endian output into little-endian  (and vice versa) using the swapbytes function, i.e. s =   swapbytes(s)
you can remove the header using the following SO answer


text:
Q: junit test with mockito using argumentCaptor I am learning to write test cases in junit using mockito. Can anyone please explain how to write junit test using ArgumentCaptor for a method like this ?
public int mtd(A a){
int value=dao.getValues(a);
return value;
}

My junit test case look like this
@RunWith(MockitoJUnitRunner.class)
public class SampleTest {

  @Mock
  private InternDAO internDAO;

  @Mock
  InternServiceImpl service;

  @Before
  public void init() {
    service = new InternServiceImpl();
  }
  @Test
  public void test() throws DataServiceException, BusinessServiceException {

      Intern intern=new Intern();
  intern.setStartDate(new Date());
    intern.setEndDate(new Date());
    Mockito.when(service.doSignedUpCount(intern)).thenReturn(2);
    int val=service.doSignedUpCount(intern);
 Assert.assertEquals(val, 2);

  }

}

It i throwing nullpointer exception

A: First of all Thanks @noscreenname for helping me.
I got NullPointerException cause i didn't set internDAO object value.


text:
Q: How can I parse string using square brackets as a delimiter in Java? I have a class that parses ZonedDateTime objects using.split() to get rid of all the extra information I don't want.
My Question: Is there a way to use square brackets as delimiters that I am missing, OR how do I get the time zone ([US/Mountain]) by itself without using square brackets as delimiters?
I want the String timeZone to look like "US/Mountian" or "[US/Mountian]
What I've Tried:
Ive tried wholeThing.split("[[-T:.]]?) and wholeThing.split("[%[-T:.%]]") but those both give me 00[US/Mountain]
I've also tried wholeThing.split("[\\[-T:.\\]]) and wholeThing.split("[\[-T:.\]") but those just give me errors.
(part of) My Code:
 //We start out with something like   2016-09-28T17:38:38.990-06:00[US/Mountain]

    String[] whatTimeIsIt = wholeThing.split("[[-T:.]]"); //wholeThing is a TimeDateZone object converted to a String
    String year = whatTimeIsIt[0];
    String month = setMonth(whatTimeIsIt[1]);
    String day = whatTimeIsIt[2];
    String hour = setHour(whatTimeIsIt[3]);
    String minute = whatTimeIsIt[4];
    String second = setAmPm(whatTimeIsIt[5],whatTimeIsIt[3]);
    String timeZone = whatTimeIsIt[8];

A: Using split() is the right idea.
String[] timeZoneTemp = wholeThing.split("\\[");
String timeZone = timeZoneTemp[1].substring(0, timeZoneTemp[1].length() - 1);

A: If you want to parse the string yourself, use a regular expression to extract the values.
Don't use a regex to find characters to split on, which is what split() does.
Instead, use a regex with capture groups, compile it using Pattern.compile(), obtain a Matcher on your input text using matcher(), and check it using matches().
If it matches you can get the captured groups using group().
Example regex:
(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d+)[-+]\d{2}:\d{2}\[([^\]]+)\]

In a Java string, you have to escape the \, so here is code showing how it works:
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";

String regex = "(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).(\\d+)[-+]\\d{2}:\\d{2}\\[([^\\]]+)\\]";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
    System.out.println("Year    : " + m.group(1));
    System.out.println("Month   : " + m.group(2));
    System.out.println("Day     : " + m.group(3));
    System.out.println("Hour    : " + m.group(4));
    System.out.println("Minute  : " + m.group(5));
    System.out.println("Second  : " + m.group(6));
    System.out.println("Fraction: " + m.group(7));
    System.out.println("TimeZone: " + m.group(8));
} else {
    System.out.println("** BAD INPUT **");
}

Output
Year    : 2016
Month   : 09
Day     : 28
Hour    : 17
Minute  : 38
Second  : 38
Fraction: 990
TimeZone: US/Mountain

UPDATED
You can of course get all the same values using ZonedDateTime.parse(), which will also ensure that the date is valid, something none of the other solutions will do.
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";

ZonedDateTime zdt = ZonedDateTime.parse(input);
System.out.println("Year    : " + zdt.getYear());
System.out.println("Month   : " + zdt.getMonthValue());
System.out.println("Day     : " + zdt.getDayOfMonth());
System.out.println("Hour    : " + zdt.getHour());
System.out.println("Minute  : " + zdt.getMinute());
System.out.println("Second  : " + zdt.getSecond());
System.out.println("Milli   : " + zdt.getNano() / 1000000);
System.out.println("TimeZone: " + zdt.getZone());

Output
Year    : 2016
Month   : 9
Day     : 28
Hour    : 17
Minute  : 38
Second  : 38
Milli   : 990
TimeZone: US/Mountain


text:
Q: Hook Trait into each Eloquent Select Query I've made a small Trait for filtering an Eloquent Query. Now I want to apply this function in the Trait to each SELECT query before returning instead of calling
$data = MyModel::all()->filterable(),
$data = MyModel::with('foo')->filterable()
etc each time. Is this actually possible?
For example, the nullable package does it by observing
via static::saving(function ($model) { ...
Can this be done for selecting data, too?

A: What you're looking for is called a Global Query Scope.


text:
Q: `jsonwebtoken` - `decode` not readable in `Nodejs` api In my MEAN application, I am validating the username and password. later I am trying to get the user information to display in the web page. But I am not getting the data as readable.
I don't know the issue here and the wrong what i do. any one help me.
my response api is :
apiRoute.get('/me', function(req, res) {
                res.send(req.decoded);
            })

from the req.decoded I am getting the result as :
{
  "data": {
    "iat": 1474893984,
    "exp": 1474937184
  },
  "status": 200,
  "config": {
    "method": "GET",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "cache": true,
    "url": "/api/me",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "x-access-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NzQ4OTM5ODQsImV4cCI6MTQ3NDkzNzE4NH0._Qs2rTaH_oCAZ0c1LOe5oFiUVOZ9jXtpWc0fSykH4Xw"
    }
  },
  "statusText": "OK"
}

In the data, i am not getting the user name, instead of getting some num values.
here is how i am setting the decode when user logs in:
apiRoute.use(function( req, res, next ) {

        var token = req.body.token || req.param('token') || req.headers['x-access-token'];

        if( token ) {

            jwt.verify( token, superSecret, function( err, decoded ) {

                if( err ) {

                    return res.status(403).send({
                        success: false,
                        message: 'Failed to authenticate token.'
                    });

                } else {
                    req.decoded = decoded; //setting the value on login.
                    next();

                }

            })

        } else {

            return res.status(403).send({
                success: false,
                message: 'No token provided.'
            });

        }

    })

UPDATE
As per hpavlino suggession i have updated my code, and I am getting this in console, if any one find the solution let me know:
express deprecated req.param(name): Use req.params, req.body, or req.query instead app\routes\api.js:67:37
token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NzQ5MDAzMDEsImV4cCI6MTQ3NDk4NjcwMX0.8gjrBcX6cD74pix1weqv06qoqw1xFcFHLoR3Mp2fUSE
Access token has expired
GET /api/me 200 19.364 ms - -
GET /app/views/pages/families.html 304 21.319 ms - -
GET /favicon.ico 304 5.999 ms - -

A: I used this method and it decoded right information:
if (token) {
  try {
    var decoded = jwt.decode(token, jwtSecret)
    if (decoded.exp <= Date.now()) {
      console.log("Access token has expired")
      return next()
    }

    console.log(decoded);

  } catch (err) {
    console.log("couldn't decode token: " + err)
    return next()
  }

} else {
  console.log("token not found!")
  return next()
}


text:
Q: UPDATE field from table 1 to table 2 where the field joining them is not unique in table 2 I'm trying to update a column in one table1 ('keyword') with data (from 'data') in table2 where they joined on 'itemid'. 'Itemid' is not unique in table2, however, and I'm stuck on how to get the data from the record that matches the correct 'field' to update table1, as in the tables below:
table1:
|itemid | keywords
-------------------
|   1   |
|   2   |
|   3   |
-------------------

table2:
|itemid | field     | data
---------------------------------------------------------
|   1   | author    | Shakespeare
|   1   | title     | Hamlet
|   1   | topics    | love, loyalty, treason
|   2   | author    | Dickens
|   2   | title     | Christmas Carol
|   2   | topics    | greed, reconciliation
|   3   | author    | Melville
|   3   | title     | Moby-Dick
|   3   | topics    | madness, immortality, sea
---------------------------------------------------------

what I want to achieve is this in table1:
|itemid | keywords
-----------------------------------------
|   1   | love, loyalty, treason
|   2   | greed, reconciliation
|   3   | madness, immortality, sea
-----------------------------------------

What is the right query to accomplish this? I've tried these queries, which don't throw any errors, but they don't update any lines.
UPDATE table1 AS t1, table2 AS t2 SET t1.keywords=t2.data WHERE t1.itemid=t2.itemid AND t2.field='topics'

UPDATE table1 AS t1
    JOIN table2 AS t2
    ON t1.itemid=t2.itemid
SET t1.keywords=t2.data
WHERE t2.field='topics'

UPDATE table1 AS t1, (SELECT itemid, data FROM table2 WHERE field='topics') AS t2 SET t1.keywords=t2.data

I've looked here and found lots of related UPDATE posts, but none seemed to address this issue. I'm sure it's something simple that I'm missing.

A: UPDATE table1 t1, table2 t2
SET t1.keywords = t2.data
WHERE t1.itemid = t2.itemid
  AND t2.field = 'topics'

A: UPDATE table1 AS t1
SET t1.keywords =
    ( SELECT t2.data
      FROM table2 AS t2
      WHERE t1.itemid = t2.itemid
        AND t2.field='topics'
    )


text:
Q: How to I sort this hierarchical list? The problem
I've got an unordered List<Item>, where each Item can point to another Item in the list by a unique ID.
I want to sort the list so that each Item is followed by the Item to which it points.

Initializing the list
public class Item {
    public string ID {get;set;}
    public string nextID {get;set;}
}

void Main()
{

    var items = new List<Item>();

    items.Add(new Item  { ID = "X", nextID = "" });
    items.Add(new Item  { ID = "A", nextID = "D" });
    items.Add(new Item  { ID = "C", nextID = "B" });
    items.Add(new Item  { ID = "E", nextID = "" });
    items.Add(new Item  { ID = "B", nextID = "A" });
    items.Add(new Item  { ID = "D", nextID = "" });

    SortItems(items);

    // should result in Items with IDs in this order: ["X","E","C","B","A","D"]

}

A: Using the topological sort function TSort() from this answer, I wrote the following function to sort to my specifications:
public List<Item> sortItems(List<Item> items) {

    // perform a topological sort
    var sortedItems =
        items.TSort(item => items.Where(o=>item.ID == o.nextID || item.nextID == ""))
        .ToList();

    // this next code moves the unpointed items to top of list

    // find items that are not pointed to, and do not point to any other item
    var soloItems=
        sortedItems.Where(o => !sortedItems.Where(p => p.nextID == o.ID).Any() && o.nextID == "").ToList();

    // reverse the soloItems list so they
    // to appear in the same order in which
    // they were found in unsorted list
    soloItems.Reverse();

    // move the soloItems from the bottom of sortedItems to the top of sortedItems
    sortedItems.RemoveAll(o => soloItems.Contains(o));
    sortedItems.InsertRange(0,soloItems);

    return sortedItems;

}

A: Interesting problem. At first I wondered if it would be possible using a simple Linq query construction with some selector delegates, but that gets messy quite quickly.
The below simple linq construction gets you part of the way, but really requires use and propagation of counts and original input order as well.
// Simple Linq, but just not good enough
// Need to also propagate original input order and count the number of siblings
Func<IEnumerable<Item>, Item, IEnumerable<Item>> SelectSuccessors = (set, item) => set.Where(i => i.ID == item.nextID);
Func<IEnumerable<Item>, IEnumerable<Item>, IEnumerable<Item>> Flatten = null;
Flatten = (set, sibblingPool) => set
    .SelectMany(i => new[] { i }.Concat(Flatten(SelectSuccessors(sibblingPool.Except(set), i), sibblingPool.Except(set))));
var unparented = items.Where(i => !items.Any(n => n.nextID == i.ID));
foreach (var item in Flatten(unparented, items))
    Console.WriteLine(item.ID);

Its result is ["X", "C", "B", "A", "D", "E"]
A very different type of construction is to really capture the recursive structure of this problem, in a self recursive data structure:
public class ItemHierarchy : Tuple<Item, int, List<ItemHierarchy>>
{
    public static List<ItemHierarchy> BuildHierarchy(IEnumerable<Item> items)
    {
        var inputOrderNumbered = items.Select((item, order) => Tuple.Create(item, order));
        var roots = inputOrderNumbered.Where(i => !items.Any(n => n.nextID == i.Item1.ID));
        return roots.Select(r => BuildFor(r.Item1, r.Item2, inputOrderNumbered.Except(roots))).ToList();
    }

    public Item Item
    {
        get { return this.Item1; }
    }
    public int OriginalInputOrder
    {
        get { return this.Item2; }
    }
    public int NumberOfDescendents
    {
        get { return this.Item3.Count + this.Item3.Sum(i => i.NumberOfDescendents); }
    }
    public IEnumerable<Item> Flattened
    {
        get { return new[] { this.Item }.Concat(Descendents); }
    }
    public List<ItemHierarchy> DescendentHierarchy
    {
        get { return this.Item3; }
    }
    public IEnumerable<Item> Descendents
    {
        get { return this.Item3.SelectMany(i => new [] { i.Item }.Concat(i.Descendents)); }
    }
    public IEnumerable<Item> Leafs
    {
        get
        {
            if (NumberOfDescendents == 0)
                return new[] { this.Item };
            else
                return DescendentHierarchy.SelectMany(d => d.Leafs);
        }
    }
    protected ItemHierarchy(Item item, int originalOrder, IEnumerable<Tuple<Item, int>> descendents, IEnumerable<Tuple<Item, int>> remaining)
        : base(item, originalOrder, descendents.Select(d => BuildFor(d.Item1, d.Item2, remaining)).ToList())
    {
    }

    private static ItemHierarchy BuildFor(Item item, int originalOrder, IEnumerable<Tuple<Item, int>> numberedSiblings)
    {
        var descendents = numberedSiblings.Where(s => s.Item1.ID == item.nextID);
        return new ItemHierarchy(item, originalOrder, descendents, numberedSiblings.Except(descendents));
    }
}

Which can then be used to solve the problem you posed as:
// This works quite well.
// As a bonus it preserves the original input information
// and offers a navigatable/queryable hierarchy.
var hierarchy = ItemHierarchy.BuildHierarchy(items);
foreach (var item in hierarchy.OrderBy(r => r.NumberOfDescendents).ThenBy(r => r.OriginalInputOrder).SelectMany(r => r.Flattened))
    Console.WriteLine(item.ID);


text:
Q: how to offset a rotation contained in a unit quaternion rotation from the origin of a rigid object. I'm using Unity3D for a project. The way it handles sorting transformations is with a 3vector-unit quaternion-3vector "sandwich" (the 1st vector for position, the quaternion for rotation, and the 2nd vector for uniform axis scale). When you add a rotation to a transform it rotates the object around the origin of the mesh (usually the center of the object), my question is, is there a way to rotate an object around an "offset" from the object's center mathematically?
is short move the rotation itself to a new position, and still influence the object? (see figure for clarity)

A: In 3d you can rotate around an arbitrary axis, shifted from the origin, by translating the object, then rotating and then translate back.
Translation is used to shift the rotation from the origin. You can use the coordinates of the new "center of rotation" to be the tranlation vector.
Suppose you have a function $Q : R^3 \rightarrow R^3$ that rotates a 3d vector using quaternions.
$$v' = Q(v - c) + c$$
Where $c$ is the new center of rotation, $v$ is the vector you want to rotate around $c$ and $v'$ is the rotated vector.
You can also put the above in matrix notation:
$$M = T_c R T_c^{-1}$$
Where the matrix $M$ is the shifted rotation matrix, $T_c$ is a translation matrix and $R$ is a rotation matrix derived from a quaternion. All matrices are $4 \times 4$. Here I assume your vectors are expressed in homogeneous coordinates. So you can apply $M$ to a homogeneous vector $v$ as:
$$v' = M v$$
You can even mix matrix and quaternions like:
$$v' = T_c Q(T_c^{-1} v)$$
Here we are assuming that $Q : R^4 \rightarrow R^4$ i.e., $Q$ is rotating homogeneous vectors.


text:
Q: Scaling laws for singular values of random matrices Assume that we have an $n\times n$ matrix ${\bf A}$ with elements drawn i.i.d. Gaussian with mean zero and variance 1.
Are there any results on the asymptotic behavior of its $i$-th largest singular value?
I am mostly interested when $i=\sqrt{n}$ or $i=n/\log(n)$, or in general when $i$ is some increasing function of $n$.

A: Yes, see Roman Vershynin's notes.


text:
Q: Applications of higher order reciprocity laws I'm currently studying quartic & cubic residues and their reciprocity laws, and would like to know of any real world applications to finding the values of their respective residue symbols.
I know that applications of quadratic residues are in cryptography, primality testing, and graph theory. However I have yet to find an application of quartic/cubic residues and specifically using their reciprocity theorems.


text:
Q: iOS - Limit Pinch to Zoom using CGAfineTransform I'm trying to set a max and a min limit to the zooming when I use the pinch to zoom gesture
CGAffineTransform transform = CGAffineTransformMakeScale(recognizer.scale, recognizer.scale);
NSLog(@"Pinch scale: %f", recognizer.scale);
float scale = recognizer.scale;
float SCALE_MIN = 1.0f;
float SCALE_MAX = 3.0f;

if (SCALE_MIN < scale < SCALE_MAX) {
    self.view.transform = transform;
}

else {

}

The logic behind this, was that it would only zoom if the condition was satisfied
but this just zooms endlessly.

A: C is not Python. The < operator is binary and left-associative, so
SCALE_MIN < scale < SCALE_MAX

is parsed as
(SCALE_MIN < scale) < SCALE_MAX

The left hand side is either 1 or 0 (true or false), which is always smaller than SCALE_MAX (which is 3). So your condition is always true. (Did you not get a compiler warning regarding that?)
Hint: you need to use the logical AND (&&) operator to combine the two conditions.


text:
Q: Definition of custom coordinate system with Equator rotation? I need to define cylindrical coordinate system in ArcGIS Desktop with numeric equator rotation. Pictures below show how Equator is rotated.
Coordinates of points 1 and 2 are known.
Is there a way to do it in ArcGIS Desktop?


text: Q: How to set up a shared team calendar in Sharepoint 365 that updates individual calendars when an event is cancelled or moved I have a team site and I've added the calendar.  I've synced the team site's calendar with my calendar in outlook.  I now have both calendars up side by side in my Outlook, which is great.  I am able to create and copy events on both calendars with no issues.  The problem I'm having is when the event is moved or cancelled.  If I cancel or delete an event on the team site, the version in my personal calendar does not show as canceled or deleted.  If I move the event on my team site, the item does not move on my personal calendar and vice versa.  How do I make this work?


text:
Q: Trying to write a function that takes a cardinal direction and coords, returns new coordinates I'm currently trying to write a function that takes a str of north, east, south, and/or west and then a starting location for both an x and y coordinate on a grid.
I'm currently trying to figure out how I could take a string that, for example, reads "EWNeWn" and can separate it so a program can interpret it to follow directions.
If the direction is "N", the y-coord increases by 1. "E" increases the x-coord by 1. "S" decreases the y-coord by 1. and W decreases the x-coord by 1.
It's supposed to be returned as a tuple.
I thought I was on the right track at first but I'm not really sure anymore, I'm quite new to this.
Any help??
Here's my code:
def movement(string, x, y):
if (string == 'N', 'n'):
    y += 1
    return (x, y)
elif (string == 'E', 'e'):
    x += 1
    return (x, y)
elif (string == 'S', 's'):
    y -= 1
    return (x, y)
elif (string == 'W', 'w'):
    x -= 1
    return (x, y)

A: Something like (string == 'N', 'n') wouldn't work. That would make a tuple of the first element being True or False (the condition is string == 'N'), and the second element would be simply 'n'.
As OP mentioned in the comments, try this:
def movement(string, x, y):
    for char in string:
        if char.lower() == 'n':
            y += 1
        elif char.lower() == 'e':
            x += 1
        elif char.lower() == 's':
            y -= 1
        elif char.lower() == 'w':
            x -= 1
    return (x, y)
print(movement('abcdefghijklmnopqrstuvwxyz', 0, 0))


text:
Q: Encoding with requests in python Came across a strange issue.
I am passing a dictionary as part of a POST request to a cgi script:
self.settings = {
    'SubmitCommands': ['C:\Python27\python.exe path\my_script.py']
}

Here is my code:
    settings = self.settings

    # Make web call to CGI script
    user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent' : user_agent, "Accept": "text/plain"}
    response = requests.post(
            "path\CGI\cgi_script.py",
            headers=headers, data=settings)

And here is the resulting traceback:
Traceback (most recent call last):
  File "path\CGI\cgi_script.py", line 119, in initi
alizeJob
    self.submitCommands = eval(inputSubmitCommands)
  File "<string>", line 1
    C:\Python27\python.exe path\my_script.py
     ^
SyntaxError: invalid syntax

However, if I do this the old fashioned way I do not get the traceback:
    settings = self.settings

    # Set and encode parameters
    params = urllib.urlencode(settings)

    # Make web call to CGI script
    user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent' : user_agent,
                "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"}
    conn = httplib.HTTPConnection(self.host)
    conn.request("POST", "path/CGI/cgi_script.py", params, headers)
    response = conn.getresponse()

Earlier today someone warned me on Stack Overflow for picking a library just because it is new.  Looks like I should have listened to them.   However, I am still curious about what went wrong.

A: Python is interpreting your backslashes as escape codes. Just double them up to fix that.
self.settings = {
    'SubmitCommands': ['C:\\Python27\\python.exe path\\my_script.py']
}


text:
Q: Looking for ways to retrieve emails and display it in an HTML inbox page I'm trying to retrieve emails via a python script. I was looking to see if there's a way to retrieve them and display into an HTML inbox page. I know that I could just log onto my email and see my inbox, but I still want to see if I can retrieve my emails and render it in readable form.

A: Assuming you're trying to retrieve your Gmail inbox, Google's Gmail API is perfect for that use case.
First of all, here's the setup instructions for Python:
https://developers.google.com/gmail/api/quickstart/python
Once you've got your Gmail project set up (including signing up and getting an API key), you can retrieve an inbox from the Users.messages data. The example Gmail uses in the first link (quickstart) retrieves Users.labels, so it should be a pretty basic modification to retrieve Users.messages using the same syntax.
Alternatively, Gmail has a REST API which you could use to easily retrieve JSON data using a simple HTTP request. See here:
https://developers.google.com/gmail/api/v1/reference/
Note: if you're going the HTTP request route, then you might as well use JQuery (Javascript library) to execute an HTTP request using the $.get() and/or $.post() methods.


text:
Q: Invalid Block Tag, Expected 'endblock' I know this issue is all over stackoverflow, but this particular instance of it has me lost. The reason is, I get this error periodically - without changing the HTML file at all.
The issue seems to be here:
{% extends "base.html" %}
{% load static %}
{% load support_tags %}

{% block content_header %}

Header

{% endblock content_header %}

{% block new-main-area %}
        {% ticket_categories as categories %} {# Problem is here #}
            <option value="None">Select a Category</option>
        {% for cat in categories %}
            <option value="{{cat.slug}}">{{cat}}</option>
        {% endfor %}
{% endblock new-main-area %}

{% block extrascripts_bottom %}
{% endblock extrascripts_bottom %}

Thank you!

A: IMHO, the code is misusing with tag:
Replace following lines:
{% ticket_categories as categories %}
    <option value="None">Select a Category</option>
{% for cat in categories %}
    <option value="{{cat.slug}}">{{cat}}</option>
{% endfor %}

with:
{% with ticket_categories as categories %}
    <option value="None">Select a Category</option>
{% for cat in categories %}
    <option value="{{cat.slug}}">{{cat}}</option>
{% endfor %}
{% endwith %}

Or (with is not necessary at all):
<option value="None">Select a Category</option>
{% for cat in ticket_categories %}
    <option value="{{cat.slug}}">{{cat}}</option>
{% endfor %}


text:
Q: Efficiency on array iteration Consider a 2-d array n by n of the form
array1 ={ {x11,x12,x13,...,x1n},{x21,x22,x23,...,x2n},{xn1,xn2,xn3,...,xnn}}.
I want to expand every point in this array in terms of a 2-d Gaussian distribution.
The first step is to create an array which contains the normalization factors for the Gaussian distribution. This results is also a 2d array of the same form as the previous one this we'll name array2.
With the two arrays formed the main idea is to iterate through array1 and for each element[x,y] in array1 we sum over the multiple of element[x,y] and element[i,j] in array2.
Below is my attempt, which works but its very slow due to the use of loops.
GaussianArray[set1_, set2_] := Module[{
    n = Dimensions[set1][[1]],
    k = Dimensions[set2][[1]],
    i, j, l, m, x, y, t, res
    },
   res = ConstantArray[0, {n, n}];
   t = Ceiling[k/2];
   Do[
    Do[
      If[x + l - t == 0, i = Mod[x + l - t, n] + n,
       i = Mod[x + l - t, n]];
      If[y + m - t == 0, j = Mod[y + m - t, n] + n,
       j = Mod[y + m - t, n]];
      If[0 == i, i = x + l - t, i];
      If[0 == j, j = y + m - t, j];
      res[[x, y]] = res[[x, y]] + set1[[i, j]]*set2[[l, m]];
      , {l, 1, k}, {m, 1, k}];
    , {x, 1, n}, {y, 1, n}];
   res
   ];

There are some conditional statements required in order to deal with boundaries and to ensure that the correct multiplication is performed. This approach does give the desired result but as previously mentioned is dreadfully slow. I look forward to hearing ideas on how to improve this code.
As per some comment suggestions here is a more concrete example.
Let
array1 = {{a11, a12, a13, a14, a15}, {a21, a22, a23, a24, a25}, {a31, a32, a33, a34, a35}, {a41, a42, a43, a44, a45}, {a51, a52, a53, a54, a55}}
and
array2 = {{a, b, c}, {d, e, f}, {h, i, j}};
using my suggested solution we can look at the first element of
GaussianArray[array1,arra2]
which is
a51 b + a52 c + a15 d + a11 e + a12 f + a25 h + a21 i + a22 j + a a55
This approach is extremely slow. Below are two plot of the timing for different sizes of the arrays.

A: As suggested by @lericr in the comments. ListCorrelate[] solves the timing issue. The code above can be changed to
GaussianArrayUpdate[set1_, set2_] := Module[{
    n = Dimensions[set1][[1]],
    k = Dimensions[set2][[1]],
    t, res
    },
   t = Ceiling[k/2];
   res = ListCorrelate[set2, set1, {t, t}];
   ];

This produces the same output as my original suggestion but works extremely fast. The picture below show timing for GaussianArrayUpdate.Blue denotes the timing for array1 set at a constant 200x200 and array2 with a varied size. Red denotes the timing for array2 set at a constant 3x3 and array1 with a varied size.


text:
Q: Form for editing a page doesn't work in Django (CS50 Project) I am creating a Wikipedia like web app in django and one of the features is that the user is able to edit a page. I have tried to code this, however it doesn't seem to work. I have spent hours trying to figure out the problem and I am unable to fix it. When I enter data into the form, it isn't getting saved onto the file. I press the edit page link, it takes me to editpage.html (which is /wiki/pageName/editpage) and I can type in different data, but when I press the save button, nothing is saved and when I look at the actual file on the disk, it is still the original and none of the edits have been saved.
my views.py editpage function:
def editpage(request, title):
if request.method == 'post':
    form = editPageForm(request.POST)
    if form.is_valid():
        pageTitle = form.cleaned_data['title'].capitalize()
        pageContent = form.cleaned_data['content']
        util.save_entry(pageTitle, pageContent)
        return HttpResponseRedirect(f'/wiki/{pageTitle}')
else:
    return render(request, 'encyclopedia/editpage.html', {
        'title': title,
        'content': util.get_entry(title)
    })

my urls.py:
from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path('<str:title>/editpage', views.editpage, name='editpage'),
    path('newpage', views.newpage, name='newpage'),
    path(f'<str:title>', views.display, name='display')
]

the editpage.html website:
{% extends "encyclopedia/layout.html" %}

{% block title %}
    Editing: {{ title }} page
{% endblock %}

{% block body %}

Editing {{title}}.md

    <form action='/wiki/{{title}}' method='POST'>
        {% csrf_token %}
        <input type='text' placeholder='Title' name='title' value={{title}}>

        Content (.md format):

        <textarea name='content' id='content'>{{content}}</textarea>
        <input type='submit' value='Save'>
    </form>
{% endblock %}

util.save_entry function code:
def save_entry(title, content):
"""
Saves an encyclopedia entry, given its title and Markdown
content. If an existing entry with the same title already exists,
it is replaced.
"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
    default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))

A: I think it has to be request.method == 'POST'. And I think you should implement the logic with the case form.is_valid() return False, too. Go ahead, mate ^^


text:
Q: How can I add an event listener to a form when it's loaded as part of a partial page? I have the following page:
<!doctype html>

    @RenderSection("Content")

        Authenticating ...

and this partial page:
@{ Layout = "~/Views/Account/Layout.cshtml"; }
@section content {
   <form action="/Account/Login" class="form" method="post">
      <button type="submit" class="glossy">Login</button>
   </form>
}

I want the loading-mask div to become visible when the submit is pressed. However this does not seem to happen. Could this be because my partial is not yet loaded? Can anyone give me some advice how I could make this work?

A: Try using
document.getElementsByClassName('form')[0]

instead of
document.getElementsByClassName('form')

That's because getElementsByClassName returns a HTMLCollection object instead of an Element one, like document.getElementById does.


text:
Q: How to get the objects from a request url module function to another function So, i was working in on multi API project where ,there's one part where one had to enter the address , for where you want to get the weather outputs, and i am stuck in a part where i can take the API values of long. and lat. converted out of a address string and pass it to a API for weather outputs.as i can't access the API output of one to another.
The request url is like this:
request({url:url,json:true}, (error,response) => {
   console.log(response.body.current.weather_descriptions[0] +' The temperature is '+chalk.inverse(response.body.current.temperature)+' but it feels like '+ chalk.inverse(response.body.current.feelslike))
})

A: ok, i found an answer using call back function, i have answered below the code.

const geoCode = (geoUrl, callback) => {
    request({url:geoUrl,json:true}, (error,response) => {
        if(error)
        {
            console.log('Unable to connect to the server.....')
        }
        else{
    callback(undefined,{
        latitude:response.body.data[0].latitude,
        longitude:response.body.data[0].longitude
    })
}

        })
}

geoCode(geoUrl,(error,data) =>
{
    var url = 'youur api'
    url = url+data.latitude+","+data.longitude
// console.log(url)

    request({url:url,json:true}, (error,response) => {

        if(error)
        {
            console.log('Unable to connect to the server.....')
        }
        else{
            console.log(response.body.current.weather_descriptions[0] +' The temperature is '+chalk.inverse(response.body.current.temperature)+' but it feels like '+ chalk.inverse(response.body.current.feelslike))
}

        })
})


text:
Q: execute Generated password to Database I want to send a hashed data to the database.thats my data:
0MPA00JQ'Q:0TGF6T?>TE)pRc1.kA<<\I<b3@ZaR<BXq].k#1A6mm"`>:s_c<+RjO:,Y$i2`Y;E

But because the data has a lot of symbols, I encounter the following error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'0MPA00JQ'Q:0TGF6T?>TE)pRc1.kA<<\I<b3@ZaR<BXq].k#1A6mm">:s_c<+RjO:,Y$i2Y;E"",
"' at line 1

I tried many methods but none of them worked with the same error! Methods I used:
sql = """INSERT INTO {}(disc, data) VALUES (""{}"", ""{}"")""".format(tb,hash_for_data(disc),hash_for_data(data))

sql = """INSERT INTO %s(disc, data) VALUES (""%s"", ""%s"")""" % (TABLE, HASHED_DATA_1, HASHED_DATA_2)

And a few other methods

A: The only way it worked was to finally hash the hash data:
base64.b16encode(HASHED DATA)

In this way the output is equal to the digit without the symbol


text:
Q: Prop passed to child component is undefined in created method I am using Vue.js 2.
I have a problem with passing value to the child component as a prop. I am trying to pass card to card-component.
In card-component I can access the prop in the Card goes here {{card}} section.
However when I try to access it in created or mounted methods it's undefined.
Parent:
<template>

                <card-component :card="place.card"></card-component>

</template>

Child:
<template>

                    Card goes here {{card}}

</template>

I did a lot of googling but none of the solutions I found have fixed my issue.

A: This is purely a timing issue. Here's what happens...

*

*Your parent component is created. At this time it has an empty array assigned to place (this is also a problem but I'll get to that later). An async request is started

*Your parent component creates a CardComponent instance via its template
<card-component :card="place.card"></card-component>

at this stage, place is still an empty array, therefore place.card is undefined
3. The CardComponent created hook runs, logging undefined
4. The CardComponent is mounted and its mounted hook runs (same logging result as created)
5. Your parent component is mounted
6. At some point after this, the async request resolves and changes place from an empty array to an object, presumably with a card property.
7. The new card property is passed down into your CardComponent and it reactively updates the displayed {{ card }} value in its template.
If you want to catch when the card prop data changes, you can use the beforeUpdate hook
beforeUpdate () {
  console.log(this.card)
}

Demo

Vue.component('CardComponent', {
  template: '
card = {{ card }}
',
  props: ['card'],
  created () {
    console.log('created:', this.card)
  },
  mounted () {
    console.log('mounted:', this.card)
  },
  beforeUpdate () {
    console.log('beforeUpdate:', this.card)
  }
})
new Vue({
  el: '#app',
  data: {
    place: {}
  },
  created () {
    setTimeout(() => {
      this.place = { card: 'Ace of Spades' }
    }, 2000)
  }
})

  <card-component :card="place.card" />

See https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

If place is meant to be an object, you should not be initialising it as an array. Also, if your CardComponent relies on data being present, you may want to conditionally render it.
For example
data () {
  return { place: null }
}

and
<card-component v-if="place" :card="place.card"></card-component>

then CardComponent will only be created and mounted after place has data.

A: Make sure you have props: true in the router file. It is a simple solution but many of us forget this.
{
  path: '/path-to',
  name: 'Name To',
  component: Component,
  props: true
}


text:
Q: Vaadin Flow: Grid Select All is ignoring Filtering Vaadin Framework Version:
23.1.7
Issue
I'm building up a web application using Vaadin. In the view I added a Grid and set
grid.setSelectionMode(Grid.SelectionMode.MULTI);

I also added a FilterField, that filters the GridListDataView.
The Multiselect and the filter working fine, each for it's own. But when I try to Filter the grid, then click the "Select All" Checkbox in the header column all rows in the grid are selected (also those, which are currently not visible, because of the filter.
In fact, it's exactly the issue mentioned here: https://github.com/vaadin/framework/issues/10595 , which should have been fixed by vaadin 8.9.0, but I'm still/again facing this issue.
Question
Is there any known way to work around that and get only those items selected that are currently visible?


text:
Q: How to load Cipher encrypted image file in ImageView without saving to device I am creating an application with content security for no one could ever copy the contents and files. I am using cipher to encrypt the image directly from the URL, with out downloading to the device.
Please find my code below.
URL url = new URL(images.getImageurl());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
File folder = new File(Environment.getExternalStorageDirectory(), "zerb");
boolean success = true;

if (!folder.exists()){
folder.mkdirs();
}
InputStream fis = connection.getInputStream();
String path = folder.getAbsolutePath() + "images.getImageName + ".jpg";
encryptfile(fis, path, AppConstants.password + images.getContentid() + images.getTopicid())
fis.close();

And the cipher encryption Method code is
private static boolean encryptfile(InputStream inputStream, String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    FileOutputStream fos = new FileOutputStream(path.concat(".crypt"));
    byte[] key = (AppConstants.salt + password).getBytes("UTF-8");
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16);
    SecretKeySpec sks = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    int b;
    byte[] d = new byte[8];
    while ((b = inputStream.read(d)) != -1) {
        cos.write(d, 0, b);
    }
    cos.flush();
    cos.close();
    inputStream.close();
    File encryptedFile = new File(path.concat(".crypt"));
    return (encryptedFile.exists());
}

and the decryption code is
 public static void decrypt(String path, String password, String outPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    FileInputStream fis = new FileInputStream(path);
    FileOutputStream fos = new FileOutputStream(outPath);
    byte[] key = (AppConstants.salt + password).getBytes("UTF-8");
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16);
    SecretKeySpec sks = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    int b;
    byte[] d = new byte[8];
    while ((b = cis.read(d)) != -1) {
        fos.write(d, 0, b);
    }
    fos.flush();
    fos.close();
    cis.close();
}

If I decrypt the image, it will be shown and can be copied from the device.
All I need is to load the encrypted image to an ImageView without saving the decrypted image to the device, so that no one can copy. Please someone help me.

A: An ImageView can show an in-memory android.graphics.Bitmap which can be read in directly from an InputStream.
For example, the decrypt() method could be adapted to return a Bitmap :
public Bitmap decrypt(String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    FileInputStream fis = new FileInputStream(path);
    byte[] key = (AppConstants.salt + password).getBytes("UTF-8");
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16);
    SecretKeySpec sks = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);
    CipherInputStream cis = new CipherInputStream(fis, cipher);

    Bitmap bitmap = BitmapFactory.decodeStream(cis);
    cis.close();

    return bitmap;
}

(Although it's called Bitmap, it's fine to decode a .jpg or .png).
Then this can be shown in the ImageView:
ImageView imageView = findViewById(R.id.imageView);
Bitmap bitmap = decrypt(path + ".crypt", password);
imageView.setImageBitmap(bitmap);


text:
Q: Unable to read registry during installation of winform app on win server 2003 I am working on a win form based application in c#. When being deployed it writes its install location in registry. Now there is a separate plugin which during deployment looks for this value in registry.
Now the problem I am having is that it is working perfectly on my 32-bit win 7 dev box. But on client's 64-bit win 2003 server, the host application is able to write registry value but the plugin is getting empty string from registry. One problem could be that it is unable to find the registry on a server box.
Any ideas what could be the issue and how can I resolve it?

A: On 32 Bit the registry key will be something like:
HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany

On 64 Bit the registry key will be something like:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyCompany

I'm guessing the plugin may need updating / configuring (depending on how you use it) to support 64 Bit.

A: 64-bit versions of Windows emulate 32-bit functionality through the "Windows on Windows" (WoW) subsystem. In the case of the registry, they move the 32-bit keys over to a special subkey for compatibility reasons.
The keys for 32-bit software on a 64-bit OS will be in: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node.
This is the registry analogue of the file system redirector that maps system32 to SysWOW64.
More details can be found on the MSDN topic about the Registry Redirector.


text:
Q: would it be use to or used to? Jasmine use to take  piano lessons, but now she is learning to play the trombone.
Jasmine used to take  piano lessons, but now she is learning to play the trombone

A:
used to

You are describing a past state, hence use of the past tense, used. If "use to" is found, or heard, it is most likely because the -d got lost in the following t-.