text:
Q: How to select only last matching result if this is equal to x from mysql table i've three tables in my mysql database:
orders table (example):
orders
id  | user_id | price
1   | 10       | 29.99
2   | 20       | 29.99
3   | 30       | 29.99
4   | 40       | 29.99

users table:
users
id   | name   | surname
10   | mark   | white
20   | john   | long
30   | anders | red
40   | john   | smith

and orders_updates table
orders_updates
id | order_id | status_id | date
1  | 1        | 1         | 03/05/2020
2  | 1        | 2         | 04/05/2020
3  | 2        | 1         | 05/05/2020
4  | 3        | 1         | 06/05/2020
5  | 4        | 1         | 06/05/2020
6  | 4        | 2         | 06/05/2020

What i need:
new orders
order_id | user_id | name   | surname
2        | 20      | john   | long
3        | 30      | anders | red

Now, i need to create the "new orders" page (orders_updates.status_id = 1), how i can get only orders with only status_id=1 and not some other status_id.
This is where i'm stuck:
SELECT o.*, u.*
FROM orders o, users u, orders_updates ou
WHERE o.user_id = u.id
AND (SELECT MAX(ID) FROM order_updates WHERE order_updates.order_id = o.id)
AND ou.order_id = o.id

Thank you all.

A: Try the following
select
    order_id,
    user_id,
    name,
    surname

from orders_updates ou

join orders o
on ou.order_id = o.id

join users u
on u.id = o.user_id

where ou.status_id = 1

order by
    order_id

A: I would go with:
select
    order_id,
    user_id,
    name,
    surname

from orders_updates ou

join orders o
on ou.order_id = o.id

join users u
on u.id = o.user_id

where ou.status_id = 1
and ou.order_id not in (
  select distinct order_id
  from orders_updates
  where status_id in (2,3)
)

order by
    order_id

I put as a sample status_id in (2,3) but you should include there all the other status_ids you don't want to be considered.
Hope that helps!


text:
Q: React - Map inside a map function I'm looking to create a simple multiplication table using React. I've got the following code where I'm trying to loop through an array.
{array.map((num) => {
  return (

      {num}

      {array.map((x) => {
        return {x}	;
      })}

  );
})}

I'm getting the error 'num.map is not a function'
I understand that num is not a function, but I wanted to check if there is a way I could basically create a nested loop? If not, my alternative would be to convert a string to JSX, but I wanted to check whether there's a way I could achieve this with map first.

A: You can use Array.from() to create a range of numbers, iterate them, and produce react nodes:

const renderRange = (start, end, cb) => Array.from(
  { length: end - start + 1 },
  (_, i) => cb(i + start)
)

const Demo = () => (

      {renderRange(1, 10, x => (

          {renderRange(1, 10, y => (

              {x * y}

          ))}

      ))}

)

ReactDOM.render(
  <Demo />,
  root
)
td {
  border: 1px solid black;
  padding: 2px;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: eval after exec: seemingly same strings do not provide the same result (may be encoding problem) I defined the _exec_ function for getting the output of a function represented by a string.
For instance the sgn function evaluated with the arg value (see code below).
Then I will have to perform a single eval in the end.
(Warning: exec or eval of unknown code must be secured before use.)
def _exec_(thecode):
    local = {}
    exec(thecode, globals(), local)
    return local["_output_"]

sgn = "\nif _input_[0]<0:\n    _output_ = -1\nif _input_[0]==0:\n    _output_ = 0\nif _input_[0]>0:\n    _output_ = 1"
arg = "[5]"

code_list = ["_input_ = "+arg+sgn]
print(eval("1+_exec_(code_list[0])"))

The last 2 lines provide the good result.
However I will have to use it for an undetermined number of times with various "string-functions" and "string-arguments".
Is it possible to do it with only 1 named string instead of a list of strings?
I tried:
code = "1+_exec_(_input_ = "+arg+sgn+")"
print(eval(code))

which lead to SyntaxError: invalid syntax.
Maybe the encoding of special characters is wrong, then I tried:
code = "1+_exec_(_input_ = "+arg+sgn.encode('unicode-escape').decode()+")"
print(eval(code))

which lead to SyntaxError: unexpected character after line continuation character.
I also tried to use the answer to Python: exec() a code block and eval() the last line, without success.

A: They aren't the same strings, "seemingly" or otherwise. Just take the eval out of both print(eval(...)) calls and compare:
>>> print("1+_exec_(code_list[0])")
1+_exec_(code_list[0])

vs:
>>> code = "1+_exec_(_input_ = "+arg+sgn+")"
>>> print(code)
1+_exec_(_input_ = [5]
if _input_[0]<0:
    _output_ = -1
if _input_[0]==0:
    _output_ = 0
if _input_[0]>0:
    _output_ = 1)

That latter one doesn't look anything like something that might be expected to be valid syntax.


text:
Q: couldn't style react components with external css My react file isn't picking up my external styles.css
index.js :
import React from "react";
import ReactDOM from "react-dom";
import "./css/styles.css";

ReactDOM.render(

 Hello world

,
  document.getElementById("root")
);

styles.css:
.App {
  font-family: sans-serif;
  text-align: center;
}

.upper-deck {
  font-size: "90px";
}

Project folder format :

A: Don't use quotes for scaler values in CSS. Remove the quotes around the pixel value for the font size.
.upper-deck {
  font-size: 90px;
}


text:
Q: scrape image and title from https://www.open2study.com/courses using python and beatifulsoup from bs4 import BeautifulSoup
import urllib

r = urllib.urlopen('https://www.open2study.com/courses').read()

soup = BeautifulSoup(r)
links = soup.find('figure').find_all('img', src=True)

for link in links:
    txt = open('test.txt' , "w")
    link = link["src"].split("src=")[-1]
    download_img = urllib.urlopen('https://www.open2study.com/courses')
    txt.write(download_img.read())
    txt.close()

I need to scrape image and title from this website.

A: Instead of doing a split you can grab the src directly with beautifulsoup
Use this to get the div that has the title and image in it
for link in soup.find_all("div",attrs={"class" : "courses_adblock_start"}):

Then use this to grab the title and image in each div:
    link.find("h2",attrs={"class":"adblock_course_title"}).get_text())
    link.find("img", attrs={"class":"image-style-course-logo-subjects-block"}).get("src"))

You also open the page every time in the loop which you want to avoid, you only need to open it once and then use it for the loop like so:
url = "http://www.open2study.com/courses"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read())

for link in soup.find_all("div",attrs={"class" : "courses_adblock_start"}):
    try:
        print("Title : " + link.find("h2",attrs={"class":"adblock_course_title"}).get_text())
        print("Image : " + link.find("img", attrs={"class":"image-style-course-logo-subjects-block"}).get("src"))
    except:
        print("error")

Here is the new output:
Title : World Music
Image : https://www.open2study.com/sites/default/files/styles/course_logo_subjects_block/public/Course%20Tile_world_music.jpg?itok=CG6pvXHp
Title : Writing for the Web
Image : https://www.open2study.com/sites/default/files/styles/course_logo_subjects_block/public/3_writing_for_web_C_0.jpg?itok=exQApr-1

A: Something like this?
import urllib
from bs4 import BeautifulSoup

titles = []
images = []

r = urllib.urlopen('https://www.open2study.com/courses').read()
soup = BeautifulSoup(r)

for i in soup.find_all('div', {'class': "courses_adblock_rollover"}):
    titles.append(i.h2.text)

for i in soup.find_all(
    'img', {
        'class': "image-style-course-logo-subjects-block"}):
    images.append(i.get('src'))

with open('test.txt', "w") as f:
    for i in zip(titles, images):
        f.write(i[0].encode('ascii', 'ignore') +
                '\n'+i[1].encode('ascii', 'ignore') +
                '\n\n')


text:
Q: How to save and retrieve variables upon screen rotation? Can someone kindly give me a solution to this and explain how he/she came to that particular solution?
Thanks so much
1) Upon rotation of the GUI from portrait to landscape or the opposite disappears all local variables.Write content of the class, where it is marked with To-Do, so that variable isGameFinished taken care of by rotation and collected again when the app is rotated
Class
public class StatteActivity extends Activity{

private boolean isGameFinished;
private Button buttonFinishGame;

protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_state);

//Get previous state for isGameFinished if it exists
//TO-DO

//Find button
buttonFinishGame = (Button) findViewByID(R.id.buttonFinishGame);
buttonFinishGame.setOnClickListener(new OnClickListener(){
public void onClick(View v){
isGameFinished = true;
}
});

if(isGameFinished){
finish();
}
}

protected void onSaveInstanceState(Bundle outState){
//To-Do
super.onSaveInstanceState(outState);
}
}

A: Do it like this:
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    // Saving variables
    savedInstanceState.putBoolean("isGameFinished", isGameFinished);

    // Call at the end
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
    // Call at the start
    super.onRestoreInstanceState(savedInstanceState);

    // Retrieve variables
    isGameFinished = savedInstanceState.getBoolean("isGameFinished");
}

Cheers.


text:
Q: Biztalk SQL Adapter or a .NET SqlClient My application has BizTalk orchestration which needs to do basic insert into a table. Which is the better way of doing it

*

*using a SQL adapter that calls the stored procedure(with just one insert statement) on SQL server

*including a method call on orchestration where the method uses the SQLclient.SQLCommand.ExecuteNonQuery method with the SQLstored procedure on the GetCommand.

I want to know the best way of inserting the data into a database in the BizTalk orchestration.

A: The correct and best way to integrate with SQL Server in a BizTalk app is with the WCF SQL-Adapter.
Do not use the SQL Client in code since you have a greater chance of making things worse, operations, maintenance and performance, over using the built in tools.
Never guess or make assumptions about performance since without knowing exactly what to address, through test and measurement, you will either A) Spend time 'fixing' a problem that doesn't exist or B) make things worse by implementing something less optimized than the base product or C) both.
Use the WCF-SQL Adapter and if you measure a specific gap with an SLA, let us know, we can help you with that.  99.99%, the solution will not involve using the SQL Client directly.

A: You should always prefer using the SQL Adapter.

*

*It will be tracked in the Group Hub

*You'll get better diagnostics and tracking options around the port

*Retry logic is built in and configurable

The biggest downside is performance - it will create another persistence point in your orchestration on the send shape, whereas an inline SQL call would avoid that.


text:
Q: Should I convert categorical variables to continuos variables for SEM(Structural Equation Model)? Now, I trying to use SEM for checking HBN(Hierarchical Bayesian Network) structure.
I have ordered categorical independent variables and binary categorical dependent variable.
So, Should I convert that variables to continuos variables or dummy coding??
Can I just put the variables value like 'low', 'mid', 'high'...?

A: You do have not a minimal code with a reproducible example, so, I am not able to enter specificities... But generally speaking, depends on the package (and programming language) you use, but:

*

*binary data should be kept as binary (TRUE/FALSE, 1/0 usually accepted and identified as binary),

*and ordinal ones kept as ordinal. It means, that recording the ordinal as numeric (or factor) 1, 2, and 3 usually makes sense, to keep it ordinal. Converting it into string/character would be treating it as nominal (like in blue/yellow/black, no order). If the function accepts both (factor, character), possibly you need to specify explicitly their how to treat it/variable type).


text:
Q: ThreadpoolExecotor missing some rows in python I was experimenting with the multithreading and could not understand why it is skipping many rows?
please help me improve my code
can i use shutodown fn to improve it?
import concurrent.futures
import requests
import json
import time

URLList = []
for i in range(100):
    URLList.append("https://randomuser.me/api/")
def getName(urlApi):
        print(requests.get(urlApi).json()["results"][0]["name"])
def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        executor.submit(getName)
        executor.map(getName , URLList)

start_time = time.time()
main()
midtime = time.time() - start_time

print(f"--- {midtime} seconds ---")

Output is some random rows not 100 rows
{'title': 'Miss', 'first': 'Lily', 'last': 'Johnson'}
{'title': 'Mr', 'first': 'میلاد', 'last': 'سلطانی نژاد'}
{'title': 'Ms', 'first': 'Celina', 'last': 'Henry'}
{'title': 'Mr', 'first': 'آرمین', 'last': 'سالاری'}
{'title': 'Ms', 'first': 'Stans', 'last': 'Ordelman'}
{'title': 'Mr', 'first': 'Matthäus', 'last': 'Hilger'}
{'title': 'Ms', 'first': 'Marta', 'last': 'Flores'}
{'title': 'Mr', 'first': 'Alex', 'last': 'Gutierrez'}
{'title': 'Mr', 'first': 'Hugo', 'last': 'Walker'}
{'title': 'Mr', 'first': 'Vincent', 'last': 'Campbell'}
{'title': 'Mr', 'first': 'آریا', 'last': 'صدر'}
{'title': 'Mr', 'first': 'Lode', 'last': 'Mulderij'}
{'title': 'Miss', 'first': 'Manuela', 'last': 'Rubio'}
{'title': 'Mr', 'first': 'Jacob', 'last': 'Wang'}
{'title': 'Mr', 'first': 'رضا', 'last': 'کامروا'}
{'title': 'Mr', 'first': 'سهیل', 'last': 'مرادی'}
{'title': 'Miss', 'first': 'Kristin', 'last': 'Roberts'}
{'title': 'Mr', 'first': 'Allen', 'last': 'Weaver'}
{'title': 'Miss', 'first': 'Cathy', 'last': 'Johnston'}
{'title': 'Mr', 'first': 'Isaías', 'last': 'da Paz'}
{'title': 'Mr', 'first': 'Felix', 'last': 'Lam'}
{'title': 'Mr', 'first': 'Julio', 'last': 'Chambers'}
{'title': 'Mr', 'first': 'Felix', 'last': 'Johansen'}
{'title': 'Mr', 'first': 'Ruben', 'last': 'Mora'}
{'title': 'Mr', 'first': 'Marco', 'last': 'Diaz'}
{'title': 'Ms', 'first': 'Yvonne', 'last': 'Sims'}
{'title': 'Mr', 'first': 'Conrad', 'last': 'Owren'}
{'title': 'Mr', 'first': 'آرسین', 'last': 'گلشن'}
{'title': 'Mr', 'first': 'Aitor', 'last': 'Santos'}
{'title': 'Ms', 'first': 'Sally', 'last': 'Bell'}
{'title': 'Mr', 'first': 'Valentin', 'last': 'Marquez'}
{'title': 'Mr', 'first': 'Jacob', 'last': 'Mortensen'}
{'title': 'Monsieur', 'first': 'Nicolas', 'last': 'Lucas'}

Please Assist me.

A: I am able to get all 100 results when using the following snippet:
def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        results = [executor.submit(getName , x) for x in URLList]
    print(len(results))

However, when I try to actually look at the results:
[result.result() for result in results]

I get:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is because some of the requests do not actually come back successful.
So let's try changing getName a little bit so we see what happens when we fail:
def getName(urlApi):
  request = requests.get(urlApi)
  try:
    return request.json()["results"][0]["name"]
  except:
    return request.text

And for we get for some rows is:

<title>Uh oh, something bad happened</title>

Uh oh, something bad happened

Tweets by randomapi

If you try to reduce the number of workers, you will see that more requests come back successful, which suggests that you are facing some rate limiting. In any case, as far as multithreading is concerned, everything is working correctly and you are indeed sending a hundred requests and receiving a hundred responses. It's just that some of them aren't exactly the JSON responses you were hoping to get.
When setting max_workers to 1 I was able to get all 100 responses come back successfully. This way the requests are sent sequentially but asynchronously which is still parallel and therefore faster than simply sending them over one by one, waiting for each response before sending the next request.
With max_workers up to 4, I was still able to get 100% of the requests successfully but at max_workers=5 about half of them failed. You have to try and see what rate works best - you can always resend the failed requests but it's better to find the highest possible rate with no failures at all.


text:
Q: 'have the time' vs 'have time' I would like to use the phrase "Have you had time to look at my draft?" in American English, and I'm wondering if I need to use "the" before time.
I couldn't found an explicit answer to my question.
I found this discussion: enter link description here

A: Both are idiomatic. Without the article is less common. *Enough time** is also frequent.


text:
Q: Is it possible to restrict the CHANGE fields returned by JIRA API /rest/api/2/search I am using the API /rest/api/2/search/jql=XYZ&expand=changelog&fields=status This helps to restrict issue fields to status, but changelog contains full change history. But I want to restrict the change log to retrieve only status change details to reduce the amount of data returned by API

A: No, it's not possible to select records from the expanded history, the fields param only selects fields from the issue itself, not its changelog. The only way you can reduce the amount of data returned is by making the filter more complex, if you can. Maybe adding filters by created or updated dates, or status IS/WAS NAME-OF-STATUS if the status you are looking for is well known. After that, you'll have to process the response and iterate over all history items to filter the ones you need.


text:
Q: Realm 5.0.1 file shows up empty in Xcode 11.4 I'm using Realm 5.0.1 in Xcode 11.4.
My realm file is showing up empty (which it isn't):
Here is the class:
import Foundation
import RealmSwift

class Place4: Object {
    @objc dynamic var api:String?
    @objc dynamic var apiCounty:String?
...
    @objc dynamic var utmY:String?
    @objc dynamic var propDepth:String?

}

All fields are optional String. Here is the code that accesses the realm file:
        static let config = Realm.Configuration(fileURL: Bundle.main.url(forResource: "Place4", withExtension: "realm"), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: true, schemaVersion: 0, migrationBlock: nil, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil)

let realm = try! Realm(configuration: config)
let what =  realm.objects(Place4.self)
 print("19c what.count: \(what.count)")

output:
19c what.count: 0

I was able to open the file in Realm Studio using the path obtained as follows:
// debug
let path = Bundle.main.path(forResource: "Place4", ofType: "realm")
print("89q \(String(describing: path?.description))")

OK I simplified the config. It's static because it's in a separate utility class. I have used this code successfully before on other bundled realm files. There's something about these data it doesn't like, like the fact that all properties/fields are optional.
 static let config = Realm.Configuration(fileURL: Bundle.main.url(forResource: "Place4", withExtension: "realm"))
 let realm = try! Realm(configuration:config)
 places = realm.objects(Place4.self)
 print(places?.count)  // outputs 0 incorrectly


text:
Q: Insert blank cell based on a value in a selected range The script inserts a certain number of blank rows above or below based on the value in a certain cell.
For example if the value in cell G3 is 3 then it would insert 3 rows.
I only want to add blank rows to a selected column, in this case column E:G, because the data to the left of the worksheet in column "A:C" can't be shifted down.
Sub Insert_Rows()

Column_Number = Int(InputBox("Number of the Column on Which the Cell Values Depend: "))

Above_or_Below = Int(InputBox("Enter 0 to Insert Rows Above Each Row." + vbNewLine + "OR" + vbNewLine + "Enter 1 to Insert Rows Below Each Row."))

Dim Count As Integer
Count = 0

For i = 1 To Selection.Rows.Count
    For j = 1 To Int(Selection.Cells(i + Count, Column_Number))
        Selection.Cells(i + Above_or_Below + Count, Column_Number).EntireRow.Insert
        Count = Count + 1
    Next j
Next i

End Sub

This is the result:

This is what I want:


text:
Q: Playing Super Smash Bros 4 online in Latin America I tried to play ssb4 online but there is too much input delay and sometimes lag in the matches. I really want to play online because it is the best way I have to practice but when I try it is like a totally diferent game in comparison to playing with a friend in the same room.
I want to know if in North America it is a similar situation. Maybe the delay and lag is produced because I live too far away from the servers. Do exist a method to reduce this delay/lag to make the game more playable?

A: I cannot say for North America, but here in Australia lag on online Smash 4 is still definitely a problem.
You mention about being far away from the server, but as far as I know the game actually doesn't use dedicated servers. It instead uses only peer-to-peer connections, meaning that the quality of your game will not only be affected by your connection, but by the connection and hardware of all the other players in the match. So it wouldn't be about how far you are from a server, but how far away you are from the other players, and the quality of the connection between you and those players.
However, there are some things you can do to make sure it's not a problem on your side of things. This article has some suggestions, which I'll outline here:

*

*Don't use bandwidth-hungry applications on your network while you play. Things like streaming and large downloads are going to affect your game latency.

*Physical interference from other devices is a possibility. Bluetooth and WiFi devices, along with microwaves could interfere with your wireless network performance. (Personally, I've never had trouble with things like this, but it's a possibility worth checking.)

*If you are playing on Wii U, get an ethernet to USB adapter. These are relatively inexpensive and will allow you to use a wired internet connection from your router to your Wii U. This will avoid any latency involved in WiFi. In fact, the Smash 4 development team said themselves this was the best way to play online lag free.

Other than this, there is little you can do to reduce lag. If it's not problems with your connection, then you just have to hope the players you get matched with are close by and have good connections.
Of course if you have friends who live near you, you can choose "With Friends" to play with them, hopefully with less lag.


text:
Q: Why my Singleton class returns two different objects? I have written following Singleton class code,
class Singleton
{
private:
    Singleton(){}

public:
    static Singleton& getInstance()
    {
        static Singleton instance; //made it static so only initialized once

        return instance;
    }
};

Now I tried to use it,
int main(int argc, char* argv[])
{

    Singleton s = Singleton::getInstance();
    Singleton s1 = Singleton::getInstance();

    cout<<&s << "   " << &s1<<endl; //why getting different address here?

    return 0;
}

Both s,s1 gives different addresses.
Sample Output:

001AFECB   001AFEBF

I am using Visual Studio 2012. I made instance object static, so it should be initialized only once, and it should not die.


text:
Q: Async/await not reacting as expected Using the code below I expect the string "Finished" to appear before "Ready" on the console. Could anybody explain to me, why await will not wait for finishing the task in this sample?
    static void Main(string[] args)
    {
        TestAsync();
        Console.WriteLine("Ready!");
        Console.ReadKey();
    }

    private async static void TestAsync()
    {
        await DoSomething();
        Console.WriteLine("Finished");
    }

    private static Task DoSomething()
    {
        var ret = Task.Run(() =>
            {
                for (int i = 1; i < 10; i++)
                {
                    Thread.Sleep(100);
                }
            });
        return ret;
    }

A: The reason why you're seeing "Finished" after "Ready!" is because of a common confusion point with async methods, and has nothing to do with SynchronizationContexts. SynchronizationContext control which thread things run on, but 'async' has its own very specific rules about ordering. Otherwise programs would go crazy! :)
'await' ensures that the rest of the code in the current async method doesn't execute until after the thing awaited completes. It doesn't promise anything about the caller.
Your async method returns 'void', which is intended for async methods that don't allow for the original caller to rely on method completion. If you want your caller to also wait, you'll need to make sure your async method returns a Task (in case you only want completion/exceptions observed), or a Task<T> if you actually want to return a value as well. If you declare the return type of the method to be either of those two, then the compiler will take care of the rest, about generating a task that represents that method invocation.
For example:
static void Main(string[] args)
{
    Console.WriteLine("A");

    // in .NET, Main() must be 'void', and the program terminates after
    // Main() returns. Thus we have to do an old fashioned Wait() here.
    OuterAsync().Wait();

    Console.WriteLine("K");
    Console.ReadKey();
}

static async Task OuterAsync()
{
    Console.WriteLine("B");
    await MiddleAsync();
    Console.WriteLine("J");
}

static async Task MiddleAsync()
{
    Console.WriteLine("C");
    await InnerAsync();
    Console.WriteLine("I");
}

static async Task InnerAsync()
{
    Console.WriteLine("D");
    await DoSomething();
    Console.WriteLine("H");
}

private static Task DoSomething()
{
    Console.WriteLine("E");
    return Task.Run(() =>
        {
            Console.WriteLine("F");
            for (int i = 1; i < 10; i++)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("G");
        });
}

In the above code, "A" through "K" will print out in order. Here's what's going on:
"A": Before anything else gets called
"B": OuterAsync() is being called, Main() is still waiting.
"C": MiddleAsync() is being called, OuterAsync() is still waiting to see if MiddleAsync() is complete or not.
"D": InnerAsync() is being called, MiddleAsync() is still waiting to see if InnerAsync() is complete or not.
"E": DoSomething() is being called, InnerAsync() is still waiting to see if DoSomething() is complete or not. It immediately returns a task, which starts in parallel.
Because of parallelism, there is a race between InnerAsync() finishing its test for completeness on the task returned by DoSomething(), and the DoSomething() task actually starting.
Once DoSomething() starts, it prints out "F", then sleeps for a second.
In the meanwhile, unless thread scheduling is super messed up, InnerAsync() almost certainly has now realized that DoSomething() is not yet complete. Now the async magic starts.
InnerAsync() yanks itself off the callstack, and says that its task is incomplete.
This causes MiddleAsync() to yank itself off the callstack and say that its own task is incomplete.
This causes OuterAsync() to yank itself off the callstack, and say that its task is incomplete as well.
The task is returned to Main() which notices it's incomplete, and the Wait() call begins.
meanwhile...
On that parallel thread, the old-style TPL Task created in DoSomething() eventually finishes sleeping. It prints out "G".
Once that task gets marked as complete, the rest of InnerAsync() gets scheduled on the TPL to get executed again, and it prints out "H". That completes the task originally returned by InnerAsync().
Once that task gets marked complete, the rest of MiddleAsync() gets scheduled on the TPL to get executed again, and it prints out "I". That completes the task originally returned by MiddleAsync().
Once that task gets marked complete, the rest of OuterAsync() gets scheduled on the TPL to get executed again, and it prints out "J". That completes the task originally returned by OuterAsync().
Since OuterAsync()'s task is now complete, the Wait() call returns, and Main() prints out "K".
Thus even with a little bit of parallelism in the order, C# 5 async still guarantees that the console writing occurs in that exact order.
Let me know if this still seems confusing :)

A: You're in a console app, so you don't have a specialized SynchronizationContext, which means your continuations will run on Thread Pool threads.
Also, you are not awaiting the call to TestAsync() in Main. This means that when you execute this line:
await DoSomething();

the TestAsync method returns control to Main, which just continues executing normally - i.e. it outputs "Ready!" and waits for a key press.
Meanwhile, a second later when DoSomething completes, the await in TestAsync will continue on a thread pool thread and outputs "Finished".

A: As others have noted, console programs use the default SynchronizationContext, so the continuations created by await get scheduled to the thread pool.
You can use AsyncContext from my Nito.AsyncEx library to provide a simple async context:
static void Main(string[] args)
{
  Nito.AsyncEx.AsyncContext.Run(TestAsync);
  Console.WriteLine("Ready!");
  Console.ReadKey();
}

Also see this related question.


text:
Q: Different layout for all Ajax calls in Yii2 Whenever an ajax call is executed, I want the controllers to use the layout named "ajax" instead of the default "main" layout.
Does someone have an idea of how to do it?

A: For a global solution, you can create a base controller in components and change the layout in the init function:
namespace app\components;

class Controller extends \yii\web\Controller
{

    public function init()
    {
        parent::init();
        if (Yii::$app->request->isAjax) {
            $this->layout = '@app/path/to/ajax';
        }
    }
}

You should then ensure your controllers extend app\components\Controller.

A: You need to check if its an Ajax request then change the layout
if(Yii::$app->request->isAjax) {
  $this->layout = 'ajax';
}


text:
Q: Cannot save multiple images from a single image opencv (Java) i am using opencv 3.1 with Eclipse to divide an image in more images.
The problem is that when i try to save them, only the first of 9 images (for example) is saved.
The odd thing is that the console says the images are saved but i can see only one.
The code is the following:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Range;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class prova {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

    Imgcodecs imageCodecs = new Imgcodecs();

       String file
="C:/Users/Zast/Desktop/workspacePR2/tesina/images/img.jpg";
      Mat mat= imageCodecs.imread(file);

      System.out.println("Image Loaded");

   // Creating an empty matrix to store the result
     // Mat dst = new Mat();

       for (int i=0; i<3; i++){
             for (int j=0; j<3; j++){
            int a1=i*200;
            int b1=i*200+199;
            int a2=j*200;
            int b2=j*200+199;
            Mat mat2= mat.submat(a1,b1,a2,b2);
            imshow ("filtro", mat2);

            String file2 =
"C:/Users/Zast/Desktop/workspacePR2/tesina/images/img1.jpg";

            imageCodecs.imwrite(file2, mat2);
            System.out.println("Image Saved ............");
             }}
}

    private static String String(int i) {

    return null;
}

    public static void imshow(String windowname, Mat m){
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if ( m.channels() > 1 )
            type = BufferedImage.TYPE_3BYTE_BGR;
        int bufferSize = m.channels()*m.cols()*m.rows();
        byte [] b = new byte[bufferSize];
        m.get(0,0,b); // get all the pixels
        BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
        final byte[] targetPixels = ((DataBufferByte)
        image.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);
        ImageIcon icon=new ImageIcon(image);
        JFrame frame=new JFrame(windowname);
        JLabel lbl=new JLabel(icon);
        frame.add(lbl);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

      System.out.println("Image Processed");
   } }

The output console is the following:
Image Loaded
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............
Image Processed
Image Saved ............


text:
Q: Calculating average value of a signal The formula is
$$
\frac{1}{T}\int_{a}^{b}S(t) .dt
$$
I understand how the integral gives us the area under the curve, but average means the sum of all over how much all is, the integral here is the sum of all $S(t)dt$ between $a$ and $b$ but shouldn't it really be just the sum of the $S(t)$'s between $a$ and $b$ divided by $T$?

A: To take an average of a few discrete data points, we would add all the data points and divide by the number of data points. If you had a time interval $T$ divided into steps of size $\Delta t$, the number of data points would be $N=T/\Delta t$. Therefore, the average of measurements at those times would be
$$\frac{S(t=1)+S(t=2)+...S(t=N)}{N}=\frac{S(t=1)\Delta t+S(t=2)\Delta t+...S(t=N)\Delta t}{T}$$
Now think of taking the limit that $\Delta t$ becomes infinitesimal and you get the integral.


text:
Q: If (co)domain of map of chain complexes is in(pro)jective, then every quasi-isomorphism is a homotopy equivalence I'm reading some lecture notes which are an introduction to homotopy theory, and there is a short section on chain complexes, where the difference between a quasi-isomorphism and homotopy equivalence of chain complexes is explained. Then, the following proposition is stated:

Let $f: C_{\bullet} \to D_{\bullet}$ be a quasi-isomorphism of chain complexes. If $D_{\bullet}$ is projective OR $C_{\bullet}$ is injective, then $f$ is also a homotopy equivalence.

I would like to know a reference where a proof of this is given, or at least where this is discussed in a bit more detail. I have checked the textbooks of Weibel and Rotman, but I wasn't able to find anything. I don't know homological algebra too well, so maybe I didn't see a certain proposition or theorem in one of these books that implies this.
For what it's worth, I tried for about 15 minutes to do this by myself, and the only idea I had was to take an isomorphism in homology $h_{n}: H_{n}(D_{\bullet}) \to H_{n}(C_{\bullet})$ inverse to $f_{*}$ and try to find an epimorphism $D_{n} \to H_{n}(D_{\bullet})$ and $C_{n} \to H_{n}(C_{\bullet})$, and then lift the diagram which combines these three morphisms by projectivity of $D_{\bullet}$, finding a $g_{n}$ which would then ideally be an inverse homotopy equivalence to $f$.
Also, since $d:D_{n} \to D_{n-1}$ may not be zero (same for $C$), such an epimorphism might be hard to find, so I thought maybe being able to find a chain complex with differential zero which is homotopy equivalent to $D_{\bullet}$ would help, but that is probably equivalent to solving the problem itself, no?


text:
Q: 2d transformations, rotation not as intended I'm trying to implement a set of basic euclidean transforms in 2d space in javascript and I seem to be having a problem with my rotation.
    // simple 2d html5 interface
"use strict";

class Point{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    mul(c){
        this.x *= c;
        this.y *= c;
    }
}

class TransMatrix{
    /*    see https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/geometry/geo-tran.html
     *    for more info.
     *    c1 c2 c3
     *    c4 c5 c6
     *    c7 c8 c9
     */
    constructor(){
        this.c1 = 1;
        this.c2 = 0;
        this.c3 = 0;

        this.c4 = 0;
        this.c5 = 1;
        this.c6 = 0;

        this.c7 = 0;
        this.c8 = 0;
        this.c9 = 1;
    }

    applyMatrix(point){
        point.x = this.c1*point.x + this.c2*point.y + this.c3;
        point.y = this.c4*point.x + this.c5*point.y + this.c6;
    }

    copy(){
        var matrix = new TransMatrix();
        matrix.c1 = this.c1;
        matrix.c2 = this.c2;
        matrix.c3 = this.c3;

        matrix.c4 = this.c4;
        matrix.c5 = this.c5;
        matrix.c6 = this.c6;

        matrix.c7 = this.c7;
        matrix.c8 = this.c8;
        matrix.c9 = this.c9;
        return matrix;
    }

    translation(x,y){
        var newMatrix = this.copy();

        newMatrix.c3 += x;
        newMatrix.c6 += y;

        return newMatrix;
    }
    scale(s){
        var newMatrix = this.copy();

        newMatrix.c1 += s;
        newMatrix.c5 += s;

        return newMatrix;
    }
    rotation(r){ //radians
        var newMatrix = this.copy();

        newMatrix.c1 += Math.cos(r);
        newMatrix.c2 += -Math.sin(r);
        newMatrix.c4 += Math.sin(r);
        newMatrix.c5 += Math.cos(r);

        return newMatrix;
    }
}

function drawHexagon(canvas, matrix, strokeColor, fillColor) {
    if (!canvas) {
        return;
    }

    var points = [new Point(0.5 ,  1),
                  new Point(1   ,  0),
                  new Point(0.5 , -1),
                  new Point(-0.5, -1),
                  new Point(-1  ,  0),
                  new Point(-0.5,  1)
    ];

    points.forEach(point => {
        matrix.applyMatrix(point);
    });

    drawHexagonLit(canvas,points[0],points[1],points[2],points[3],points[4],points[5], "red", "green");
}

function drawHexagonLit(canvas, p1, p2, p3 ,p4 ,p5, p6, strokeColor, fillColor){ // add border cases here
    if(!canvas){
        return;
    }
    var ctx = canvas.getContext("2d");
    if(!ctx){
        return;
    }
    ctx.beginPath();
    ctx.moveTo(p1.x, p1.y);
    ctx.lineTo(p2.x, p2.y);
    ctx.lineTo(p3.x, p3.y);
    ctx.lineTo(p4.x, p4.y);
    ctx.lineTo(p5.x, p5.y);
    ctx.lineTo(p6.x, p6.y);
    ctx.lineTo(p1.x, p1.y);
    ctx.strokeStyle = strokeColor;
    ctx.fillColor = fillColor;
    ctx.stroke();
    ctx.fill();
    ctx.closePath();
}

function dynamicBackgroundInit(canvas){
    if(!canvas){
        return;
    }
    var worldMatrix = new TransMatrix();

    var rotate = 0;

    function step(){
        canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
        rotate += 0.01;
        var transform = worldMatrix.rotation(rotate); // this is better reflected by a matrix inside an object
        transform = transform.translation(50,50);
        transform = transform.scale(30,30);
        drawHexagon(canvas, transform, "red", "green");
        window.requestAnimationFrame(step);
    }

    window.requestAnimationFrame(step);
}

Calling and translation work as intended but rotation seems to generate poor results. Initially I thought I was just rotating on an external origin point but I no longer think so as the problem is still there when the initial object is simply scaled up.

A: Your transformation code produces artifacts because you use point coordinates both before and after transform, so in second line the transformed coordinate in used instead of the original:
applyMatrix(point){
        point.x = this.c1*point.x + this.c2*point.y + this.c3;
        point.y = this.c4*point.x + this.c5*point.y + this.c6; // transformed point.x is used instead of the original point.x

}
Instead do the following:
applyMatrix(point){
        var x = point.x, y = point.y;
        point.x = this.c1*x + this.c2*y + this.c3;
        point.y = this.c4*x + this.c5*y + this.c6;
    }

Use similar caching of original coordinates in any other transformation you try to apply simlultaneously. Store them in temp variables first then apply using original and new coords as different variables


text:
Q: code after [NSThread cancel] is not invoked I have a instance variable of type NSThread:
NSThread *workerThread;

In one function, I instantiate this NSThread variable & starts it:
-(void)startTask {
  workerThread = [[NSThread alloc] initWithTarget:self
                                                    selector:@selector(doWork)
                                                      object:nil];
  [workerThread start];
}

(The doWork is doing long running task.)
In another function, I try to stop the task & stop/kill the worker thread & do something else:
-(void) stopTask {
 // stop long running task
 [self stopWork]
 NSLog(@"I can see this log");
 [workerThread cancel];

 // code never reach here
 [self doSomethingElse];
}

The problem I encounter is after I started the worker thread, when I call stopTask, the [self doSomethingElse] never get invoked.
Why? How to get rid of this problem?


text:
Q: How do I resolve, "The application which this project type is based on was not found." error? I'm trying to launch the ServiceStack.AndroidIndie solution to use with the tutorial. I'm trying to enable the ServiceStack Api in my Android app; However, I'm receiving the following error, upon trying to open the project file:
Migration Report -

Overview

Project Path                            Errors  Warnings    Messages
ServiceStack.Client.AndroidIndie.csproj     1       0           0
ServiceStack.Interfaces.AndroidIndie.csproj 1       0           0
ServiceStack.Text.AndroidIndie.csproj       1       0           0
ServiceStack.AndroidIndie.sln               0       0           1

ServiceStack.Client\ServiceStack.Client.AndroidIndie.csproj: The application which this project type is based on was not found.
ServiceStack.Interfaces\ServiceStack.Interfaces.AndroidIndie.csproj: The application which this project type is based on was not found.
..\..\ServiceStack.Text\src\ServiceStack.Text\ServiceStack.Text.AndroidIndie.csproj: The application which this project type is based on was not found.
ServiceStack.AndroidIndie.sln: The solution file does not require migration.

I am of course using the latest version downloaded of the official GitHub page, also synced with ServiceStack directly through windows GitHub app.
Tried launching projects in both VS 2012 and VS 2013. Same error.
Any ideas?

A: The Xamarin plugin for Visual Studio is not free. It is currently only available with a Xamarin Business plan ($999 p/a) or Enterprise plan ($1899 p/a). See the Xamarin Store
You can confirm if the plugin is installed and active by:

*

*Opening Visual Studio

*Choose Tools Menu

*Choose Extensions & Updates

*You should see, under Installed > All

Check it's not disabled.
If it's not there then you will need to to this:

*

*Visit xamarin.com/download

*Choose Download Xamarin for Windows

*Run the installer on windows. Select the Android Components. (add iOS if required). It will probably take about 30 minutes to install.

*Launch Visual Studio when the installion completes

*Open the project, this dialog should be shown

*Create a Xamarin account and activate the 30 day trial or Enter your existing Xamarin Business/Enterprise credentials.
You will be able to open the project in Xamarin Studio (as you have discovered), for free, without any issue.


text:
Q: Solving Equations Containing Floor Functions Recently I have been struggling with a problem involving the floor function. The problem is:
$$
\lfloor x+5 \rfloor = 3\lfloor x\rfloor-1
$$
I have had a similar question to this however it only involved the floor function on one side of the equation and I was able to set up a pair of inequalities and solve them however I have not been able to do the same for this question.
What I have done so far is attempt the same procedure by solving the equation and then setting up a set of inequalities but have been unable to come up with a reasonable answer. I have also graphed this for clarity but am still unsure what is really going on or how to approach this question.
Thank you.

A: *

*equation: $$\lfloor x+5 \rfloor=3\lfloor x \rfloor−1$$

*same as: $$\lfloor x\rfloor+5 = 3\lfloor x \rfloor-1 $$

*add $1$: $$\lfloor x \rfloor+6 = 3\lfloor x \rfloor $$

*subtract $\lfloor x \rfloor$: $$6 = 2\lfloor x \rfloor$$

*divide by $2$: $$3 = \lfloor x \rfloor$$

*do the floor thing: $$3 \le x \lt 4$$

A: This is equivalent to $\lfloor x\rfloor +5=3\lfloor x\rfloor-1$, i.e.
$$
\lfloor x\rfloor=3 \implies x \in [3,4[.
$$


text:
Q: Are there any decent Windows Phone 7 device one can connect a usb flash drive to? Are there Windows Phone 7 devices that have USB Host drivers so that my C# program can access data on a USB Flash Drive?

A: You won't find many phones of any operating system which support USB host.
USB really isn't suitable for mobile devices - the USB specification requires a 5V power rail which really isn't suitable for a phone and its battery to support.
If you need expandable storage, I believe there are some phones with micro SD slots available (and there should be more of these available in the future) - although there are some restrictions about these - they're not really removable - see http://support.microsoft.com/kb/2450831.


text:
Q: Why does less force correspond to less work done? I'm confused with the definition of work in physics. I know that it's defined as a product of force, displacement and a cosine of angle between them: $W = F  s \cos(\alpha)$. But that means that the work of moving an object from one place to another depends on the absolute value of force we apply to it provided the displacement and the angle stay the same. But as I understood, the work equals to the total energy given away to move the object. But with weaker force and the same distance we will move the object to the finish point just with more time and the energy intuitively should stay the same. So why is that the case that weaker force corresponds to less work done? Thank you.

A: No, the energy wouldn't be the same if you move an object the same distance with a weaker force. Let's see this explicitly. The energy that is given to the object during this process will be reflected in what property of the object? It will be reflected in its speed. So, if the speed of the object at the end of the process is smaller for the weaker force then we can explicitly see that the process carried out with a weaker force will, in fact, be pouring less energy into the object. So, let's see what is the speed $v$ at the end of this process if it is carried out under the influence of a force $F$. For simplicity, I will assume that the force is in the direction of the displacement.
Assuming a constant force, the acceleration of the object will be $F/m$. Now, since the object travels a distance of $s$ starting from rest, we can write $s=\frac{1}{2}\frac{F}{m}t^2$ where $t$ is the time it takes for the process to complete. As you can see, you are right that it would take a larger $t$ if we choose a smaller $F$ to cover the same distance $s$. But, now, let's compute the speed that the object will have at the end of this process. For uniformly accelerated motion, we can write $v=\frac{F}{m}t$. Expressing this $t$ in terms of $s$ from our previous formula, we can write $$v=\frac{F}{m}\sqrt\frac{2ms}{F}=\sqrt{\frac{2Fs}{m}}$$
So, indeed, the weaker the force, the smaller the final speed will be.

A: Nice question.  So , I am considering a situation where we are rolling a ball up a hill. Neglect any friction and assume the hill is a perfect inclined plane making an angle (theta) with the horizontal. Let the mass of the ball be M.
And let's consider rolling the ball a distance D up the hill.
To move the ball up the hill , the minimum force we need to apply on it is Mgsin(theta) (to balance gravity)
So consider we are applying a force 2Mgsin(theta) on the ball .
Let's consider the energy changes which happened after rolling the ball a distance D up the hill .
The gravitational potential energy of the ball ( rather the earth - ball system) increases by some amount .
The ball gains some velocity and hence gains some  kinetic energy .
Now say we apply a force  4Mgsin(theta) , clearly the work done by us on the ball  is  doubled.
But the change in gravitational potential energy is the same!
What about kinetic energy?
As we applied a greater force on the ball , the net acceleration of the ball was more than the first case and hence the velocity gained by it after rolling the same distance D up the hill will be greater.
Hence , the kinetic energy gained by  the ball is more than the first case .
In other words , you can say that the additional work goes into the kinetic energy of the ball.


text:
Q: First time opening an SSH server to internet, what to check I've been running a few servers for a relatively long time, but I always only rented them, so I don't have much experience securing the actual server (as opposed to the application I'm running on it).
Now I feel like opening up my small home SSH server to the internet.
I will be the only one using it, my passwords are complicated enough, I've changed the default SSH port to something around 4000, the only accessible port is this SSH port through port-forwarding on my router/firewall, and it gets updated automatically every night (it runs Arch Linux, a rolling release distribution).
What are, if any, other things I should do to keep it secure?
Thanks!

A: Make sure only SSH-2 is allowed (since SSH-1 has raised some security concerns in the past):
Protocol 2

Specify which are the only users allowed to login via SSH:
AllowUsers bob, john

For increased security, disallow password authentication and use public-key authentication:
PasswordAuthentication no
PubkeyAuthentication yes

Note: this tutorial contains instructions for creating keys and configuring public-key authentication.

A: As well as the points about disabling root login or using public key authentication only, I'd also double check that there are no user accounts on the system that have trivial or empty passwords. You've said your personal passwords are fine, but that doesn't rule out an account with a poor password having been created for some other reason.
As an example:  I had to fix up one network where the previous admin had installed nagios on all his systems from source, and created a nagios user with either no password, or the password "nagios", and then proceeded to get three different machines compromised.

A: You might want to look at some kind of IP blacklisting tool like http://denyhosts.sourceforge.net/. It blocks any IPs that try to log in unsuccessfully too many times and is highly configurable.

A: I suggest that you install Fail2ban! http://www.fail2ban.org
It bans an IP after x failed tries for y minutes, helping to keep scriptkiddies in check ;)

A: Make sure root logins are disabled PermitRootLogin no. I would also consider disabling passwords altogether PasswordAuthentication no and use public keys PubkeyAuthentication yes.

A: Reoccurring log reviews across the pertinent portions/components of your systems (depending on its actual/specific configuration)...


text:
Q: Selenium wait until user clicks on button I am trying to make a python program using selenium that opens the browser and does some stuff, waits for the user to click on a button, then selenium takes over again. I know that I am supposed to use an explicit wait but I do not know how to make selenium wait for the user to click a button on the browser before continuing with my code.
Here is a summary of my code so far:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait

driver_path = my_driver_path
driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options)

driver.get(my url)
... (Some code that does automation stuff until a certain point)

#What do I do here?
wait = WebDriverWait(driver, 10)

...(After the user clicks I want the program to resume)

A: Presumably, something on the website changes when the user clicks on the button. Define that change as the wait condition.
For example, if you expect an element to pop up:
def is_visible(by, identifier):
    def condition(driver):
        elems = driver.find_elements(by, identifier)
        ele = elems and elems[0]
        exists_and_displayed = ele and ele.is_displayed()
        return exists_and_displayed
    return condition

wait.until(is_visible(By.ID, 'added_or_unhidden_after_click'))

Or if you expect something to disappear:
def is_not(condition):
    @ft.wraps(condition)
    def wrapper(driver):
        return not condition(driver)
    return wrapper

wait.until(is_not(is_visible(By.ID, 'removed_or_hidden_after_click')))

(typed from memory, might have a syntax error or so, but you should get the idea)
(The built-in expected_conditions as EC basically do these same things, but I run into small issues with them here and there the way they're written, so I prefer to roll my own.)


text:
Q: Filter ng-repeat json result against array At the moment I have a json result which is displayed in an ng-repeat that I would like to have filtered based on a separate object or array of data:
Controller.js
$scope.jsonResult = [
 {
   "id": "a123"
 },
 {
  "id": "b456"
 }
]

HTML
{{r.id}}

What I am attempting to achieve is to create a separate array of info and then use this data to filter the ng-repeat results that display in my HTML.
$scope.itemsToFilter = ["b456","foo"]

Since an item within my itemsToFilter array matches an object within my jsonResult scope, I would like that not to display within my ng-repeat within the HTML. Is this something I should write a custom filter for? Sorry I am very new to Angular.

A: The easiest way is by using a custom filter. A quick filter can be written like this:
$scope.filterByStrings = function (item) {
    return ($scope.itemsToFilter.indexOf(item.id) === -1);
};

And called like this:

{{item.id}}

Here is the fiddle.

A: You can create an Angular filter which returns the array filtered by items' ids which match your blacklist:
angular.module("yourAppName")
.filter("filterArrayByBlacklist", function() {
    blackList = ["b456","foo"];
    return function(array) {
        return array.filter(function(item) {
            return blackList.indexOf(item.id) === -1; // item id not found in blacklist
        });
    };
});

You can then filter the ng-repeat by your filter function:
{{r.id}}

See this plnkr for a demo: http://plnkr.co/edit/VK3jiVBpL0e1G06WmPZq


text:
Q: How to MVVM toggleswitch in UWP How to correctly setup toggleswitch with command? I am using behavior to launch command using Toggled event. However I have problem when user changed state of switch, but my model rejects it. I do not know how to correctly program it, so view rejects update if it was rejected by model.
Here are my attempts to do it (INotifyPropertyChanged details skipped for clarity):
1. One way command
class ToggleSwitchVm {
     public bool IsOn => Model.IsOn;
     public ICommand SwitchManipulated {get;}
}

When user manipulates ToggleSwitch state in UI changes, but it is not related to state in model. Also toggleswitch ignores PropertyChanged events, while it is calling command:
async void SwitchManipulatedCommand(bool? state) {
    if(!Model.SetNewState(state.Value)) { // if failed to set state raise PropertyChanged to refresh view
        RaisePropertyChanged(nameof(IsOn)); // this call is ignored :(
    }
}

2. Two way property?
class ToggleSwitchVm {

    private void ModelOnPropertyChanged(object sender, PropertyChangedArgs args){
       if(args.PropertyName == nameof(Model.IsOn)){
          IsOn = Model.IsOn;
       }

    }

    private bool _isOn;
    public bool IsOn
    {
        get => _isOn;
        set {
                if(SetValue(ref _isOn, value))
                {  // true if model was manipulated
                    // View set value, or model set value?
                    if(!Model.SetState(value))
                    {
                         RaisePropertyChanged(nameof(IsON)); // ignored by view
                    }
                }
            }
    }
}

This is a mess, because both Model and View set IsOn property and there is no way to know which one set it.

A:
How to MVVM toggleswitch in UWP

The ToggleSwitch IsOnProperty is DependencyProperty, that means it could use to bind data with two way model. And you have no need to process the IsOn proprty in command method. Please refer the following code to implement the feature.
Xaml Code
<Page.DataContext>
    <local:ViewModel />
</Page.DataContext>

<Grid>
    <ToggleSwitch
        Header="Toggle work"
        IsOn="{Binding IsOn, Mode=TwoWay}"
        OffContent="Do work"
        OnContent="Working"
        />
</Grid>

Code behind
public class ViewModel: INotifyPropertyChanged
{
    private bool _isOn;
    public bool IsOn
    {
        get { return _isOn; }
        set { Set(ref _isOn, value); }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}


text:
Q: SSRS subscription throwing Invalid State error when saving I have migrated to a new report server. When trying to create new subscriptions through the URL I am getting the following error:
Operation is not valid due to the current state of the object.

I found that a certain windows KB can cause this issue (KB2656356 and KB2656351) However I have found that adding a key to the web.config file might also do the trick.
<https://social.msdn.microsoft.com/Forums/sqlserver/en-US/cb6ede72-6ed1-   4379-9d3c-847c11b75b32/report-manager-operation-cannot-run-due-to-current-state-   of-the-object?forum=sqlreportingservices/>

But after adding this key and bouncing the services, no change. I still get the error. Has anyone experienced this?
ui!ReportManager_0-1!5144!03/21/2017-10:23:17:: e ERROR: System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Web.HttpRequest.FillInFormCollection()
   at System.Web.HttpRequest.get_Form()
   at System.Web.HttpRequest.get_HasForm()
   at System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull)
   at System.Web.UI.Page.DeterminePostBackMode()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
library!ReportServer_0-2!5e0!03/21/2017-10:23:18:: i INFO: Call to GetSystemPermissionsAction().
ui!ReportManager_0-1!5144!03/21/2017-10:23:18:: e ERROR: HTTP status code --> 500
-------Details--------
System.InvalidOperationException: Operation is not valid due to the current state of the object.

    at System.Web.HttpRequest.FillInFormCollection()

    at System.Web.HttpRequest.get_Form()

    at System.Web.HttpRequest.get_HasForm()

    at System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull)

    at System.Web.UI.Page.DeterminePostBackMode()

    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
 library!ReportServer_0-2!5e0!03/21/2017-10:23:18:: i INFO: Call to GetSystemPropertiesAction().
 ui!ReportManager_0-1!5144!03/21/2017-10:23:18:: e ERROR: System.Threading.ThreadAbortException: Thread was being aborted.
    at System.Threading.Thread.AbortInternal()
    at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at Microsoft.ReportingServices.UI.ReportingPage.ShowErrorPage(String errMsg)

The SSRS version is 11.0.3000.0. It is a native install. I am creating the subscription through the report server URL "businessreport/reports";. It seems directly related to the amount of available parameters. In my case if I pair down the amount of items including the report, then I don't have an issue. Obviously i can edit the report to fix this, but I inherited a very large amount of reports. I'd rather be able to pass as many as necessary. Hopefully that helps
Also I have tried editing the web.config file in both of the following directories:
I:\MSRS11.SQLPROD\Reporting Services\ReportManager

and
    I:\MSRS11.SQLPROD\Reporting Services\ReportServer
I included the following:  This did not make a difference at all.


text:
Q: iphone sdk - expected identifier error i'm trying to load up a url with the value of the input field added to the end of the url and it errors with "expected identitifer" :(
[self fetchURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/test/script.php?name=%@&",[[urlField text]]]];

what have I done wrong?

A: You have missed the bracket
[self fetchURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/test/script.php?name=%@&",[[urlField text]]]]];

OR try instead
    NSString *urlString = [NSString stringWithFormat:@"http://localhost/test/script.php?name=%@&",[urlField text]];
    NSURL *url = [NSURL URLWithString:urlString];
    [self fetchURL:url];


text:
Q: Format String Attack in C I'm studying a security unit and I'm attempting to understand format string attacks. Could somebody please attempt to explain this to me?
The following code is taken from: http://julianor.tripod.com/bc/tn-usfs.pdf:
/*
 * fmtme.c
 *       Format a value into a fixed-size buffer
 */
#include <stdio.h>
int
main(int argc, char **argv)
{
    char buf[100];
    int x;
    if(argc != 2)
        exit(1);
    x = 1;
    snprintf(buf, sizeof buf, argv[1]);
    buf[sizeof buf - 1] = 0;
    printf("buffer (%d): %s\n", strlen(buf), buf);
    printf("x is %d/%#x (@ %p)\n", x, x, &x);
    return 0;
}

As I understand it, the %n format specifier is used to read a specified address back into memory, then when printf pops values off the stack, it should read our address. I can't seem to pull this off.
In the document, the following example is provided:
perl -e 'system "./fmtme", "\x58\x74\x04\x08%d%n"'

Where did \x58\x74\x04\x08%d%n come from?

A: "\x58\x74\x04\x08%d%n" is the "shell code".
The exploit is explained very carefully in that document. I suppose it expects you to have some understanding of the typical layout of stack frames, which also is explained in the table . Keep in mind that stack addresses typically grows downwards, which means that a function call that "pops" more arguments than was actually passed to it will start reading local variables from the stack frame below its own. This is what this shell code exploits.
It puts an address in the first 4 bytes of buf (because snprintf prints it into there) and then it skips the x variable (from the frame below it) and finally reads the address from the first part of buf (but interpreted as a pointer) and write a value to it, via the %n format code.


text:
Q: Windows Tablet PC Keyboard blocks application I have created a Windows Form application (with MetroUI) for a Windows Tablet PC. The problem is that some dialogs are full screen.
When the user clicks on an input field which is located in the middle or at the bottom, the on-screen keyboard completely blocks the input field and the user is unaware of the input until the keyboard is hidden.
Is there a way I can show the user the input field during the input process (while the keyboard is still on screen). For instance whenever a user selects and input field in iOS or Android, the application tends to move upward to make way for the keyboard.


text: Q: xrandr center/adjust image on the display monitor It is possible to center/adjust the image on the display monitor with xrandr on ubuntu 16.04? The display is a borderless LG 24bk750y-b connected to a HMDI port of a Dell Inspiron 15 3567 with radeon hybrid graphics AMD Radeon R5 M430


text:
Q: How to use Loops in cloudbees CASC bundle for Controller configuration? Here is what I'm trying to use --

    ## Items.yaml
    removeStrategy:
      rbac: SYNC
      items: NONE
    items:
    - kind: multibranch
      name: "{{ item.name }}"
      projectFactory:
        workflowBranchProjectFactory:
          scriptPath: Jenkinsfile
      sourcesList:
      - branchSource:
          source:
            bitbucket:
              repoOwner: "{{ item.owner }}"
              serverUrl: https://github.com
              credentialsId: github_account
              id: github_id
              repository: "{{ item.repo }}"
      loop:
        -  { name: 'x', owner: 'y' , repo: 'z' }
        -  { name: 'a', owner: 'b' , repo: 'c' }


text:
Q: Search engine for Apache Derby I would like use a search engine for my application with Apache Derby database (contatin around 10k rows with text).
For web projects I used an elasticsearch, but it a desktop application. I would like to use an elasticksearch or solr for this app. It possible run elasticsearch or solr for it? It's require many memory or run in other (not application) thread, or have an alternative for derby?

A: There is a Lucene-Derby integration as part of this summer's release of Derby: https://issues.apache.org/jira/browse/DERBY-590
The development is complete; it is in testing. You can get access to it now, and give feedback to the development team about how it works for you.


text:
Q: Javascript copy  tag with html format to clipbord I'm trying to copy all of the content from a p tag using javascript. It works, but it copies the text in one long line of text. I want it to copy with the format using the break tags, like if someone were to copy / paste using their mouse like so:
Current Time: :
Time Found: :
Ambient Temp: °C
Notes:
Frequency:
Reproducible?"
Thanks so much for any help.
  <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>title</title>

Documentation Sheet

     Current Time: :

     Time Found: :

     Ambient Temp: °C

     Notes:

     Frequency:

    Reproducible?

      <button onclick="copyToClipboard('#p1')">Copy text</button>

    ere

A: One can write a function to do this like:
function copyToClipboard(id) {
        var from = document.getElementById(id);
        var range = document.createRange();
        window.getSelection().removeAllRanges();
        range.selectNode(from);
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
 }

Note: My solution does not require jQuery, and takes a document id as an input, so don't forget to leave out the "#"!
Just use it as follows:
 <button onClick="copyToClipboard('p1')">Copy text</button>

A: I don't think there's a quick and easy way to do what you want to do. You'd have to use html() instead of text() to extract the contents of the
 tag, but then you'd have a bit of work to do processing the HTML you'd get back -- stripping tags that should be ignored, converting entities, converting inner
 and
 into line breaks, etc.
So you'd change this line like this:
$temp.val(parseHtml($(element).html())).select();

Then would follow the harder work of defining the parseHtml() function.


text:
Q: Extend JS Boolean.prototype fail I want to do this:
a = false;

a.toggle();

console.log(a) // -> true;

So I created this:
Boolean.prototype.toggle = function (){this = !this; return this;}

But Its just doesnt work. I tried many similar versions also with valueOf and whatever, but always fail.
I suspect that Boolean object has no setter method @ its prototype. But May be you guys can help with this.
Thanks in advance.
(Please dont answer "Why a = !a doesnt good for you?")

A: First of all, you can never assign to this in javascript so this = !this won't work.
Second of all, it does not appear that the Boolean object has a setter.  It has valueOf() and it has toString().
This is the closest I can come to it:
Boolean.prototype.toggle = function (){return !this.valueOf();}

var a = false;
var b = a.toggle();

console.log(b) // -> true;


text:
Q: How to add imported image to formData I need to send the imported image as a file. I try to add it into new File() but it will not recognize the type and correct size of image and i can't send i to backend
import img from '../image.png';
...
const image= new File([img], "img.png");

console.log(image) //
lastModified: 1590023609558
lastModifiedDate: Thu May 21 2020 05:13:29 GMT+0400 (Armenia Standard Time) {}
name: "img.png"
size: 41 //(my real file size is 124KB)
type: ""
webkitRelativePath: ""


text:
Q: How to run varnish as a non-privilege user? I need to run varnish as a non-root user. Here is what I'm actually doing:
wget https://repo.varnish-cache.org/source/varnish-4.0.2.tar.gz
tar xzf varnish-4.0.2.tar.gz
./configure --prefix=/home/neuquino/varnish
make
make install

But, when I run varnishd command I get the following error:
Message from VCC-compiler:
Not running as root, no priv-sep

It seems to be something with VCL compiler. Is there any option I should pass to the ./configure or make commands to be able to run varnishd as a normal user?
I'm looking forward to find something like ./configure --user=neuquino, but I can't find such option in the configure file.


text:
Q: Parsing out data from files (Python): How to determine the number of republicans, democrats and independents in the 114th congress So, I have been working on this bit of code to determine the number of senators from the 114th congress who were republicans, democrats, and independents. Here's my code. For some reason, I keep getting funky errors regarding my variables that start with num. Please help.
def main():
    # Determines the number of senators of each party affiliation
    infile = open("Senate114.txt", 'r')
    set1 = {line.rstrip() + "\n" for line in infile}
    infile.close()
    listx = list(set1)
    listx.sort(key=lambda x: x.split(',')[2])  # sort by party affiliation
    partyAffiliation = listx[2]
    rep = []
    dem = []
    ind = []
    numRep = []
    numDen = []
    numInd = []
    while (partyAffiliation == 'R'):
        rep = rep.expend
        numRep == int(len(rep))
    while (partyAffiliation == 'D'):
        dem = dem.extend
        numDem == int(len(dem))
    while (partyAffiliation == 'I',):
        ind = ind.extend
        numInd == int(len(ind))

    print('Party Affiliation: ')
    print('Republicans: ',numRep)
    print('Democrats:' ,numDem)
    print('Independents:' ,numInd)

main()

A: Assuming data that looks similar to this:
Gooding,Cuba,R
Miller,Dennis,D
Bolton,Michael,I
Grouch,Oscar,I
Einstein,Albert,R
Azaria,Hank,D
Motzart,Amadeus,I

You can use code like the following:
import collections

lines = open("Senate114.txt").read().splitlines()
parties = [line.split(",")[2] for line in lines]
party_counts = collections.Counter(parties)

print(party_counts)

OUTPUT
Counter({'I': 3, 'R': 2, 'D': 2})

You could add on:
print('Party Affiliations: ')
print('Republicans:', party_counts.get('R', 0))
print('Democrats:', party_counts.get('D', 0))
print('Independents:', party_counts.get('I', 0))


text:
Q: "Could not find method platform()" after Firestore upgrade for Flutter project I just upgraded to Firestore 0.14.4 from 0.13.* for my VSCode/Flutter project and am now getting the build errors below.
FAILURE: Build failed with an exception.

* Where:
Build file 'C:\projects\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.14.4\android\build.gradle' line: 54

* What went wrong:
A problem occurred evaluating project ':cloud_firestore'.
> Could not find method platform() for arguments [com.google.firebase:firebase-bom:25.12.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org
BUILD FAILED in 2s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

My build.gradle file has the line classpath 'com.android.tools.build:gradle:3.3.2 which makes me think my gradle needs upgrading? So, I did the usual Google search but it didn't seem straightforward to upgrade gradle (though I'm sure I missed something). Does it sound like I need to upgrade and, if so, how do I do that?


text:
Q: IF...ELSE conditional always return ELSE conditional I have a simple query like this:
@DesignKey [INT] = NULL
AS
        BEGIN
            -- SET NOCOUNT ON added to prevent extra result sets from
            -- interfering with SELECT statements.
            SET NOCOUNT ON;

            -- Insert statements for procedure here
            IF(@DesignKey != NULL)
            BEGIN
                 SELECT
                     [P].[LegacyKey] AS [Job No]
                   , [TT].[Name] AS [Task]
                   , CONCAT([E].[FirstName] , ' ' , [E].[MaidenName]) AS [Technician]
                    FROM [Task] AS [T]
                        LEFT JOIN [TaskAssignation] AS [TA] ON [T].[TaskAssignationId] = [TA].[TaskAssignationId]
                        LEFT JOIN [Employee] AS [E] ON [TA].[EmpKey] = [E].[EmpKey]
                        INNER JOIN [TaskType] AS [TT] ON [T].[TaskTypeId] = [TT].[TaskTypeId]
                        INNER JOIN [Design] AS [D] ON [T].[DesignKey] = [D].[DesignKey]
                        INNER JOIN [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
                        INNER JOIN [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
                    WHERE [E].[EmpKey] IS NOT NULL
                         AND [T].[DesignKey] = @DesignKey
            END
               ELSE
            BEGIN
                             SELECT
                    [P].[LegacyKey] AS [Job No]
                   , [TT].[Name] AS [Task]
                   , CONCAT([E].[FirstName] , ' ' , [E].[MaidenName]) AS [Technician]
                    FROM [Task] AS [T]
                        LEFT JOIN [TaskAssignation] AS [TA] ON [T].[TaskAssignationId] = [TA].[TaskAssignationId]
                        LEFT JOIN [Employee] AS [E] ON [TA].[EmpKey] = [E].[EmpKey]
                        INNER JOIN [TaskType] AS [TT] ON [T].[TaskTypeId] = [TT].[TaskTypeId]
                        INNER JOIN [Design] AS [D] ON [T].[DesignKey] = [D].[DesignKey]
                        INNER JOIN [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
                        INNER JOIN [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
                    WHERE [E].[EmpKey] IS NOT NULL

            END
        END

As you can see it will execute different selects depending if @DesignKey comes null or not, so I execute query as:
exec usp_Get_EmpoyeeByDesign

and it runs correctly it execute second select now if I send @DesignKey as:
exec usp_Get_EmpoyeeByDesign @DesignKey = 2837

It load same result, it doesn't take care my if conditional I test it sending parameter of designKey in where clause as:
WHERE [E].[EmpKey] IS NOT NULL
                         AND [T].[DesignKey] = 2837

and it  throws desire results. So in conclusion query don't validate if @DesignKey come or not. What is wrong there? Regards

A: Replace     != NULL    with   IS NOT NULL.
Any operation with NULL returns NULL, not True.
Think of NULL as meaning "I don't know".
You have two baskets of apples.  One of them has 7 apples.  The other basket is covered so you don't know how many apples there are. Do the two baskets have the same number apples?  Do they have a different number of apples?
declare @a int, @b int
set @a = 7    -- 7 apples
set @b = NULL -- I don't know how many apples

if @a = @b
  print 'Equal' -- doesn't print

if @a <> @b
  print 'Not equal' -- doesn't print

Since you don't know how many apples are in the second bucket you can't know that the number of apples are equal, nor can you know whether they are not equal.


text:
Q: Merging two adjacent polygons which borders are not touching each other? I want to merge adjacent single polygons which are apart from each other.
Important note: I cannot use ArcGIS, I need to do this programatically, in any language (R, Python, Ruby, PostGIS) doesn't really matter which it is, it can be a combination of a scripting or compiled code and/or command line tools.
So far I have tried using Turf.js methods convex (hull) and union. Union doesn't grow/shrink the edges to to complete with the neighbouring polygon, but it rather just creates a a geometry collection of all the polygons processed as a single feature. The convex hull creates a single polygon but ignores the inner points, just the farthest and gives a wrong final shape. I've tried using the Eliminate Sliver Polygons... in the QGIS Vector>Geoprocessing Tools menu but the operation fails with a Python error: **

global name 'QErrorMessage' is not defined
  Traceback (most recent call last):
    File "/usr/local/Cellar/qgis-214/2.14.1/QGIS.app/Contents/Resources/python/plugins/fTools/tools/doEliminate.py", line 96, in accept
      self.eliminate(inLayer, boundary, self.progressBar, outFileName)
    File "/usr/local/Cellar/qgis-214/2.14.1/QGIS.app/Contents/Resources/python/plugins/fTools/tools/doEliminate.py", line 236, in eliminate
      QErrorMessage(self).showMessage(
  NameError: global name 'QErrorMessage' is not defined

3 Adjacent polygons that are suppose to be merged into a single one:

Desired resulting single polygon shape
The expected border is drawn with a red contour.

A: Demo solution with OpenJUMP
Original polygons

Buffer the polygons so much that they overlap and make a union. This can be done as a single operation with OpenJUMP. Flat end cap and mitre join with quite a high limit are good settings.

The gaps between the polygons have disappeared but the union is too large.

Use negative buffer for the union and shrink it. Red outline shows the final result.


text:
Q: i'm so confused about Threads I read a lot about threads but don't understand yet :( let me explain to you what I have learned about threads. all we are working on such as codes any thing worked on UI thread or Main thread right? After that what happens if we call runOnUiThread? and my other question how do we know it's Time to use a new thread? I mean how do we understand we are working on another thread or replace or code in the new thread?
I know this is an unclear question but I don't understand as well. Please help me Thanks, john.

A: Let me try to answer. Actually Android has Main Thread (also called as UI Thread) and other thread.
Main Thread is basically for showing UI and other thread is for processing other big processes such as connecting to the server, etc.
runOnUiThread is called when you want to move from other thread to main thread. It is needed since only main thread can show/display result on UI. So when you have done some process on other thread, and you want to display the result on the apps, you need to show it on main thread by calling runOnUiThread.
We working on other thread only if it is a big or lengthy process like taking data from the server, load data, etc. And we move from other thread to main thread whenever we want to show some UI result.

A: Easiest way is to use   AsyncTask<> class. You'll need to override three functions.

*

*doInBackGround(...) : The codes that gets executed in background thread.

*onPreExecute(..) : code that gets executed before background thread
completes executing like displaying progress bars, etc.

*onPostExecute(...): Code that gets executed after background thread
has completed running. Perform task like updating UI in here

A: One general rule of thumb is: Don't use multithreading if you don't need to. Multithreading is always error-prone, and in many situations there's no benefit. Basically, you start a new thread whenever you execute a lengthy operation (i.e. some extensive computation like image processing) that would block the main thread for some time, so the application would become unresponsive.


text:
Q: Cannot find problem - [Error] ld returned 1 exit status I need help finding this error the compiler is giving me:

C:\Users\AppData\Local\Temp\ccaruUld.o Test3_Problem2.cpp:(.text+0x73): undefined reference to `SUM(float, float)'
C:\Users\Downloads\collect2.exe    [Error] ld returned 1 exit status

Code:
    //Test 3 - Problem 2
#include<iostream>
#include<cmath>
using namespace std;

float SUM(float value,float sum);

int main()
{
    //Introduce program to user
    cout<<"This program asks for 5 numbers and averages the numbers \
together.";

    //Declare variables
    float averg,value[4],sum1=0;

    //Allow user to enter 5 values
    for(int i=0;i<=4;i++){
        cin>>value[i];
    }
    sum1=SUM(value[4],sum1);
    cout<<value[0];

}
    float SUM(float vales[4],float sum) {
        for(int i=0;i<=4;i++){
            sum+=vales[i];
    }
    return sum;
}

Cannot whatsoever find it no matter how much I fix my code.
I looked at similair questions and since this is an entry level C++ course all of the answers looked like alien language to me...

A: I encountered a few different problems, so I rewrote the code and commented on the errors that I fixed. Hope this helps!
//Test 3 - Problem 2
#include<iostream>
#include<cmath>
using namespace std;

//THE FIRST PARAM WAS NOT DECLARED AS A VECTOR
//obs: That way you do not need to set the vector size limit or the variable name
float SUM(float[],float);

int main()
{
    //Introduce program to user
    //Forgot the " << endl;"
    cout<<"This program asks for 5 numbers and averages the numbers \ together." << endl;

    //Declare variables
    //Declared vector size less than 5 numbers
    float averg,value[5],sum1=0;

    //Allow user to enter 5 values
    for(int i=0;i<=4;i++){
        cin >> value[i];
    }
    sum1 = SUM(value,sum1);
    //You were print the vector at position 0 instead of the result of the sum
    //and forgot the " << endl;"
    cout << sum1 << endl;;

}
    //VALES WAS NOT DECLARED AS A VECTOR
    //obs: Beware of indentation
float SUM(float vales[],float sum) {
    for(int i=0;i<=4;i++){
        sum+=vales[i];
    }
    return sum;
}

A: Assuming the code you have posted here is all of it, your problem is that you have not implemented the SUM() function.
This code:
float SUM(float value,float sum);

Is called a function prototype which is not the same as an implementation of that function.
https://en.wikipedia.org/wiki/Function_prototype

The term function prototype is particularly used in the context of the programming languages C and C++ where placing forward declarations of functions in header files allows for splitting a program into translation units, i.e. into parts that a compiler can separately translate into object files, to be combined by a linker into an executable or a library.

This is why your IDE is possibly not warning you that the SUM function does not exist, because you have a function prototype at the top of your code which matches the calls in your code to that function.
To fix this you need to implement the SUM function:
float SUM(float value,float sum)
{
    //Implementation
}

A: Try this, it should work:
//Test 3 - Problem 2
#include<iostream>
#include<cmath>
using namespace std;

float SUM(float vales[4],float sum) {
    for(int i=0;i<=4;i++){
        sum+=vales[i];
}
return sum;
}

int main()
{
 //Introduce program to user
 cout<<"This program asks for 5 numbers and averages the numbers \
 together.";

//Declare variables
float averg, value[4], sum1=0.0;

//Allow user to enter 5 values
for(int i=0;i<=4;i++){
    cin>>value[i];
}
sum1=SUM(value,sum1);
cout<<value[0];
}


text:
Q: SQL - Add constraint check using object's member function I'm using Oracle 11g to create my SQL queries.
So far I have an object:
CREATE OR REPLACE TYPE property_type AS OBJECT (
    propertyNo                NUMBER,
    dateOfRegistration        DATE, [etc..]

  MEMBER FUNCTION       date_of_registration_is_valid RETURN NUMBER
);
/

Which compiles no problem and has the body:
CREATE OR REPLACE TYPE BODY property_type AS
  MEMBER FUNCTION date_of_registration_is_valid RETURN NUMBER IS
    is_valid        NUMBER;
    BEGIN
      IF (self.dateOfRegistration < SYSDATE) THEN
        is_valid := 1;
      ELSE
        is_valid := 0;
      END IF;

    RETURN is_valid;
  END;
END;
/

Which also compiles and works fine, then I get to my table:
CREATE TABLE property_table OF property_type (
  PRIMARY KEY           (propertyNo),
  CONSTRAINT            property_not_null
  CHECK                 (propertyNo IS NOT NULL),
  CONSTRAINT            property_reg_is_valid
  CHECK                 (property_object.date_of_registration_is_valid() = 1)
) NESTED TABLE relates_to STORE AS relates_to_table;
/

Which I expect to check the date_of_registration_is_valid() function to see if it returns the value 1 (true). I've tried all sorts of alternatives such as replacing the property_object value for self, leaving it blank etc, but I get an error. For the above it's the error:
Error report -
SQL Error: ORA-00904: "PROPERTY_OBJECT"."DATE_OF_REGISTRATION_IS_VALID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:

So how can I use a member function as a CHECK CONSTRAINT?

A: From the documentation, check constraints can't call user-defined functions, which presumably includes member functions.
You could get similar behaviour with a constructor function that raises an exception:
CREATE OR REPLACE TYPE property_type AS OBJECT (
    propertyNo                NUMBER,
    dateOfRegistration        DATE,
    -- [etc ]
    CONSTRUCTOR FUNCTION property_type (SELF IN OUT NOCOPY property_type,
        propertyNo NUMBER, dateOfRegistration DATE /* [etc] */ )
    RETURN SELF AS RESULT
);
/

CREATE OR REPLACE TYPE BODY property_type AS
    CONSTRUCTOR FUNCTION property_type (SELF IN OUT NOCOPY property_type,
        propertyNo NUMBER, dateOfRegistration DATE /* [etc */ )
    RETURN SELF AS RESULT IS
    BEGIN
        IF dateOfRegistration < SYSDATE THEN
            RAISE_APPLICATION_ERROR(-20001, 'Registration date before today');
        END IF;
        SELF.propertyNo := propertyNo;
        SELF.dateOfRegistration := dateOfRegistration;
        RETURN;
    END;
END;
/

Then without the member function check constraint (or the nested table as my simplified type doesn't have one), and without the explicit null check ans the primary key on the same column implies that anyway:
CREATE TABLE property_table OF property_type (
  PRIMARY KEY           (propertyNo)
);
/

Table property_table created.

A couple of trial inserts:
insert into property_table values (property_type(1, sysdate));

1 rows inserted.

insert into property_table values (property_type(2, sysdate - 1));

Error starting at line : 32 in command -
insert into property_table values (property_type(2, sysdate - 1))
Error report -
SQL Error: ORA-20001: Registration date before today
ORA-06512: at "STACKOVERFLOW.PROPERTY_TYPE", line 7

Depending on the data, you might want the validation to be against trunc(sysdate) so it's from midnight this morning, not the current time.


text:
Q: County Finder form/plugin? I'm developing a WP site for a client and need to build in a "county finder" for our state (VT).  Users would type the name of a town into a field  (or select the town from a drop-down menu), press the submit button, and the system would spit out the name of the county that the town is located in.  Ideally the results are delivered within the page, no new page load required, but that's not essential.
I'm not expecting to find a pre-made solution...I'll have to enter the towns and counties manually of course...but I wasn't even sure what to look for in this case.
Any suggestions appreciated.  Thanks!

A: Dadra,
A bit off the WordPress topic, but you may want to consider using the US Census API to do your lookups.
Integrating this into WP should be pretty simple, could be done by zipcode, city name, etc... and could be done with and AJAX callback all on one page.
Example of what I think you want: http://quickfacts.census.gov/cgi-bin/qfd/lookup
US Census API Developer site: http://www.census.gov/developers/
For specific WP implementation methods, I'm thinking you may want to hire someone with a fairly solid background with external API integrations.


text:
Q: How to capture a specific region of an inactive application window in C# .NET? I only need a very specific portion of an non-foreground application window saved as a Bitmap, not the entire application window. I have been using this function to find and create a screenshot of my application but I do not understand how to modify the starting point and size of the RECT to process only a specific portion of the application window (i.e. notepad).

public static IntPtr WinGetHandle(string wName)
{
     foreach (Process pList in Process.GetProcesses())
         if (pList.MainWindowTitle.Contains(wName))
             return pList.MainWindowHandle;

     return IntPtr.Zero;
}

[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

public static void PrintThisWindow(IntPtr hwnd)
{
    // Create the Rectangle
    RECT rc = new RECT();
    GetWindowRect(hwnd, out rc);

    // Capture bmp from hwnd
    Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
    Graphics gfxBmp = Graphics.FromImage(bmp);
    IntPtr hdcBitmap = gfxBmp.GetHdc();
    PrintWindow(hwnd, hdcBitmap, 0);

    // Dispose
    gfxBmp.ReleaseHdc(hdcBitmap);
    gfxBmp.Dispose();

    //bitmap.Save
    bmp.Save("Example.png");
}

//Whatever window you want to test.
IntPtr hwnd = WinGetHandle("New Text Document.txt - Notepad");
PrintThisWindow(hwnd)

I have tried manually setting the RECT with RECT rc = new RECT(100, 100, 200, 200)
I have also tried setting the location 'point' and size of the rect: rc.Location = new Point(100, 100) and rc.Size = new Size(100, 100). Help would be appreciated, I spent many many hours trying to find a function that is similar that I could adapt but I couldn't find anything aside from CopyFromScreen: captureGraphics.CopyFromScreen(200, 200, 0, 0, new Size(100, 100)); which works by starting at the correct point and size BUT it quite literally copies from the entire screen and not from a specific window. Thanks in advance!
Here is the RECT class:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    private int _Left;
    private int _Top;
    private int _Right;
    private int _Bottom;

    public RECT(RECT Rectangle) : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
    {
    }
    public RECT(int Left, int Top, int Right, int Bottom)
    {
         _Left = Left;
         _Top = Top;
         _Right = Right;
         _Bottom = Bottom;
    }

    public int X
    {
         get { return _Left; }
         set { _Left = value; }
    }
    public int Y
    {
         get { return _Top; }
         set { _Top = value; }
    }
    public int Left
    {
         get { return _Left; }
         set { _Left = value; }
    }
    public int Top
    {
         get { return _Top; }
         set { _Top = value; }
    }
    public int Right
    {
         get { return _Right; }
         set { _Right = value; }
    }
    public int Bottom
    {
         get { return _Bottom; }
         set { _Bottom = value; }
    }
    public int Height
    {
         get { return _Bottom - _Top; }
         set { _Bottom = value + _Top; }
    }
    public int Width
    {
         get { return _Right - _Left; }
         set { _Right = value + _Left; }
    }
    public Point Location
    {
         get { return new Point(Left, Top); }
         set
         {
              _Left = value.X;
              _Top = value.Y;
         }
    }
    public Size Size
    {
         get { return new Size(Width, Height); }
         set
         {
              _Right = value.Width + _Left;
              _Bottom = value.Height + _Top;
         }
    }

    public static implicit operator Rectangle(RECT Rectangle)
    {
         return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height);
    }
    public static implicit operator RECT(Rectangle Rectangle)
    {
         return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);
    }
    public static bool operator ==(RECT Rectangle1, RECT Rectangle2)
    {
         return Rectangle1.Equals(Rectangle2);
    }
    public static bool operator !=(RECT Rectangle1, RECT Rectangle2)
    {
         return !Rectangle1.Equals(Rectangle2);
    }

    public override string ToString()
    {
         return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}";
    }

    public override int GetHashCode()
    {
         return ToString().GetHashCode();
    }

    public bool Equals(RECT Rectangle)
    {
         return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;
    }

    public override bool Equals(object Object)
    {
         if (Object is RECT)
         {
              return Equals((RECT)Object);
         }
         else if (Object is Rectangle)
         {
              return Equals(new RECT((Rectangle)Object));
         }

         return false;
    }
}


text:
Q: Why my Mathematica 9.0.1 wont work with some samples of Mathematica in Graph Theory? Bug introduced in 9.0 and fixed in 10.0
 FindMinimumCostFlow is introduced in 9.0.

I updated my Mathematica recently to 9.0.1 cause the previous version was giving me freaky result especially in FindMinimumCostFlow and OptimumFlowData. But even in new version I have problems.It can not still solve the multi-source multi-sink problem even the same example of Mathematica documentation such as first of basic examples:
FindMinimumCostFlow[
 Graph[{1, 2, 3, 4, 5, 6}, {UndirectedEdge[1, 2],
   UndirectedEdge[2, 3], UndirectedEdge[3, 4], UndirectedEdge[1, 5],
   UndirectedEdge[5, 6], UndirectedEdge[6, 4], UndirectedEdge[2, 5],
   UndirectedEdge[3, 6]}, {ImageSize -> 110,
   VertexShapeFunction -> {"Name"}}],
{1, 3, 4, -3, -4, -1}]

After evaluation it doesn't return any result. Can somebody help me on that?


text:
Q: How to extract a few lines from a pdf files? I have a PDF file that goes like this:
Q1. How many planets are there?
A. 1
B. 3
C. 8
D. 9
Answer: 8
Explanation: bla bla bla
Q2. How many moons are there?
A. 1
B. 3
C. 8
D. 9
Answer: 1
Explanation: bla bla bla
Q3. Who is Alex's friend?
A. Adam
B. Donald
C. Joe
D. Jack
Answer: Joe
Explanation: bla bla bla
And so on upto Q100
How to remove the Answer and Explanation and only get the Questions, i.e. in the following format
Q1. How many planets are there?
A. 1
B. 3
C. 8
D. 9
Q2. How many moons are there?
A. 1
B. 3
C. 8
D. 9
Q3. Who is Alex's friend?
A. Adam
B. Donald
C. Joe
D. Jack
.... and so on upto Q100

A: OK, After a lot of trial and error was abe to figure out
First I converted the PDF to txt file
then used the code (pic attached)
Basically converted the file to lists and used regex to append only needed outputs. (input File was UTF). A very dumb way of doing it, but it works!!!


text:
Q: Does Commercial use of GhostScript as Saas needs a licence ? I was working on a project. In which a user can upload PDF and convert it into images and So that i have used GhostScript dll (gsdll32.dll). Now in my application i want to charge from users as monthly subscription so that i can provide them more features.
But i neither have any knowledge about the licencing terms nor about ghostscript tearms & conditions.
So do i need to purchase any licence regarding Or is there any other free C# library, that can be used for pdf processing, which i can use in a commercial applicatoni without acquiring any licence ?
Well i am preferring any free c# library for regarding (Premium Saas or direct application selling).
Thank you
If anyone having real time experience regarding above, Please help me out.

A: I am not a lawyer. You should get one, if you are concerned about possible legal issues.

Does Commercial use of GhostScript as Saas needs a licence?

Well, first of all, you need a license to use any software (except one, which is public domain) in any way.
As for Ghostscript at the moment Artifex offers it under: a) GNU Affero GPL, which is license for free/libre software; b) non-free/proprietary license, which Artifex calls a 'commercial license'. But it's called 'commercial' because, I guess, Atrifex makes money on it, definitely not because that is only way for you to use Ghostscript for profit.
Any free software license, including GNU AGPL, by definition gives you, once you obtain a copy of software, right to use it for commercial purposes, including selling it; but you, of course, have to strictly follow the terms of that license. The key point of GNU AGPL is that it is a strong copyleft license. That means, that you have to make your entire software product, which is based on Ghostscript, subject of GNU AGPL, which in turn put you under obligation to provide to your customers (including customers of SaaS) correspondent sources for your product and to grant them permissions to (0) use it in any purpose, (1) redistribute it, (2) modify it and (3) distribute modifications; all of that in accordance with GNU AGPL.
So no, you have not obtain 'commercial license' from Artifex to use Ghostscript in your app. But if are not going to provide these four freedoms to your users, then yes, you'd better contact Artifex and ask them a price.
By the way, Artifex is not pioneer of that practice of copyleft/proprietary bi-licensing, it is well-known for years.
As for why I said 'at the moment'. Not so long ago, prior to version 9.06 (inclusive), free/libre license of Ghostscript was not GNU Affero GPL, but ordinary GNU GPL (see license files doc/COPYING in source archives as a proof), which is a bit more permissive – it does not oblige you to grant any permissions to users that interact with your software via client-server protocol over a network but does not possess a copy (that's what you mean by 'SaaS', I guess). Users who bought a copy still have to obtain it under GNU GPL.
Version 9.06 is definitely not too old – is supplied now in testing version of Debian. You might consider using it.