text:
Q: How can do such a custom tab in iOS
Hi all, as you can see, how can I implement a custom tab bar like above?
When you clicked one tab, the tab would be dim, and the tab would be over the other one. Thanks all.

A: There is no standard controller with such behaviour in cocoatouch, so, there are two ways to do that - first way is to implement this control by yourself from scratch,  the second way is to use custom third party control, for example: http://www.hollance.com/2011/11/mhtabbarcontroller-a-custom-tab-bar-for-ios-5-using-the-new-container-apis/


text:
Q: Getting the Top 5 Lowest Value in An array I have a Java program that will output the top 5 lowest value from an array(disCent) with this kind of algorithm. This is my code:
   Arrays.sort(distCent);
  System.out.println(Arrays.asList(distCent));

Thanks for your recommendations on using sort. I've modified my code as above. Now, how do I check the position of the first 5 value in the sorted list from the original list so the output should be something like this:
Smallest is at x position with value of y.
2nd smallest is at x position with value of y....and so on.

A: Use the sort() method to get the values in ascending order then just grab the first five.
Arrays.sort( array );

If you need the position in the original array then get the index of the sorted array's first five values.

A: As the other answer notes, you should use the Arrays.sort method. You really shouldn't re-invent the wheel for something this basic.
If, however, you cannot use the Arrays methods for some reason, and/or have a pathological hatred of sorting, the following code should do what you desire:
public static void lowest5(int[] args){
    int[][] ret = {{Integer.MAX_VALUE,0},{Integer.MAX_VALUE,0},{Integer.MAX_VALUE,0},{Integer.MAX_VALUE,0},{Integer.MAX_VALUE,0}}; \\There are much better ways to do this
    for(int i = 0; i < args.length;i++){
        int swapper = args[i]
        int swapper_index = i;
        for(int n = 0; n < 5;n++){
            if(swapper < ret[n][0]){
                swapper ^= ret[n][0]; \\this is a neat trick for swapping in place
                ret[n][0] ^= swapper; \\b ^ (a^b) = a
                swapper ^= ret[n][0]; \\ a ^ (a^b) = b

                swapper_index ^= ret[n][1];
                ret[n][1] ^= swapper_index;
                swapper_index ^= ret[n][1];
            }
        }
    }
    //print ret
}

A: Assuming you have the lastest JDK installed it should be pretty easy:
    final int[] ints = {1, 3, 6, -10, 43, 100};
    final int[] just5 = Arrays.stream(ints).sorted().limit(5).toArray();
    System.out.println(Arrays.toString(just5));

It works even with fewer than 5 items. (Arrays from java.util.Arrays)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Можно ли ограничть подключени к БД с сервера только одним пользователем? Есть сеть, а в сети есть сервер, который досутпен всем и БД Oracle.
Хочется сделать так, чтобы с этого сервера можно было подключаться только одним конкретным техническим пользователем. Подключения с других серверов не должны ограничваться.
Можно наверное написать триггер на логон, который будет отклонять все сесии с указаного сервера, если подключается не тех. уз. Однако, это выглядит ужасным решением.
Возможно у Oracle есть какие нибудь настройки безопасности или еще что-то, что позволит органичть подключение?

A: Краткое напоминание, что происходит, если с именем пользователя БД выполняется комманда connect.

*

*Сначала, посредством Oracle Net, устанавливается сетевое соединение (сессия). Через это соединение происходит всё дальнейшее общение между клиентом и БД.

*Клиент посылает запрос авторизации пользователя в БД, на основании которого создаётся новая сессия БД.
На первом шаге возможно ограничить доступ только на уровне протокола: IP, имя хоста, доступные сервисы БД. Но никак нельзя ограничить по имени пользователя, так как оно на этом шаге пока неизвестно.
Из этого следует, что на стороне сервера БД огранничить возможно только при авторизации пользователя (шаг два) посредством логон триггера. Например:
create or replace trigger checkUserOnLogonTrig after logon on database
declare
    currip varchar2 (16) := sys_context ('USERENV','IP_ADDRESS');
begin
    if currip = '192.168.1.111' and user != 'ADMIN' then
        raise_application_error (-20000, 'checkUserOnLogonTrig: the logon from '||currip||
            ' is not allowed for user '||user);
    end if;
end;
/

Попытки подсоединится с хоста с заданным IP будут отклонены:
SQL> conn  hr/hr@dbsrv/dbsvc
ERROR:
ORA-04088: error during execution of trigger 'SYS.CHECKUSERONLOGONTRIG'
ORA-00604: error occurred at recursive SQL level 1
ORA-20000: checkUserOnLogonTrig: the logon from 192.168.1.111 is not allowed for user HR

Возможно, что лучшее алтернативное решение будет: ввести ограничения на подключение к БД на стороне сервера приложений, как средствами ОС, так и самого приложения.

A: В режиме ограниченного сеанса к базе данных могут подключаться только пользователи с ограниченными правами сеанса, другие обычные пользователи не могут подключаться к базе данных, если мы не отключим режим ограниченного сеанса.
Уже подключенные пользователи могут выполнять свои действия DML / DDL, но новый сеанс для пользователей не будет создан.
Включить режим может пользователь с правами sysdba:

SQL> alter system enable restricted session ;

System altered.

Проверить для каких пользователей включен режим ограничения сессии:

SQL>
SQL> select logins from v$instance ;
LOGINS
----------
RESTRICTED

Назначить права техническому пользователю:
SQL> grant restricted session to techuser ;

Grant succeeded.

Забрать права на ограниченную сессию:

SQL> revoke restricted session from techuser ;

Revoke succeeded.

Выключить режим ограниченной сессии:

SQL> alter system disable restricted session ;

System altered.


text:
Q: Using Cron job to activate a php script but it's not run completely I am using cronjob to activate a php script. Although when i do it manually from the browser, the script takes 3-4 seconds to load and it outputs result into the database.
When cron job does it, it seems that the script is unable to complete in the alloted time and the cronjob stops loading the script mid way, the cron works about 1/10 of the time, the rest 9/10 times it fails to complete the task. Is there a way i can ensure that the script is loaded completely each time the cron job activates it?
Script is simple completely php based. Any suggestions?

A: I'd suggest implementing a lockfile (overrun protection) solution. Basically when your script kicks off it will do a check for a lockfile, and if the lockfile exists, the script can assume the previous incantation is still running, so it will halt execution. And when the script is complete it will remove the lockfile so subsequent runs can get passed the lockfile check and execute in their entirety.
A lock file usually contains the process id spawned by the script and usually located somewhere like /var/lock/my_script.lock.
You can google around for more info, but here is a site with a lockfile example.


text:
Q: Intel XDK - codesign - no identity found - AdHoc - Distribution Profile I'am developing an Hybrid mobile APP using Cordova in Intel XDK.
While developing, Emulating & Testing and also Building Development Builds to test on real device, all worked well.
Now I created an Production Certificate and an Distribution Provisioning Profile, and let the Intel XDK Build the APP for Ad Hoc to send it via "Application Loader" to the App store to roll it out on multiple Test-Devices.
But here the online-build stops saying "no identity found" see the pastebin.
What do I do wrong??

A: Ok Folks, it worked that way:

*

*DO NOT NAME YOUR Wildcard APP ID like your final APP ID (it CONFUSES a lot) -.-

*Download the CSR from the XDK

*Create an Production Certificate for "App Store and Ad Hoc" with that CSR

*Download that Certificate and upload it to the iOS Build in the XDK

*Create an Distribution Provisioning Profile BE AWARE OF MAKING MISTAKES NOW

*Chose "Distribution > Ad Hoc", then "next"

*Choose THE RIGHT!!!!! App ID (not the Wildcard, like I did, because it was named like the right App ID, my Fault) then "Continue"

*Choose THE RIGHT!!!! Certificate (generated with the CSR from the XDK, not -like I did- generated with an local MAC keychain)

*Download the Porovisioning Profile and set it in the Build-Settings

*Build your APP

It is my FIRST APP so all that Settings (Certificates, Devices, Provisioning Profiles, ...) are really confusing for me because I don't now their relation ^^
May that also helps someone else who is confused like I was -.-


text:
Q: finding mean using pig or hadoop I have a huge text file of form
data is saved in directory data/data1.txt, data2.txt and so on
merchant_id, user_id, amount
1234, 9123, 299.2
1233, 9199, 203.2
 1234, 0124, 230
 and so on..

What I want to do is for each merchant, find the average amount..
so basically in the end i want to save the output in file.
something like
 merchant_id, average_amount
  1234, avg_amt_1234 a
  and so on.

How do I calculate the standard deviation as well?
Sorry for asking such a basic question. :(
Any help would be appreciated. :)

A: Apache PIG is well adapted for such tasks. See example:
inpt = load '~/pig_data/pig_fun/input/group.txt' as (amnt:double, id:chararray,c2:chararray);
grp = group inpt by id;
mean = foreach grp {
    sum = SUM(inpt.amnt);
    count = COUNT(inpt);
    generate group as id, sum/count as mean, sum as sum, count as count;
};

Pay special attention to the data type of the amnt column as it will influence which implementation of the SUM function PIG is going to invoke.
PIG can also do something that SQL can not, it can put the mean against each input row without using any inner joins. That is useful if you are calculating z-scores using standard deviation.
 mean = foreach grp {
    sum = SUM(inpt.amnt);
    count = COUNT(inpt);
    generate FLATTEN(inpt), sum/count as mean, sum as sum, count as count;
};

FLATTEN(inpt) does the trick, now you have access to the original amount that had contributed to the groups average, sum and count.
UPDATE 1:
Calculating variance and standard deviation:
inpt = load '~/pig_data/pig_fun/input/group.txt' as (amnt:double, id:chararray, c2:chararray);
grp = group inpt by id;
mean = foreach grp {
        sum = SUM(inpt.amnt);
        count = COUNT(inpt);
        generate flatten(inpt), sum/count as avg, count as count;
};
tmp = foreach mean {
    dif = (amnt - avg) * (amnt - avg) ;
     generate *, dif as dif;
};
grp = group tmp by id;
standard_tmp = foreach grp generate flatten(tmp), SUM(tmp.dif) as sqr_sum;
standard = foreach standard_tmp generate *, sqr_sum / count as variance, SQRT(sqr_sum / count) as standard;

It will use 2 jobs. I have not figured out how to do it in one, hmm, need to spend more time on it.

A: So what do you want? You want the running java code or the abstract map-reduce process? For the second:
The map step:
record -> (merchant_id as key, amount as value)

The reduce step:
(merchant_id, amount) -> (merchant_id, aggregate the value you want)

As in the reduce step, you will be provided with a stream of record having the same key and you can do almost everything you can including the average, variance.

A: you can calculate the standard deviation just in one step; using the formula
var=E(x^2)-(Ex)^2
inpt = load '~/pig_data/pig_fun/input/group.txt' as (amnt:double,  id:chararray, c2:chararray);
grp = group inpt by id;
mean = foreach grp {
    sum = SUM(inpt.amnt);
    sum2 = SUM(inpt.amnt**2);
    count = COUNT(inpt);
    generate flatten(inpt), sum/count as avg, count as count, sum2/count-    (sum/count)**2 as std;
};

that's it!

A: I calculated all stats(min, max, mean and standard deviation) in just 1 loop. FILTER_DATA contains data-set.
    GROUP_SYMBOL_YEAR = GROUP FILTER_DATA BY (SYMBOL, SUBSTRING(TIMESTAMP,0,4));
STATS_ALL = FOREACH GROUP_SYMBOL_YEAR {
    MINIMUM = MIN(FILTER_DATA.CLOSE);
    MAXIMUM = MAX(FILTER_DATA.CLOSE);
    MEAN = AVG(FILTER_DATA.CLOSE);
    CNT = COUNT(FILTER_DATA.CLOSE);
    CSQ = FOREACH FILTER_DATA GENERATE CLOSE * CLOSE AS (CC:DOUBLE);
    GENERATE group.$0 AS (SYMBOL:CHARARRAY), MINIMUM AS (MIN:DOUBLE), MAXIMUM AS (MAX:DOUBLE), ROUND_TO(MEAN,6) AS (MEAN:DOUBLE), ROUND_TO(SQRT(SUM(CSQ.CC) / (CNT * 1.0) - (MEAN * MEAN)),6) AS (STDDEV:DOUBLE), group.$1 AS (YEAR:INT);
};


text:
Q: How do I set GUID / UUID as primary (and not clustered) key in MySQL? Reason I'm using GUID / UUID as primary key: Data syncing across devices. I have a master database on the server, and then each device has its own database with the same structure (although, different engines. MySQL on the server, SQLite on the Android devices, etc).
I've read that if you're going to use GUID's as your primary key, it should at least not be the clustering key. However, I can't find how to do that with MySQL. All I can find is this reference that says if you have a primary key, InnoDB will use it as the clustering key.
Am I missing something?

A: The article you linked to is about Microsoft SQL Server, which gives you the option of which index to use as the clustering key.
With MySQL's InnoDB storage engine, you have no option. The primary key is always used as the clustering key. If there is no primary key, then it uses the first non-null unique key. Absent any such unique key, InnoDB generates its own internal 6-byte key as the clustering key.
So you could make a table that uses a GUID as a non-unique key, but in practice use it as a candidate key.
CREATE TABLE MyTable (
  guid CHAR(32) NOT NULL,
  /* other columns... */
  KEY (guid) -- just a regular secondary index, neither primary nor unique
);

However, there's a legitimate use for the clustering key. If you frequently do lookups based on the GUID, they will be more efficient if you use the GUID as the clustering key.
The concerns about using a GUID as the clustering key are mostly about space. Inserting into the middle of a clustered index can cause a bit of fragmentation, but that's not necessarily a huge problem in MySQL.
The other issue is that in InnoDB, secondary indexes implicitly contain the primary key, so a CHAR(32) or whatever you use to store the GUID is going to be appended to each entry in other indexes. This makes them take more space than if you had used an integer as the primary key.


text:
Q: What is the use of UIScreen property in UIWindow? I was looking at the UIWindow class reference and there I found the UIScreen property which defaults to [UIScreen mainScreen]
@property(nonatomic,retain) UIScreen *screen NS_AVAILABLE_IOS(3_2);
// default is [UIScreen mainScreen]. changing the screen may be an expensive operation and should not be done in performance-sensitive code

We initiailise the UIWindow object with the UIScreen in AppDelegate
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]

I am wondering why do we need the UIScreen property in UIWindow

A: By default, all windows are created on the primary device screen. If additional screens are attached to the device, assigning a different screen object to this property causes the window to be displayed on the new screen.
As per Apple docs:

Moving windows from screen to screen is a relatively expensive operation and should not be done in performance-sensitive code. Instead, it's recommended that you change the screen before displaying the window the first time. Changing the screen of a window that has not yet been ordered onto the screen has no significant additional cost.

A: UIScreen refers to the device frame.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScreen_Class/index.html
You can get the device size for finding the Devices iPhone 4,iPhone 5, iPhone 6, iPhone 6+ & iPad
[[UIScreen mainScreen] bounds] //gives u the size of the device.
You can differentiate the devices as per above sizes.
[[UIScreen mainScreen] bounds].size.width //gives the width of device
[[UIScreen mainScreen] bounds].size.height) //gives the height of device.
Or you can use in this way
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

Hope it helps you...

A: From IOS Developer Library
self.window is assumed to be a declared property of your application delegate that is configured to retain the window object. If you were creating a window for an external display instead, you would assign it to a different variable and you would need to specify the bounds of the non main UIScreen object representing that display.
When creating windows, you should always set the size of the window to the full bounds of the screen. You should not reduce the size of the window to accommodate the status bar or any other items. The status bar always floats on top of the window anyway, so the only thing you should shrink to accommodate the status bar is the view you put into your window. And if you are using view controllers, the view controller should handle the sizing of your views automatically.

A: A UIScreen object defines the properties associated with a hardware-based display. iOS devices have a main screen and zero or more attached screens. Use this class to obtain screen objects for each display attached to the device. Each screen object defines the bounds rectangle for the associated display and other interesting properties such as its brightness. For more refer this docs

A: Your application has only one UIWindow where all other view's draw's. When application
begins UIWindow covers the entire screen space. This is the reason when you instantiate
UIWindow you have to set it's frame size to Main Screen bounds size.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds];

What is the role of UIScreen here ?
UIScreen represents rectangles of device screen. Your UIScreen knows more about
your device screen attributes like resolution, pixel aspect ratio, brightness, dimming.
On other side UIWindow manages your view hierarchy and help views to display contents on the screen. UIWindow during initialisation gets it's frame from UIScreen bound property and initialises it self so that it can have maximum landscape from device screen to give it to subviews. Once initialisation done UIWindow frame includes status bar plus drawing area plus bottom bar.


text:
Q: Apollo Server gql usage recommendation I've been implementing a GraphQL server for the first time. While reading the documentation, I found the recommendation to use gql with typeDefs (https://www.apollographql.com/docs/apollo-server/migration-two-dot#existing-schema). I know the purpose of gql but I don't understand why its needed with Apollo Server if the constructor parses typeDefs internally. My code works with and without it.
Why is gql recommended to be used?

Update v1
Due to the combination of using gql with tools like eslint, I immediately noticed the benefits described in the answer. Without gql, available tools aren't smart enough to differentiate between a template string and graphql.

A: This is really just a design choice on the part of the Apollo team. graphql-tools, which is what apollo-server uses under the hood, supports a number of types for the typeDefs parameter, including a function:
export type ITypeDefinitions = ITypedef | ITypedef[];
export type ITypedef = (() => ITypedef[]) | string | DocumentNode;

Because the constructor ApolloServer effectively just passes your typeDefs to graphql-tools' makeExecutableSchema, you can get away with passing in your schema's type definitions as a string or a function and it will still work. At least in JavaScript. The TypeScript definitions actually explicitly specify DocumentNode as the type, so if you were using TypeScript, it'd be a no-go.
Why does apollo-server explicitly require you to pass in a DocumentNode (which is what graphql-tag returns)? As one of the Apollo devs points out in this PR:

Supporting non-tagged-template-literals strings as typeDefs... makes it possible to define a document without a gql tag, which might be tempting, but it's worth reminding ourselves that there's some value to that tag since it makes it easier to do static analysis, automatic detection of string manipulation/variable interpolation (which is often an anti-pattern) and provides more ubiquitous editor syntax highlighting support.

If you're passing in typeDefs, you should make sure you're passing them in as a DocumentNode, and the easiest way to do is using the gql tag. Passing in one of the other types may appear to work, but the documentation and the type definitions make it clear you shouldn't do that. Keep in mind that Apollo Server could always introduce logic in future releases that results in unexpected behavior when the wrong type is passed in, if such code doesn't already exist.


text:
Q: Gcalcli is an invalid command after install Edit: As seen in comments gcalcli is installed in an other path than /usr/local/bin - so the sudo ln -s is not adviced. Check out Gcalcli - no module named gdata.calendar.service
I've installed gcalcli via sudo apt-get install gcalcli but somehow gcalcli agenda gives the following:
Error: [gcalcli] is an invalid commandUSERNAME@COMPUTER:~$
Yes, it is inline. When i write gcalcli --help I get the following peculiar output
Usage:

/usr/local/bin/gcalcli [options] command [command args or options]

alongwith the standard output.
I think i screwed up following this installation: http://www.linuxjournal.com/content/command-line-cloud-gcalcli
Where it specifies:
sudo ln -s ~/src/gcalcli/gcalcli /usr/local/bin/gcalcli
This may have put it in the wrong path or something?

A: Just found a solution that worked for me posted on github project page:
If you happen to have a .gcalclirc file in your home dir, remove it an run gcalcli again. It should redirect you to Google on your web browser to allow gcalcli to use your Google calendar data.


text:
Q: sort list on multiple attribute in multiple order in python in c++ style of sorting listOfDict = [{"sal":1000,"age":25},{"sal":1000,"age":24},
   {"sal":1000,"age":26},{"sal":2000,"age":25},{"sal":3000,"age":24}]
Expected o/p : [{"sal":3000,"age":24}, {"sal":2000,"age":25}, {"sal":1000,"age":24}, {"sal":1000,"age":25},{"sal":1000,"age":26}]
I want to sort this in decreasing order of salary and increasing order of age.
I tried c++ style like this:
def auxsort(p1data, p2data):
    if p1data['sal'] > p2data['sal']:
        return True
    if p1data['age'] <= p2data['age']:
        return True
    return False

sorted(listOfDict,key=auxsort)

But this is not allowed in python.
TypeError: auxsort() takes exactly 2 arguments (1 given)
How to solve this?
Thank you

A: You used the key wrong. It should take an element from listOfDict and return something that can directly compare against each other. I suggest the following instead:
def auxsort(p1data):
    return (-p1data['sal'], p1data['age'])

this returns a tuple of two elements. If tuples t1 < t2 is means the element they correspond to also have such ordering in the sorted output.


text:
Q: Prove: The null space is equal to the orthogonal complement of the image space I need to prove:

Let $V$ be a real linear space with an inner product. Prove that if $A:V\to V$ is a symmetric linear operator, then the null space of $A$ is orhogonal to the image space of $A$.

I only have $N \subseteq R^\perp$: Take a random $x\in N$ and a  random $y\in R, y=Au$. Then $(x,y)=(x,Au)=(Ax,u)=(0,u)=0 \implies x\in  R^\perp \implies N\subseteq R^\perp$
Edit: But I still need to prove the other side

A: To prove the stronger statement you indicate after the question in the highlighted box, note that
\begin{align}
    w \in \mathcal{R}(A)^{\perp} &\iff (Av,w)=0\;\forall v\in V \\
                      &\iff (v,Aw)=0\;\forall v\in V \\
                      &\iff Aw=0
\end{align}
The last equivalence holds because $Aw=0$ implies $(v,Aw)=0$ for all $v$, and because, if $(v,Aw)=0$ for all $v\in V$, then it holds for $v=Aw$, which implies $Aw=0$. Therefore,
$$
       \mathcal{R}(A)^{\perp} = \mathcal{N}(A).
$$
Hence,
$$
              V = \mathcal{R}(A)\oplus\mathcal{R}(A)^{\perp}=\mathcal{R}(A)\oplus\mathcal{N}(A).
$$

A: Let $x \in R^{\perp}$, then $(x,Av)=0$, for all $v\in V$.
In particular, $(Ax,Ax)=(x,AAx)=0$, so $Ax=0$ and $x\in N$.
Therefore $R^{\perp}\subset N$


text:
Q: SQL Server Last week from sun to sat I am trying to get date from Sun to sat of last week my code is,
Declare
      @now DateTime, @fmWeek DateTime, @toWeek DateTime

Set @now = GetDate()
Set @fmWeek = Convert(DateTime, DateAdd(wk, DateDiff(wk, 0, @now), -1))
Set @toWeek = DATEADD(ms,-3,Convert(DateTime, DateAdd(wk, DateDiff(wk, 0,  @now), 6)))

select @fmWeek, @toWeek

It shows me data from 2018-04-15 00:00:00.000 to 2018-04-21 23:59:59.997
I need to get dates from previous week sun to sat not the same week

A:
I need to get dates from previous week sun to sat not the same week

I would just substract 7 days:
Declare @now DateTime = GetDate()
    ,@fmWeek DateTime, @toWeek DateTime;

Set @fmWeek = DateAdd(wk, DateDiff(wk, 0, @now), -1) - 7;
Set @toWeek = DateAdd(wk, DateDiff(wk, 0, @now), 5) - 7;
select @fmWeek, @toWeek;

DBFiddle Demo

A: If you want to show only two dates, @lad2025 have given you the correct query to get the dates.
In case you want to show all the dates bewteen these two days, you can try like following.
Declare @now DateTime = GetDate()
    ,@fmWeek DateTime, @toWeek DateTime;

Set @fmWeek = DateAdd(wk, DateDiff(wk, 0, @now), -1) - 7;
Set @toWeek = DateAdd(wk, DateDiff(wk, 0, @now), 5) - 7;

SELECT @fmWeek + RN AS DATE FROM
(
    SELECT (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)))-1 RN
    FROM   master..[spt_values] T1
) T
WHERE RN <= DATEDIFF(DAY,@fmWeek,@toWeek)

Output:
Date
------------------------
2018-04-08 00:00:00.000
2018-04-09 00:00:00.000
2018-04-10 00:00:00.000
2018-04-11 00:00:00.000
2018-04-12 00:00:00.000
2018-04-13 00:00:00.000
2018-04-14 00:00:00.000


text:
Q: Update database from 2 tables with c# Worked with phpMyAdmin and c#.
I wanted to update database in the phpMyAdmin with c#. But, I had an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from bucket inner join color on bucket.color_idcolor = color.idcolor' at line 1

In the phpMyAdmin, I had 2 tables in the same database: bucket and color. In the bucket table, I had column: idbucket, volume, and color_idcolor. While in the color table, I had column: idcolor and name.
In c#, I made an windows form, where the users can update the database. They can update volume (textbox) and color (combobox), and press Save button to store the update to the database. This is a few parts of my code:
private string idBucket;
private string volume;
private string color;

public void TransferData(string idBucket, string volume, string color)
{
    this.idBucket = idBucket;
    this.volume = volume;
    this.color = color;
}

MySqlConnection conector = new MySqlConnection();

public frmChangeBucket()
{
    InitializeComponent();
    conector.ConnectionString = "server=localhost; database=bucket; uid=root";
}

void ContentCboColor()
{
    conector.Open();

    MySqlCommand comand = new MySqlCommand();
    comand.Connection = conector;
    comand.CommandType = CommandType.Text;
    comand.CommandText = "select idcolor, name from color";

    MySqlDataAdapter da = new MySqlDataAdapter();
    DataTable dt = new DataTable();

    da.SelectCommand = comand;
    da.Fill(dt);
    cboColor.DisplayMember = "name";
    cboColor.ValueMember = "idcolor";
    cboColor.DataSource = dt;

    conector.Close();
}

private void btnSave_Click(object sender, EventArgs e)
{
    conector.Open();

    MySqlCommand comand = new MySqlCommand();
    comand.Connection = conector;
    comand.CommandType = CommandType.Text;

    int result = 0;

    volume = txtVolume.Text;
    color = cboColor.SelectedValue.ToString();

    comand.CommandText = "update bucket set volume=@volume, color=@color.name, from bucket "
    + "inner join color on bucket.color_idcolor = color.idcolor "
    + "where idBucket=@idbucket";

    komen.Parameters.AddWithValue("@idbucket", idBucket);
    komen.Parameters.AddWithValue("@volume", volume);
    komen.Parameters.AddWithValue("@color.name", color);
    result += comand.ExecuteNonQuery();
    comand.Parameters.Clear();

    if (result > 0)
    {
        MessageBox.Show("You've changed " + result + " data");
    }
    else
    {
        MessageBox.Show("You haven't changed any data");
    }

    conector.Close();
    this.Close();
}

In c#, I just displayed color name in combobox. First, users can display a few data from database. I used inner join to display color name. To store the update to database, do I have to inner join again? Please answer with the right code. Thanks for your help.

A: Instead trying to save text in the int field(color=@color.name)
you should use:
"color_idcolor = color.idcolor"

basically:
    comand.CommandText = "update bucket set volume=@volume, color_idcolor=@color.idcolor "
        + "where idBucket=@idbucket";
    comand.Parameters.AddWithValue("@idbucket", idBucket);
    comand.Parameters.AddWithValue("@volume", volume);
    comand.Parameters.AddWithValue("@color.idcolor", color);
    result += comand.ExecuteNonQuery();
    comand.Parameters.Clear();

A: Your command should be;
comand.CommandText = "update bucket "
+ "inner join color on bucket.color_idcolor = color.idcolor "
+ "set volume=@volume, color_idcolor=@color.idcolor"
+ "where idBucket=@idbucket";

Remove the , from bucket after color=@color.name and the INNER JOIN should come after UPDATE and before SET

A: One issue is the from bucket in your update statement - it needs to be removed.
Another issue is the join - try to replace the join by a subquery:
update bucket
    set volume=@volume,
        color_idcolor=@color.idcolor
where idBucket=@idbucket and
bucket.color_idcolor in (select color.idcolor from color)

Put this into the command text, and it should look like this:
comand.CommandText =
    "update bucket " +
    "set volume=@volume, " +
    "    color_idcolor=@color.idcolor " +
    "where idBucket=@idbucket " +
    "and bucket.color_idcolor in (select color.idcolor from color)";

Then replace
komen.Parameters.AddWithValue("@color.name", color);

by:
komen.Parameters.AddWithValue("@color.idcolor", colorId);

Finally, since you have the color name rather than the color id, the proper color id can be looked up earlier by a separate command select color.idcolor from color where color.name = @color.name.
The code for this could be like:
string SelectItem(MySqlConnection conn, string Name)
{
 string result="";
 using (MySqlCommand cmd = new MySqlCommand())
 {
  cmd.Connection = conn;
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "select top 1 color.idcolor from color where color.name = @color.name";
  cmd.Parameters.AddWithValue("@color.name", Name);
  result=cmd.ExecuteScalar().ToString();
 }
 return result;
}

With this function you can obtain the color Id
var colorId = SelectItem(conector, color);

N.B.: This function assumes that the database connection is already open.

A:  comand.CommandText = "update bucket set volume=@volume, color=@color.name, from bucket "
    + "inner join color on bucket.color_idcolor = color.idcolor "
    + "where idBucket=@idbucket";

In update query from keyword will not come and update query you can't use join queries.


text:
Q: wordpress tag archive, sort order with custom post type I added this code added to funtions.php
function tc_tag_for_cpt($query) {
  if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
    $post_type = get_query_var('post_type');
    $post_type = ($post_type) ?  $post_type : array('resources','post','page');     //,'nav_menu_item'
    $query->set('post_type',$post_type);
    return $query;
  }
}
add_filter( 'posts_orderby', 'sort_query_by_post_type', 10, 2 );
function sort_query_by_post_type( $sortby, $thequery ) {
    if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
        $thequery->set('orderby','post_type');
        if ( !empty($thequery->query_vars['post_type']) && isset($thequery->query_vars['orderby']) && $thequery->query_vars['orderby'] == 'post_type' )
            $sortby = "find_in_set(post_type, '" . implode( ',', $thequery->query_vars['post_type'] ) . "')";
    }
    return $sortby;
}

which is supposed to display results on the tag archive sorted by post type (resources is a custom post type).
It does this but an error message appears on the top of the screen:
"Warning: implode() [function.implode]: Invalid arguments passed in /home/csleh3/public_html/sandbox/wp-content/themes/aodmarketing/functions.php on line 279"
which is the "implode" line.
My goal is to have the results on the tag archive sort the list by post type, not date or title.

A: $thequery->query_vars['post_type'] will return the specific post_type as a string like post. You can't implode that.
You should just be able to remove the part about trying to implode it:
$sortby = "find_in_set(post_type, '" . $thequery->query_vars['post_type'] . "')";


text:
Q: Git config issue w/VSCode and Ubuntu After some trial and error I was able to change the permissions of the .gitconfig file in my local users /home/ directory. This permission change allowed me to add both user.name and user.email. I apologize if this wasted anyone's time and I do appreciate all of the help. Specifically @phd, @jD3V and @VonC
I am really banging my head against my desk with this one.
I have a remote GitHub repo that I have cloned locally to my machine and I am making edits to the playbook. When I go to commit the changes to GitHub VSCode throws an error:
*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: no email was given and auto-detection is disabled
[2022-04-23T18:08:35.512Z] > git config --get-all user.name [1ms]

I have run into this issue before, no big deal. This is a fresh install of Pop!_OS so I had not yet edited my git config. I enter the following -
git config --global user.name My_GitHub_Username

Followed by -
git config --global user.email My_email_name@gmail.com

When entered they both seem to run correctly as I do not get any errors thrown when entered. However when I check the git config with git config --list nothing returns in the terminal. When I run it again running as root, I see my username -
username@pop-os:~$ sudo git config --list
user.name=My_GitHub_username
user.email=My_email_name@gmail.com

Trying to commit the code again throws the same error. I have checked similar threads/solutions here, here and here, all of which have not solved my issue.
I forgot to include initially that I have tried running both as sudo and have the same results. Here is the output of `sudo nano ~/.gitconfig -
[alias]
    lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
    lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
    lg = !"git lg1"
[color]
    ui = true
[help]
    autocorrect = 3

Would I just go ahead and add the [user] alias with the user.name and user.email options filled in?
Any ideas what I might be doing incorrectly? I am not super familiar with git but would love any and all advice.

A: To exand on the comment, git config --global do modify ~/.gitconfig, which is /home/<you>/.gitconfig.
That differs from sudo xxx, which executes command as root.
root home folder is /root.
And /root/.gitconfig was not modified by your initial git config commands.
In general, not using root, is possible, is a sensible route to follow.


text:
Q: React .useEffect При старте приложения,useEffect срабатывает ,в тот момент когда происходит инициализация State.
const [token, tokenSort] = useState(false);

Так как useEffect связан по token. В дальнейшем если изменяется token, useEffect отрабатывает. Вопрос можно ли каким то образом отменить первое срабатывание, при инициализации useState?
  useEffect(() => {

 }, [token]);

A: Сам useEffect такого не предусматривает, но можно ref использовать, например
const someFunction = () => {

    const changeCounter = useRef(false);

    useEffect(() => {

        if(changeCounter.current){

            // ...Ваш обработчик

        }

        changeCounter.current = true;

    }, [token]);

}


text:
Q: How to preserve shared variable value upon calling multiply python files sequentially by the main py file? I have 4 python files in one project folder. main.py first.py second.py variables.py
I only run main.py. This file sequentially calls first.py, then second.py. Then, main.py, first.py and second.py imports variables.py.
The content of variables.py is simply the declaration of a "shared" variable across the three.
I wanted first.py to modify this shared variable and then I want this change to be carried over when the process goes back to main.py (after returning from first.py) and when the second.py is finally called.
I initially thought I would be able to do this since the variable was declared in a separate py file, but its not working.
My understanding of what's happening is:

*

*first.py imports variables.py. This action causes the variable to be declared with it's value set to initial.

*first.py modifies this shared variable.

*first.py execution ends and goes back to main.py. At this point, I see that the value of shared variable is back to initial. Why is that? Is it because first.py execution ends? But why did it happen even if the shared variable is declared in another python file?

I appreciate anyone who can enlighten me on what's happening (how the shared variable is stored in memory, what script will determine is lifetime, ending which script will end this variable, etc..). And I appreciate suggestions on how do I go about this. At this point, I am already considering on simply writing the modified shared variable value (on first.py) to an external text file then simply read and re-initialize when second.py is called later.
My codes are below. To run the project, simply run main.py

*

*main.py

    import subprocess
    import os
    import variables

    programs = ['first.py', 'second.py']
    path=os.getcwd() + '\\running multiple py with shared variables\\'
    for program in programs:
        subprocess.run(['python', path+program])
        print('running main.py')
        print(variables.shared_variable)

*first.py

    import variables
    print('running first.py')
    variables.shared_variable = 'First modification'
    print(variables.shared_variable)

*second.py

    import variables
    print('running second.py')
    print(variables.shared_variable)

*variables.py

    shared_variable = "Initial value"

Output of program on terminal:
running first.py
First modification
running main.py
Initial value                   -> I really want this to be "First
                                   modification"
running second.py
Initial value                   -> I really want this to be "First
                                   modification"
running main.py
Initial value                   -> I don't really care here but I honestly
                                   expected this to be "First modification"
                                   as well` ```

A: There's no shmem() shared memory going on here.
    for program in programs:
        subprocess.run(['python', path + program])

You spawned a pair of child processes.
Which each computed a result.
And then called exit(), discarding the result.
If the child doesn't serialize a result
which the parent parses, then
the result is gone forever.
The symptoms you report are exactly what is expected.

The good news is that you have excellent skills
for thinking about this problem analytically,
and reporting
to others what happened.
So I am confident you will soon implement a
satisfactory solution.

A: Credits to @J_H for mentioning shared memory concept.
I was able to solve my problem using shared_memory class from multiprocessing module.
I am sharing the modified code. With this implementation, the file variables.py is not even needed since you need to track only the decided name of the shared memory block (shared_memory1 here). If you don't specify it, it will be auto-generated which you can check in the object attributes.

*

*main.py

import subprocess
import os
import variables
from multiprocessing import shared_memory

shm = shared_memory.SharedMemory(create=True, size=500, name='shared_memory1')
programs = ['first.py', 'second.py']
path=os.getcwd() + '\\running multiple py with shared variables\\'
for program in programs:
    subprocess.run(['python', path+program])
    print('running main.py')
    ctr = 0
    retrieved_val = ''
    while (shm.buf[ctr] != 0):
        retrieved_val = retrieved_val + chr(shm.buf[ctr])
        ctr = ctr + 1
    variables.shared_variable = retrieved_val
    print(variables.shared_variable)

shm.close()
shm.unlink()

*first.py

import variables
from multiprocessing import shared_memory

shm = shared_memory.SharedMemory(name='shared_memory1')

print('running first.py')
variables.shared_variable = 'First modification'

ctr = 0
for val in variables.shared_variable:
    shm.buf[ctr] = ord(val)
    ctr = ctr + 1
print(variables.shared_variable)

shm.close()

*second.py

import variables
from multiprocessing import shared_memory

shm = shared_memory.SharedMemory(name='shared_memory1')
ctr = 0
retrieved_val = ''
while (shm.buf[ctr] != 0):
    retrieved_val = retrieved_val + chr(shm.buf[ctr])
    ctr = ctr + 1
print('running second.py')
variables.shared_variable = retrieved_val
print(variables.shared_variable)

shm.close()

*variables.py

shared_variable = "Initial value"

Terminal output after running main.py:
running first.py
First modification
running main.py
First modification
running second.py
First modification
running main.py
First modification


text:
Q: Defining Scope in C++ OOP Program I am trying to get better at C++ by challenging myself by creating a program that manages employees. Given a certain salary vs. sales you will either be hired, fired or keep your job. I have been working with OOP a lot recently and thought that structuring it by class would make the exercise easier. I've gone over this again and again and I can't seem to find a solution. That being said I would very much appreciate some insight on what I am doing wrong. Keep in mind I am new to C++ and OOP but the more I learn the better I will be in the future.
Originally it was all one file then I separated the classes into header files. It seems to run a little smoother now but I still get the error that name, salary and scope (my variables) aren't defined in the scope of my program.

main.cpp

#include "Boss.h"
#include "Employee.h"
#include "PotentialEmployee.h"
#include <iostream>

using namespace std;

int main ()
{

  Boss Boss1;
  Boss Boss2;
  Boss Boss3;

  Employee Employee1;
  Employee Employee2;
  Employee Employee3;

  PotentialEmployee PotentialEmployee1;
  PotentialEmployee PotentialEmployee2;

  Employee1.name = "Michael";
  Employee2.name = "John";
  Employee3.name = "Lisa";

  Boss1.name = "Luke";
  Boss2.name = "Ben";
  Boss3.name = "Jack";

  PotentialEmployee1.name = "Bill";
  PotentialEmployee2.name = "Fred";

  Employee1.salary = 55000;
  Employee2.salary = 65000;
  Employee3.salary = 75000;

  Boss1.salary = 88000;
  Boss2.salary = 95000;
  Boss3.salary = 88000;

  PotentialEmployee1.salary = 55000;
  PotentialEmployee2.salary = 65000;

  Employee1.sales = 12000;
  Employee2.sales = 40000;
  Employee3.sales = 80000;

  Boss1.sales = 200000;
  Boss2.sales = 250000;
  Boss3.sales = 280000;

  PotentialEmployee1.sales = 55000;
  PotentialEmployee2.sales = 65000;

  if (sales <= salary)
    std::cout << "I'm sorry " << name << "you have been fired";

  else if (sales >= salary)

      std::cout << "Good job " << name << "you get a bonus";

   else
      std::cout << "Try and do better next quarter";

      return 0;
    }

main.cpp: In function 'int main()': main.cpp:66:7: error: 'sales' was
  not declared in this scope if (sales <= salary) { ^ main.cpp:66:16:
  error: 'salary' was not declared in this scope if (sales <= salary) {
  ^ main.cpp:67:34: error: 'name' was not declared in this scope
  std::cout << "I'm sorry " << name << "you have been fired"; ^
  main.cpp:71:35: error: 'name' was not declared in this scope std::cout
  << "Good job " << name << "you get a bonus";

A: As the error tries to tell you there is no sales and no salary declared in main. You probably want to refer to the Employees sales and salary, that would be
if (Employee1.sales <= Employee1.salary)
    std::cout << "I'm sorry " << name << "you have been fired";

Some more tips:

*

*better use small starting letters for object names and capitals for types. In your code it is not easy to see what is a variable and what is a type.

*whenever you find yourself naming variables foo1, foo2, foo3 etc you should use a std::vector or an array instead. This will help you to loop over all employes and evaluate their sales/salary.

*the {} for if and else are optional, but it is often better to write them any way.

*your two cases are not exclusive. If sales == salary then both conditions would be true, but only the first one will get evaluated. Hence there is a tiny confusion: Looking at the else condition one might expect that a employee with sales == salary did a good job, but they will get fired :(

*last and least, a company that keeps their employess even if they generate zero income is a very nice one :)

PS:

I was hoping to do it in a more general way where I wouldn't have to
  write out Boss1, Boss2, Boss3 each time but it looks like that's the
  best way to do it

When you find yourself writing a block of code that has lots of Boss1.some_member then that block of code is a good candidate to be actually implemented in a member function (where you dont need to prefix the object). Eg the employee could have a bool Employee::evaluate_salary_vs_sales(); that contains the logic you now have in main and returns whether they get fired or not.


text:
Q: Combinations of elements of multiple arrays I have this type of data
var arr = [
    ["A", "AA"],
    ["B"],
    ["C", "CC", "CCC"]
];

I want to get combinations of all the elements within each array. for e.g.
A B
A B C
A B CC
A B CCC
A C
A CC
A CCC
...
AA B CCC

Note the sequence of the words are same, like this should not be one of the combination B A C.
I tried a couple of logics but can't get what I am looking for. I can obtain all permutations and combinations of all the words, but that's not what I am looking for.
Please suggest

A: You basically want to permute across multiple lists:
function permute(input)
{
  var out = [];

  (function permute_r(input, current) {
    if (input.length === 0) {
      out.push(current);
      return;
    }

    var next = input.slice(1);

    for (var i = 0, n = input[0].length; i != n; ++i) {
      permute_r(next, current.concat([input[0][i]]));
    }
  }(input, []));

  return out;
}

permute(arr);

A: The problem can be solved recursively. That is: for the first array, you have, for each of the elements, the result of the combinations formed with the two other arrays.
Something like this could work:
function arrayCombine ( array ) {
    if (array.length > 1) {
        var result = new Array();

        //This combines all the arrays except the first
        var otherCombs = arrayCombine ( array.slice(1) );

        for ( var n = 0; n < array[0].length; n++ )
            for ( var i = 0; i < otherCombs.length; i++ )
                result.push ( array[0][n] + otherCombs[i] );

        return result;
    }

    //If we have only one array, the result is the array itself, for it contains in itself all the combinations of one element that can be made
    else return array[0];
}

A: *

*Make an array of indices (idx), each element corresponding to each row. Initial value 0.

*Start with index i = 0

*Do what you do with the current combination.

*Increment idx[i]. If it's less than the length of the row, go to 2

*Set idx[i] to zero

*Increment i. If it's greater than the number of rows, terminate algorithm, otherwise go to 2


text:
Q: Can you run a thread in another thread? In my programm, I want to run two seperate thread, which are initalized and launched in the main thread. This concept works fine for me, but when I now have to make a cooldown on one of the child threads while it is not paused it seems to still pause the thread;
Think of this as an example:
#include <iostream>
#include <thread>

class testClass {
    static void grandchild();
    static void child();
public:
    void parent();
};

void testClass::grandchild() {
    //infinite loop of nothing;
    while (true);
}

void testClass::child() {
    //thread initalising and
    std::thread grand(&testClass::grandchild);
    std::cout << "before join" << std::endl;
    grand.join();
    std::cout << "after join" << std::endl;
}

void testClass::parent() {
    std::thread child(&testClass::child);
    child.join();
}
int main() {
    testClass parentclass;
    parentclass.parent();
}

The output of this program now is

This also happens when I do this_thread::sleep_for and other functions which pause a thread. Can anyone explain me why this happens and what is possible for me to implement this properly or if this is even possible in C++?

A: .join() means "wait until that thread finishes". parent waits for child and child waits for grandchild and grandchild is stuck in an infinite loop, therefore nothing happens. You are effectively running single-threaded because you join with the threads you spawn.
You could not wait by using .detach() instead of .join(), but you should join all the threads before returning from main.

A: Here is a modified program that uses the grandchild thread to wait for 3 seconds before changing a value.
The child thread keeps running.
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>

class testClass {
public:
    void grandchild();
    void child();
    void parent();
    std::atomic<int> value{0};
};

void testClass::grandchild()
{
    std::this_thread::sleep_for(std::chrono::seconds(3));
    value = 5;
}

void testClass::child()
{
    //thread initalising and
    std::cout << "Starting grandchild thread.\n";
    std::thread grand(&testClass::grandchild,this);
    //grand.detach(); // could detach so that a join() will not be required later
    for (int x{0}; x<5; ++x) {
        std::cout << x << '\t' << value << '\n';
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    grand.join();
}

void testClass::parent()
{
    std::cout << "Starting child thread.\n";
    std::thread child(&testClass::child, this);
    child.join();
}
int main()
{
    std::cout << "Starting program\n";
    std::cout << "Starting parent thread.\n";
    testClass parentclass;
    parentclass.parent();
}

output:
Starting program
Starting parent thread.
Starting child thread.
Starting grandchild thread.
0       0
1       0
2       0
3       5
4       5

live demo

A: This program is behaving correctly.

*

*It displays "before join".

*It then waits until the infinite while(1) loop finishes.

*After an infinite time, it displays "after join".
If you intend different behaviour, perhaps you could explain what that different behaviour is.


text:
Q: .NET Best Method to Send Email (System.Net.Mail has issues) This seems to be pretty straight forward. I need to send email from some ASP.NET applications. I need to do this consistently without strange errors and without CPU utilization going through the roof. I'm not talking about mass emailing, just occasional emails.
System.Net.Mail appears to be horribly broken. The SmtpClient does not issue the Quit command (it may be because Microsoft(R) is not interested in following specifications), therefore a connection is left open. Therefore, if someone tries to email before that connection finally closes, you can get errors from the SMTP Server about too many connections open. This is a bug that Microsoft(R) is completely uninterested in fixing. See here:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=146711
Also, if you look around some suggest to use this code to solve this problem:
smtpClient.ServicePoint.MaxIdleTime = 1;
smtpClient.ServicePoint.ConnectionLimit = 1;

Ok, yes that does "solve" the problem of connections being left open. However, this consistently, try it on a server if you like, causes the CPU on which the process (in this case w3wp.exe) is running to jump and remain at 100% until your application pool is recycled. For whatever reason, the thread that runs mscorwks.dll!CreateApplicationContext is the culprit.
This has the very nice side effect that if you are running on a web host that frowns on sustained 100% CPU usage, you will get your application pool disabled. So this is not as trivial as some suggest.
So my question is what to do? What I need to do is so simple; however getting those "too many connections open" errors is not acceptable and nor is the 100% CPU usage. I don't want to purchase a third party component, not because I'm cheap, but I buy enough components  and MSDN subscription that it seems crazy to have to shell out $100-$300 for simple SMTP functionality.
I read that setting the MaxIdleTime higher can help but I'm skeptical of that. I don't want to risk my app pool being disabled just because Microsoft doesn't want to follow the SMTP specification.
Edit:  I looked at quiksoft.com components, however it does not support SMTP authentication and it costs $500. There's got to be a solution to this problem.

A: In .NET 4.0, SmtpClient is now disposable.  The SMTP QUIT command is issued upon disposal such as when used in a using block.

A: I faced the same CPU utilization problem with the settings described. I ended up opening a ticket with Microsoft to determine the cause of the problem. The CPU utilization problem lies in the ServicePoint class. Internally in the ServicePoint class, there is a timer that runs every (MaxIdleTime/2) milliseconds. See the problem? By changing the MaxIdleTime value to 2, the CPU utilization will drop down to normal levels.

A: I've always used Quiksoft's EasyMail .NET components with no issues at all.
Product home page: http://www.quiksoft.com/emdotnet/
They also have a free version of the component if you only need to send out e-mails:
http://www.quiksoft.com/freesmtp/

A: We have used hMailserver with great success.  The configuration can take a while to get used to but it has been a great -- and free -- mail server product.
If you want to roll your own (which I did years ago when I was having a bear of a time with CDONTS), you can start with the code below and customize to your heart's content.  It uses the TcpClient to create a TCP connection directly to the mailserver.  Not that I'd recommend this when there are so many established and debugged solutions, but I found this very useful for debugging and determining where the problem was with the prefab MS mail components.
    private void Send_Email()
    {
        #region Email Sending Function
        string strMail = "";

        try
        {
            // See RFC821 http://www.faqs.org/rfcs/rfc821.html for more specs
            // TcpClient is an abstraction of a TCP Socket connection
            TcpClient myTCP = new TcpClient();

            // Connect to the mail server's port 25
            myTCP.Connect(mailserver, 25);

            // Open a network stream which sends data to/from the TcpClient's socket
            System.Net.Sockets.NetworkStream ns = myTCP.GetStream();

            // The data to send to the mail server, basically a raw SMTP mail message
            strMail = "HELO\n";
            strMail += "MAIL FROM:from@address.com\n";
            strMail += "RCPT TO:" + recipient + "\n";
            strMail += "DATA\n";
            strMail += "Subject: mySubject\n";
            strMail += "To:" + recipient + "\n";
            strMail += "From: \"From Real Name\" <from@address.com>\n";
            strMail += "\n";
            strMail += " ---------------------------------------\n";
            strMail += "Name:     " + txtName.Text + "\n";
            strMail += "Address1: " + txtAddress1.Text + "\n";
            strMail += "Address2: " + txtAddress2.Text + "\n";
            strMail += "City:     " + txtCity.Text + "\n";
            strMail += "State:    " + txtState.Text + "\n";
            strMail += "Zip:      " + txtZip.Text + "\n";
            strMail += "Email:    " + txtEmail.Text + "\n";
            strMail += "Dealer:   " + txtDealer.Text + "\n";
            strMail += " ---------------------------------------\n";
            strMail += "THIS IS AN AUTOMATED EMAIL SYSTEM. DO NOT REPLY TO THIS ADDRESS.\n";
            strMail += "\n.\n";

            // Defines encoding of string into Bytes (network stream needs
            // an array of bytes to send -- can't send strings)
            ASCIIEncoding AE = new ASCIIEncoding();
            byte[] ByteArray = AE.GetBytes(strMail);

            // send the byte-encoded string to the networkstream -> mail server:25
            ns.Write(ByteArray, 0, ByteArray.Length);

            //ns.Read(ByteArray, 0, ByteArray.Length);
            //lblStatus.Text = ByteArray.ToString();

            // close the network stream
            ns.Close();

            // close the TCP connection
            myTCP.Close();
        }
        catch(Exception ex)
        {
            throw new Exception("Couldn't send email: <p>" + ex.Message);
        }

        #endregion

    }

A: While I haven't had any specific problems with System.Net.Mail so far, you can always use the older System.Web.Mail API which is a wrapper for CDOSYS.

A: I've used Quicksoft in the past and have no complaints. Another thing you can try is switching the SMTP configuration to use a pickup folder instead of sending using the network which should get around the "it doesn't send QUIT" issue.

A: I send most of my mail using a Sproc. I can even attach a file.

CREATE PROCEDURE [dbo].[sendMail_With_CDOMessage]
    @to VARCHAR(64),
    @CC VARCHAR(1024)='',
    @BCC VARCHAR(1024)='',
    @subject VARCHAR(500)='',
    @body VARCHAR(8000)='' ,
    @from VARCHAR(64),
    @filename VARCHAR(255)='',
    @priority INT = 0
AS
BEGIN
    SET NOCOUNT ON

    DECLARE
        @handle INT,
        @return INT,
        @s VARCHAR(64),
        @sc VARCHAR(1024),
        @up CHAR(27),
        @server VARCHAR(255)

    SET @s = '"http://schemas.microsoft.com/cdo/configuration/'

    SELECT
        @s = 'Configuration.Fields(' + @s,
        @up = 'Configuration.Fields.Update',
        @server = 'smtp.yourdomain.com'

    EXEC @return = sp_OACreate 'CDO.Message', @handle OUT
    SET @sc = @s + 'sendusing").Value'
    EXEC @return = sp_OASetProperty @handle, @sc, '2'
    SET @sc = @s + 'smtpserver").Value'
    EXEC @return = sp_OASetProperty @handle, @sc, @server
    EXEC @return = sp_OAMethod @handle, @up, NULL
    EXEC @return = sp_OASetProperty @handle, 'To', @to
    EXEC @return = sp_OASetProperty @handle, 'CC', @CC
    EXEC @return = sp_OASetProperty @handle, 'BCC', @BCC
    EXEC @return = sp_OASetProperty @handle, 'From', @from
    EXEC @return = sp_OASetProperty @handle, 'Subject', @subject
    EXEC @return = sp_OASetProperty @handle, 'HTMLBody', @body
    EXEC @return = sp_OASetProperty @handle, 'Priority', 'cdoHigh'

    IF @filename IS NOT NULL
        EXEC @return = sp_OAMethod @handle, 'AddAttachment', NULL, @filename

    EXEC @return = sp_OAMethod @handle, 'Send', NULL
    IF @return  0
    BEGIN
        PRINT 'Mail failed.'
        IF @from IS NULL
            PRINT 'From address undefined.'
        ELSE
            PRINT 'Check that server is valid.'
    END
    ELSE
        PRINT 'Mail sent.'

    EXEC @return = sp_OADestroy @handle
END


text:
Q: Do you have to install the REST starter kit in asp.net to access APIs? I'm currently trying to access a REST API for the first time using visual web developer 2008 express edition.
Every article I have found says you have to install the WCF REST starter kit which is a .msi file, which would suggest that I have to install it on my machine and presumably our server too.
My question is this. Is there a non installable version that I can use, e.g. just by dropping DLLs into the Bin directory and then using the classes contained. Or is there more to it than that and am I just getting very confused about how it works?
Jon

A: You'll find that the msi just installs/registers the dlls and the Visual Studio project templates for common REST scenarios. See the first section of this article.
EDIT: Once referenced (you will have to browse to the install folder of the starter kit to add the reference), the dlls will be be copied to the output directory (because the CopyLocal property of the reference in VS will be true) so when you publish the project via VS (or compile) the dlls will be included in the bin folder (so no you will not have to install the starter kit on the server also).

A: When you install the WCF REST Starter kit it will create a folder
C:\Program Files (x86)\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies

In this folder are the following DLLs.
 Microsoft.Http.dll
 Microsoft.Http.Extensions.dll
 Microsoft.ServiceModel.Web.dll

The first two are used as a client library to access HTTP based interfaces.  The third dll is an extension to WCF's System.ServiceModel.Web that fixes some of the problems with creating REST services using WCF.
The DLLs you need depend on whether you are trying to create a REST api, or consume an existing one.

A: The easiest way to use REST APIs in Visual Studio / Web Developer is to right click on your website in the Solution Explorer and go to Add Web Reference...


text:
Q: java regex match a string Here is a string
* '''A happy man is too satisfied with the present to dwell too much on the future.'''
** "My Future Plans" an essay written at age 17 for school exam (18 September 1896) ''The Collected Papers of Albert Einstein'' Vol. 1 (1987) Doc.22

I need to get the text which starts with only one * till the end of that line
Pattern pattern = Pattern.compile("\\*(.+?)\\n");
    Matcher matcher = pattern.matcher(text);
    List<String> s = new ArrayList<String>();
    while (matcher.find()) {
        s.add(matcher.group(1));
    }

I tried the above code, but it matches even 2 * and also the text from * to new line is not coming up properly, what am I missing here?

A: You can try this:
Pattern pattern = Pattern.compile("(?m)^\\*([^*].*)");

(?m) set the pattern in multiline mode where ^ means "begining of the line"
Adding \\n at the end is useless since the dot can't match a newline. (it's the reason why a lazy quantifier is useless too)

A: which will make some sense i think,
Pattern pattern = Pattern.compile("^(\\*[^*].+)");


text:
Q: Given a transformational matrix, is it possible to determine two bases? I'm relatively bad at Linear Algebra, so please bear with me here. Given to bases and a transform between them, it's relatively easy to find the corresponding transformational Matrix. However, I am having trouble doing the opposite: Given a Matrix, I am trying to find two bases of two Vector spaces. Is there any algorithm or way to think of this?
Specifically, given a linear transform $\psi : \mathbb R ^4 \to \mathbb R ^3, x\mapsto Ax$, I am asked to construct $\mathscr{B}_1$ as a base of $\mathbb R ^4 $ and $\mathscr B_2$ as a basis of $\mathbb R^3$ such that $M_{\mathscr B_2}^{\mathscr B_1} = B$.
Here, $ A= \left(\begin{matrix}3&-1&1&7\\1&1&1&5\\1&-1&0&1\end{matrix}\right) $ and $B= \left(\begin{matrix}0&0&1&0\\0&0&0&1\\0&0&0&0\end{matrix}\right)$.
What I find especially confusing about the question is that $\psi$ maps $x$ to $Ax$, and nothing concerning the matrix $B$. I must be missing something, because at the moment this question seems like guesswork.

A: If you solve the system$$A.\begin{bmatrix}a\\b\\c\\d\end{bmatrix}=(0,0,0),$$you will see that its solutions are the vectors of the form $(a,b,4a-6b,-a+b)$. So, take two such vectors which are linearly independent, such as $(1,0,4,-1)$ and $(0,1,-6,1)$. I will call them $v_1$ and $v_2$:
Since $\dim\ker A=2$, $\dim\operatorname{range}A=2$, by the rank-nullity theorem. Let $w,w^\ast\in\mathbb R^3$ two linearly independent vectors which belong to $\operatorname{range}A$, let $v_3\in\mathbb R^4$ be such that $A.v_3=w$ and let $v_4\in\mathbb R^4$ be such that $A.v_4=w^\ast$. Now, take $\mathscr B_1={v_1,v_2,v_3,v_4}$ and take $\mathscr{B}_2=\{w,w^\ast,w'\}$, where $w'$ is any vector of $\mathbb R^3$ such that $\{w,w^\ast,w'\}$ is linearly independent.
It follows from these computations that $A.v_1=A.v_2=0$, that $A.v_3=w$ and that $A.v_4=w^\ast$. In other words, the matrix of $A$ with respect to the bases $\mathscr B_1$ and $\mathscr B_2$ is the matix $B$.


text:
Q: Mean, Standard Deviation and variance I submitted this task, and just got my results. My mean was correct, but standard deviation and variance was wrong.
Could someone explain where i went wrong please? As they have not said.

A: Check your last two columns:
You have that $(-4.125)^2 = -17.01$, which is incorrect. Remember that when you square something (or multiply a negative by a negative) you always get a positive. Also, remember to round correctly; $(-4.125)^2 = 17.015625$ which rounds to $17.02$.
Check the rest of your last column for problems like these!

A: You have a single deviation smaller than $4$ (in absolute value), and yet your standard deviation is $3.85$? Yes, something's wrong here.
Squares can't be negative. Fix the signs in your last column, and it ought to get better.

A: I understand where i went wrong now, and what mistake i made. I have corrected my errors.


text:
Q: How to find the first existing file in a sequence I have several locations which may contain a file I need.
I want to find the first existing file in a vector.
Both
find.existing.file <- function (files) {
  present <- which(file.exists(files))
  stopifnot(length(present) > 0)
  files[present[1]]
}

and
find.existing.file <- function (files) {
  for (i in 1:length(files))
    if (file.exists(files[i]))
      return(files[i])
  stop("None exist: ",paste(files,collapse=" "))
}

should be doing what I need.
However, the first version checks all the files instead of returning on the first existing file, while the second uses a loop which, I think, is not very "R'y".
I was wondering whether I was missing something obvious.
Thanks.

A: here another option using regular expression, and list.files. I assume you search for a list of files in an existing directory.
function(listfiles,path)
  length(grep(paste(listfiles,collapse='|'),
              list.files(path))> 0

EDIT after OP clarification:
To search for a certain file in many location you can just list.files with a specific pattern.
For example, to search for init files in /etc, /usr/local/etc:
list.files(path= c('/etc','/usr/local/etc'),
           pattern='init.*')

A: This looks "functional" enough:
find.existing.file <- function (files)
  Find(file.exists,files,nomatch=stop("None exist: ",paste(files, collapse=" ")))


text:
Q: POSTing with $.ajax doesn't work Well, the problem is not new, as I saw (really surf a lot), but still can not find solution for myself.
Description of problem:

*

*Have local Web server - XAMPP;

*Firefox 29.0.1

*And trying to send POST with $.ajax
function checkUser(){
  $.ajax({
    type: 'POST',
    url: 'ajax/checkUser.php',
    data: 'uname='+$("#username").val()+'&pword='+$("#password").val(),
    success: function(){
      someNewFunc();
    },
  });
};

This function I'm calling with:
$(document).ready(function(){
        $(".button.postfix.login").on("click", function(){
        if (($("#username").val() != "") && ($("#password").val() != "")) {
            hide(); <-- hide pop ups about empty field
            checkUser();
        } else {$("#empty").show();} <-- pop ups
        });
    });

And here code of page with elements:
<input id="username" type="text" placeholder="Username" />
<input id="password" type="password" placeholder="Password" />

Sign in

I guess that data are going out, but the page checkUser.php doesn't get anything.
What am I doing wrong?
P.S. checkUser.php:
<?php
print_r($_POST);
?>

Result - Array ( )
P.P.S. By the way, if POST change to GET it's working, but need to be POST

A: Does your someNewFunc callback fire? Do you see the HTTP AJAX request in the developer console in Firefox?
Try sending your post data as a dictionary to $.ajax:
$.ajax({
  type: 'POST',
  data: {
    uname: $("#username").val(),
    pword: $("#password").val()
  }
});

A: $(document).ready(function(){

$(".button.postfix.login").on("click", function() {

    var username = $("#username").val();
    var password = $("#password").val();

if ((username != "") && (password != "")) {
    hide(); <-- hide pop ups about empty field
    checkUser(username, password); // Pass the variables here as a parameter
} else {
    $("#empty").show();} <-- pop ups
});

// Put the parameters here
function checkUser(username, password) {

  $.ajax({
    type: 'POST',
    url: 'ajax/checkUser.php',
    data: { username:username, password:password} //It would be best to put it like that, make it the same name so it wouldn't be confusing
    success: function(data){
       alert(data);
    },
  });
};

});
So when you're gonna call it on php
$username = $_POST['username'];

echo $username;


text:
Q: How to prove $\lim\limits_{n \to \infty} \frac{n}{\log_2 n!} = 0$ I believe this cannot be handled by just analytical transformations and L'Hôpital's rule (there is no derivate of n!...)
How can I prove that:
$\lim\limits_{n \to \infty} \frac{n}{\log_2 n!} = 0$
My only attempt so far at breaking this one was:
$\lim\limits_{n \to \infty} \frac{n}{\log_2 n!} = \lim\limits_{n \to \infty} \frac{\log_2 2^n}{\log_2 n!} = \lim\limits_{n \to \infty} \log_{n!} 2^n$
It is easy to prove that
$\lim\limits_{n \to \infty} \frac{2^n}{n!} = 0$
Because:
$\lim\limits_{n \to \infty} \frac{2^n}{n!} = \lim\limits_{n \to \infty} \binom{2}{1}\binom{2}{2}\binom{2}{3}...\binom{2}{n} < \lim\limits_{n \to \infty} \frac{4}{n} = 0$
Because both $2^n > 0$ and $n! > 0$
But I don't know how to use it as proof for limit

A: Using Cesaro-Stolz:
$$\lim_{n \to \infty} \frac{n}{\log_2 n!} =\lim_{n \to \infty} \frac{n+1-n}{\log_2 (n+1)!-\log_2 n!}=\lim_{n \to \infty} \frac{1}{\log_2 (n+1)} = 0$$

A: $n(n-1)(n-2).....1 \ge (n/2)^{n/2}$;
$\dfrac{n}{\log_2 n!}\le \dfrac{n}{(n/2)(\log_2 n-\log_2 2)}=$
$\dfrac{2}{\log_2 n -1}$.
Take the limit.

A: Note that for every $k >0$ we get $2^{kn} = \left(2^k \right)^n < n!$ for almost all $n$. In particular, $\log_2(n!) > kn$ for almost all $n$. This implies the claim.

A: Doing some basic simplifications with our limit, we can see that:
$$\lim_{n\to\infty}\frac{n}{\log_2{(n!)}}\\= \lim_{n\to\infty}\frac{n}{\left(\frac{\ln(n!)}{\ln(2)}\right)}\\= \ln(2)\cdot\lim_{n\to\infty}\frac{n}{\ln{(n!)}}$$ In order to prove that this limit approaches $0$, we need to prove that $\ln{(n!)}>n$ for sufficiently large $n$. This inequality can be simplified to:
$$n!>e^{n}$$
Note that the rate of which $n!$ grows as $n$ grows, whereas the growth of $e^{n}$ is constant. From this, we can show that $n!>e^n$, for sufficiently large $n$. We can now apply this inequality to where we left off in our limit simplification, hence proving that:
$$\lim_{n\to\infty}\frac{n}{\log_2{(n!)}}=0$$


text:
Q: Why do some contour lines have two different labels? Does my code have a bug or something else?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
file = 'https://aegis4048.github.io/downloads/notebooks/sample_data/unconv_MV_v5.csv'
myDF = pd.read_csv(file)
# Split the data into features and target
feature1 = "Brittle"
feature2 = "Por"
X = myDF[[feature1, feature2]]                #.iloc[:, :-1].values  # A NumPy array!
print("X.info():", X.info())
y = myDF["Prod"]         #.iloc[:, -1].values

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Create a linear regression object
reg = LinearRegression()

# Fit the model to the training data
reg.fit(X_train, y_train)

# Predict the target variable using the test data
y_pred = reg.predict(X_test)

# Evaluate the model using mean squared error (MSE)
mse = np.mean((y_test - y_pred)**2)
print("Mean Squared Error: ", mse)

print("R2 Score:", reg.score(X_test, y_test))
#define figure size in (width, height) for all plots
plt.rcParams['figure.figsize'] = [10, 7]
# Create a mesh of values for the features
print(X_train.shape)  # NumPy array
x1_min, x1_max = X_train[feature1].min(), X_train[feature1].max()
x2_min, x2_max = X_train[feature2].min(), X_train[feature2].max()
x1, x2 = np.meshgrid(np.linspace(x1_min, x1_max, 100), np.linspace(x2_min, x2_max, 100))
X_mesh = np.c_[x1.ravel(), x2.ravel()]

# Compute the predictions for the mesh of values
y_pred_mesh = reg.predict(X_mesh).reshape(x1.shape)

# Plot the predictions as a surface. Request 10 contour lines.
contours = plt.contourf(x1, x2, y_pred_mesh, 10, cmap='coolwarm', alpha=0.8)   # https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contourf.html

# Scatter plot of the training data.
# The colors of the points don't mean much except to stand out from the background
plt.scatter(X_train[feature1], X_train[feature2], c=y_train, cmap='coolwarm', s=20)

# Label the contour lines
plt.clabel(contours, inline=1, fontsize=12, colors = "black")

# Label the plot
plt.xlabel(feature1)
plt.ylabel(feature2)
plt.title('Multivariate Linear Regression Contour Plot')

# Show the plot
plt.show()

The output:


text:
Q: Refreshing element styles in jQuery In my JavaScript, I dynamically append elements to a div like this:
$('.class-name').after('
Hello World!
')

In my CSS, I have something like this:
p .foo {
    color: green;
}

When I test it, the new paragraph element appears, but the text stays black. Is this a case of the document not reading the class of the "p" element? Or does the class "foo" not apply to generated elements?

A: This should be your style:
p.foo {
   color: green;
}

Remove that blank space between "p" and "foo".

A: Try without the space between the paragraph tag and the class.
p.foo {
    color: green;
}

It's the paragraph that has the class, there is no nested element with a class 'foo'.

A: Your rule definition is slightly off. What you have is "elements with the class foo that are inside of a p element".
What you meant was elements that are p elements and have the class foo, which is
p.foo { color: green; }


text:
Q: Issue In Custom ListView I've made a Custom ListView that shows a List of currencies with (Image + TextView + LinearLayout having to prices: 1 for sell currency & 1 for Buy it ).
But unfortunately, the app's been crashed, then I've opened LogCat to see the error,  but nothing has found.
I've attached my files to inspect. Starting  from  the next package adapters
package adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.aboomar.bekamelnaharda.R;

import java.util.ArrayList;

import models.CurrencyModel;

public class CurrencyAdapter extends BaseAdapter {
Context context;
ArrayList<CurrencyModel> currencyModelArrayList;
CurrencyModel currencyModel = new CurrencyModel();

public CurrencyAdapter(Context context, ArrayList<CurrencyModel>
currencyModelArrayList) {
this.context = context;
this.currencyModelArrayList = currencyModelArrayList;
}

public CurrencyAdapter() {
}

@Override
public int getCount() {
return currencyModelArrayList.size();
}

@Override
public CurrencyModel getItem(int position) {
return currencyModelArrayList.get(currencyModel.getId());
}

@Override
public long getItemId(int position) {
return getItem(currencyModel.getId()).getId();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView =
layoutInflater.inflate(R.layout.currency_list_item,parent,false);
currencyModel = getItem(currencyModel.getId());

ImageView imageViewCurrency =
convertView.findViewById(R.id.imageCurrencyIv);
imageViewCurrency.setImageResource(currencyModel.getCurrencyImage());

TextView currencyNameTv = convertView.findViewById(R.id.nameCurrencyTv);
currencyNameTv.setText(currencyModel.getCurrencyTv());

TextView currencyBuyTv = convertView.findViewById(R.id.buyPriceTv);
currencyBuyTv.setText(currencyModel.getCurrencyPriceBuy());

TextView currencySellTv = convertView.findViewById(R.id.sellPriceTv);
currencySellTv.setText(currencyModel.getCurrencyPriceSell());

return null;
}
}

A: You are returning null in getView method but should be returning convertView


text:
Q: net::ERR_SPDY_PROTOCOL_ERROR 200 with proxy server In our project we're using 2 servers: 1 as a PROD API server and 1 as a proxy(actually nginx is used for that)
The proxy server uses HTTP/2 as well. In one scenario the proxy may get response from prod API server and replace PROD links by Proxy's and then return that to the client.
In that case we can catch the "net::ERR_SPDY_PROTOCOL_ERROR 200" error. I googled little bit about that issue, but it looks like it may be few reasons for that error.
In my case it occurs only when we replace hosts(modify the response from the PROD before sending it to client)
Can someone describe what actually the "net::ERR_SPDY_PROTOCOL_ERROR 200" means and maybe best practices to avoid that?

A: HTTP/2 is derived from the earlier SPDY protocol, that's probably why the error message doesn't mention HTTP/2 at all.
One of the reasons why you may see the ERR_SPDY_PROTOCOL_ERROR message is an invalid HTTP header coming from the server.  Perhaps your proxy is making some change to an HTTP response header which is making it invalid/malformed?
Try to disable HTTP/2 on your proxy server and see if the error goes away.  If it does, inspect the response headers and make sure they are valid.  I suspect your proxy server is malforming the response.

A: We met similar issue today when running the reverse proxy server using docker image: nginx:1.16.0-alpine. After changing to use nginx:1.16.0, this issue was solved.


text:
Q: How to prevent 2 objects from splitting on top of another Hello so Im creating a game (since i recently started studying javascript). The game is Asteroids the code is basically the same as freeCodeCamp video only some differences are the scoring system storing and music/sounds. However I want to prevent of 2 objects(asteroids) from spawning/splitting on top of another (If i split the asteroid it spawns the splits in one another) I want to make sure that splitting is more relistic since now they spawn on each other. This is the code I use to split them and the variables i have
function destroyAsteroid(index) {
            var x = roids[index].x;
            var y = roids[index].y;
            var r = roids[index].r;

            if (r == Math.ceil(ROID_SIZE / 2)) {
                roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 4)));
                roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 4)));
                score += ROID_PTS_LGE;
            } else if (r == Math.ceil(ROID_SIZE / 4)) {
                roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 8)));
                roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 8)));
                score += ROID_PTS_MED;
            } else {
                score += ROID_PTS_SML;

what would be easiest way to make them spawn next to each other rather then on top of one another.
I havent tried most of the things the only things i tried is getting a distance between the points(2 split asteroids and then using if function to check if the distance between them is the size of the asteroid size

A: I looks like newAsteroid function accepts X and Y coordinates as its first two parameters. Why not give different values for the asteroids that you want to place next to each other?
You can calculate the coordinates as something like that:
const x1 = x + r;
const y1 = y + r;
const x2 = x - r;
const y2 = y - r;

And then use these values to push new asteroids:
if (r == Math.ceil(ROID_SIZE / 2)) {
    roids.push(newAsteroid(x1, y1, Math.ceil(ROID_SIZE / 4)));
    roids.push(newAsteroid(x2, y2, Math.ceil(ROID_SIZE / 4)));
    score += ROID_PTS_LGE;
} else if (r == Math.ceil(ROID_SIZE / 4)) {
    roids.push(newAsteroid(x1, y1, Math.ceil(ROID_SIZE / 8)));
    roids.push(newAsteroid(x2, y2, Math.ceil(ROID_SIZE / 8)));
    score += ROID_PTS_MED;
} else {
    score += ROID_PTS_SML;

This should place asteroids along the diagonal line, if r is the radius.
By the way, seems strange to me that asteroids are spawning in a function called destroyAsteroid!  I see, this is called like that because 'to destroy' means 'to split' the asteroid in two pieces.


text:
Q: How to add jdbc dependency to Play project? I'm using play 2.2.2.
I'd like to enable jdbc library in a Play/Scala project as mentioned in Accessing an SQL database.
Here's my rootproject/project/plugins.sbt:
libraryDependencies ++= Seq(
  jdbc
  "com.google.zxing"   %  "core"                 % "2.0",
  "mysql"              %  "mysql-connector-java" % "5.1.27",
  "com.typesafe.slick" %% "slick"                % "2.1.0",
  "org.slf4j"          %  "slf4j-nop"            % "1.6.4"
)

While compiling the project, I get following jdbc not found error,
$ /usr/local/play-2.2.2/play compile
/packup/smartad-core/project/plugins.sbt:8: error: not found: value jdbc
      jdbc
          ^
[error] Type error in expression
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? q

My rootproject/build.sbt simply is
  import play.Project._

  name := "smartad-backend"

  version := "1.0"

  playScalaSettings

References
https://www.playframework.com/documentation/2.3.x/ScalaAnorm

A: You should combine both of those blocks into your build.sbt file. plugins.sbt is for adding sbt plugins, such as the play sbt plugin. But that's about it.
import play.Project._

name := "smartad-backend"

version := "1.0"

playScalaSettings

libraryDependencies ++= Seq(
   jdbc,
   ...
)


text:
Q: Could not find a valid gem 'rails' (>= 0) in any repository I'm on a fresh mac and just installed ruby 1.9.3 using rvm. Now I'm trying to install rails and getting the error on the title of this post. I'll post below all info I have from the command line to see if anyone can help me out here!!
Leonardos-MacBook-Air:~ leo$ gem install rails
WARNING:  Error fetching data: SocketError: getaddrinfo: nodename nor servname provided, or not known (http://rubygems.org/latest_specs.4.8.gz)
ERROR:  Could not find a valid gem 'rails' (>= 0) in any repository
ERROR:  Possible alternatives: rails
Leonardos-MacBook-Air:~ leo$ ping rubygems.org
PING rubygems.org (204.232.149.25): 56 data bytes
64 bytes from 204.232.149.25: icmp_seq=0 ttl=47 time=104.399 ms
64 bytes from 204.232.149.25: icmp_seq=1 ttl=47 time=105.760 ms
^C
--- rubygems.org ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 104.399/105.079/105.760/0.681 ms
Leonardos-MacBook-Air:~ leo$ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.23
  - RUBY VERSION: 1.9.3 (2012-04-20 patchlevel 194) [x86_64-darwin11.4.0]
  - INSTALLATION DIRECTORY: /Users/leo/.rvm/gems/ruby-1.9.3-p194
  - RUBY EXECUTABLE: /Users/leo/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/leo/.rvm/gems/ruby-1.9.3-p194/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-11
  - GEM PATHS:
     - /Users/leo/.rvm/gems/ruby-1.9.3-p194
     - /Users/leo/.rvm/gems/ruby-1.9.3-p194@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/
Leonardos-MacBook-Air:~ leo$ ruby --version
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]
Leonardos-MacBook-Air:~ leo$

A: The clue here is WARNING:  Error fetching data: SocketError: getaddrinfo: nodename nor servname provided, or not known (http://rubygems.org/latest_specs.4.8.gz)
This indicates there's an issue at Rubygems.org at the moment. There's almost certainly nothing wrong on your end. Try again in a little while and it should be ok. I just tried myself on a mac and it worked fine.

A: I have fixed this issue using the proxy command option of gem install. It has the following format:
$ gem install --http-proxy http://201.187.107.19:8080 rails

Note, the IP address and the port number refers to a proxy. You should search for a proxy list and use one of the proxies there.
This is site with proxies: http://www.cybersyndrome.net/pla5.html
Also, I have to try 7 or 8 different proxies in order to succeed. Do not give up.
Note, you could see the following error, too:
ERROR:  While executing gem ... (Gem::DependencyError)
    Unable to resolve dependencies: rails requires activesupport (= 3.2.8), actionpack (= 3.2.8), activerecord (= 3.2.8), activeresource (= 3.2.8), actionmailer (= 3.2.8), railties (= 3.2.8), bundler (~> 1.0)

Don't give up and continue with the next proxy from the list. Good luck.


text:
Q: Read text file into list without using direct loop using std::list c++ I have a program that reads a list of assignments and removes the "bad" assignments, then writes into a new file. My function that removes the bad assignments works correctly. The code I currently am using to read the text file works correctly also, but is doing so with a while loop. How can I utilize the std::list library to accomplish the same thing without the while loop. Below is the code I am using for the removing of the bad assignmemnts (Prune) along with reading the text file.
void Prune()
{
    m_Assignments.remove_if([](const Assignment& assignment){ return !assignment.IsGood();});

}

void Read(std::istream& is)
{
    std::string s;

    std::getline(is, s);
    m_Name = s;

    Assignment a;
    while (is >> a)
    {
        m_Assignments.push_back(a);
    }

}

A: You can use std::istream_iterator and std::back_inserter to copy (using std::copy) strings from input stream to the list:
std::copy (
    std::istream_iterator<std::string>{is},
    std::istream_iterator<std::string>{},
    std::back_inserter(a)
);


text:
Q: What is the difference between normal function and generator function? I am trying to understand the below methodology,
In [26]: def generator():
   ....:     print 'generator function hits'
   ....:     for i in range(3):
   ....:         yield i
   ....:

In [27]: def normal():
   ....:     print 'normal function hits'
   ....:     return range(3)
   ....:

In [28]: gen = generator()

In [29]: type(gen)
Out[29]: generator

In [30]: fun = normal()
normal function hits

In [31]: type(fun)
Out[31]: list

Here my research from the above code,
26 is the generator() function and 27 is the normal() function, when I have assigned generator() function to gen variable I haven't seen any print message like generator function hits, But if I have assigned the normal() function to fun variable, I have seen the print message like normal function hits. My question is why generator() function not hit ?

A: Because a generator function's body is not executed until you call next on it.
>>> gen = generator()
>>> next(gen)
generator function hits
0

Now on the second next() call the generator will run again from where it left off:
>>> next(gen)
1

A: Generator function stops at yield, next you call again it resumes from where yield stopped. xrange is also built-in generator version of range function. Since range returns list, xrange generates numbers on demand, memory efficiency is on the side of xrange.


text:
Q: Splitting string into a new line in apache-pig I want to split the string in a dataset that is joined by a backslash (/) into a new line.
The example datatset is:
(David Jones / John Smith)

I want the result to be:
(David Jones)
(John Smith)

The code i have written is:
A = FOREACH data GENERATE FLATTEN(STRSPLIT(name,'/',2));
DUMP A;

However the result i'm getting in the terminal is:
(David Jones, John Smith)

A: STRSPLIT creates a tuple in the same row. Flattening it will collapse it back together.
I suggest trying without the flatten

A: You should use TOKENIZE instead of STRSPLIT
Code:
A = LOAD 'input.txt' AS (name:chararray);
B = FOREACH A GENERATE FLATTEN(TOKENIZE(name,'/'));
DUMP B;

Contents of input.txt:
David Jones/John Smith

Output:
(David Jones)
(John Smith)


text:
Q: Proving differentiability (rigorously).
How do I prove them to be differentiable in a "rigorous" way?
Or do i just simply compute their differentials?

A: (i) Write $f=(f_1,f_2,f_3)$ and note it is differentiable if and only if each $f_j$ is differentiable. Now each $f_j$ is actually $C^\infty$ by composition/product/difference of standard $C^\infty$ functions. To express the derivative of $f$, compute the Jacobian.
(ii) This one is more tricky. It is $C^\infty$ on $\mathbb{R}^2\setminus \{(0,0)\}$ as a composition/product/sum/quotient of $C^\infty$ functions (where the denominator is nowhere zero). In this case, again, compute the Jacobian to express the derivative. You get
$$
df_{(x,y)}=\left(\frac{\partial f}{\partial x} \;\;\frac{\partial f}{\partial y}\right)=\left(\frac{2x^4+3x^2y^2}{(x^2+y^2)^{3/2}}\;\;\; \frac{-x^3y}{(x^2+y^2)^{3/2}}\right).
$$
At $(0,0)$, the argument is different. We will show that the derivative at this point is $0$. By definition, this amounts to showing that
$$
f((x,y))=f((0,0))+0\cdot(x,y)+\sqrt{x^2+y^2}\epsilon((x,y))
$$
where $\epsilon$ is a function which tends to $0$ as $\sqrt{x^2+y^2}$ goes to $0$.
So we compute
$$
\epsilon((x,y))=\frac{f((x,y))-f((0,0)-0\cdot(x,y)}{\sqrt{x^2+y^2}}=\frac{x^3}{x^2+y^2}.
$$
Now
$$
|\epsilon((x,y))|=\frac{|x|^3}{x^2+y^2}\leq \frac{|x|(x^2+y^2)}{x^2+y^2}=|x|\leq \sqrt{x^2+y^2}.
$$
So $\epsilon$ tends to $0$ as desired and $f$ is differentiable at $(0,0)$ with
$$
df_{(0,0)}=0.
$$

A: I think this depends on what type of reasoning the math course you're taking is trying to emphasize. For the first function, I would hope that you are allowed to take for granted the differentiability of $\sin$ and polynomials, in which case you just directly calculate according to the techniques you have learned.
For the second function, you can of course calculate the derivative for $(x,y) \neq (0,0)$. To show that it is also differentiable at the origin, you can use a $\delta,\epsilon$ type argument. Feel free to respond if you would like more elaboration.


text:
Q: Overlay two raster GeoTIFFs using rasterio mask I'm trying to crop two different geotiffs/rasters using a polygon with rasterio's mask function in order to get two corresponding/overlapping cropped numpy arrays of the same size/shape. The problem is that the cropped arrays aren't always the same shape (difference of no more than 1 pixel).
import numpy as np
import matplotlib.pyplot as plt
import os
from os.path import join
import fiona
import rasterio as rio
from rasterio.mask import mask
import gdal
import shapely
from shapely.geometry import mapping, shape, MultiPolygon, Polygon
from shapely.ops import transform
import pyproj

def gdal_reproject(src_path, dist_path, dst_crs, dst_res=(30, 30), interp=0, align=True):
    opt = gdal.WarpOptions(dstSRS=dst_crs,
                           polynomialOrder=interp,
                           targetAlignedPixels=align,
                           xRes=dst_res[0], yRes=dst_res[1])
    gdal.Warp(srcDSOrSrcDSTab=src_path,
              destNameOrDestDS=dist_path,
              options=opt)

def summarize_tif(path):
    tif1 = rio.open(path)
    x_res = (tif1.bounds.right - tif1.bounds.left) / tif1.width
    y_res = (tif1.bounds.top - tif1.bounds.bottom) / tif1.height
    print("crs {}".format(tif1.crs))
    print('dtype {}'.format(tif1.meta['dtype']))
    print("height {}, width {}".format(tif1.height, tif1.width))
    print("x_res {}, y_res {}".format(x_res, y_res))
    print("bounds {} \n \n".format(tif1.bounds))
    tif1.close()

tif_1 = join(landsat_dir, "21_32/LC080210322016072801T1/LC08_L1TP_021032_20160728_20170221_01_T1_sr_band3.tif")
summarize_tif(tif_1)
#  crs EPSG:32616
#  dtype int16
#  height 7801, width 7671
#  x_res 30.0, y_res 30.0
#  bounds BoundingBox(left=497085.0, bottom=4347885.0, right=727215.0, top=4581915.0)

with rio.open(tif_1, 'r') as tif:
    dst_crs = tif.crs

tif_2 = join(CLD_dir, "CDL_2018_18.tif")
summarize_tif(tif_2)
#  crs PROJCS["unnamed",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.2572221010042,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4269"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",29.5],PARAMETER["standard_parallel_2",45.5],PARAMETER["latitude_of_center",23],PARAMETER["longitude_of_center",-96],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]]
#  dtype uint8
#  height 15717, width 9143
#  x_res 30.0, y_res 30.0
#  bounds BoundingBox(left=687435.0, bottom=1666935.0, right=961725.0, top=2138445.0)

tif_2_reproj = join(tmp_dir, "usda_2018_18_EPSG32616_gdal_py.tif")
if os.path.isfile(tif_2_reproj):
    os.remove(tif_2_reproj)
gdal_reproject(src_path=tif_2, dist_path=tif_2_reproj,
               dst_crs=dst_crs, dst_res=(30, 30), interp=0, align=True)
summarize_tif(tif_2_reproj)
#  crs EPSG:32616
#  dtype uint8
#  height 16358, width 10673
#  x_res 30.0, y_res 30.0
#  bounds BoundingBox(left=402150.0, bottom=4156530.0, right=722340.0,
 top=4647270.0)

with fiona.open(parc_2018, layer='County_Land_Parcels_IGIO_IN_Apr2018') as src:
    meta = src.meta
    print('src crs', src.crs)
    src_crs = src.crs['init']
    for i, feature in enumerate(src):
        if i==200423:
            polys = shape(feature['geometry'])
            print(type(polys))
            polys_rpj = shapely.ops.transform(lambda xx, y: pyproj.transform(pyproj.Proj(init=src_crs),
                                                                      pyproj.Proj(init=dst_crs), xx, y),
                                                                      polys)
            print(type(polys_rpj))
            print('poly center: {}'.format(polys_rpj.centroid))

            with rio.open(tif_1, 'r') as tif:
                crop1, trnsfrm1 = mask(dataset=tif, shapes=[polys_rpj],
                                       crop=True)

            with rio.open(tif_2_reproj, 'r') as tif:
                crop2, trnsfrm2 = mask(dataset=tif, shapes=[polys_rpj],
                                       crop=True)

            break

print("crop1 shape {}, crop2 shape {}".format(crop1.shape, crop2.shape))

#  <class 'shapely.geometry.multipolygon.MultiPolygon'>
#  <class 'shapely.geometry.multipolygon.MultiPolygon'>
#  poly center: POINT (669672.4700203884 4369366.759086045)
#  src crs {'init': 'epsg:26916'}, dst crs EPSG:32616
#  crop1 shape (1, 4, 3), crop2 shape (1, 5, 3)

How do I get crop1 and crop2 to be consistently the same shape?

A: You could also use rioxarray.
The most useful examples for your use case are:

*

*clip

*reproject_match
import rioxarray
import fiona

# open the rasters
rds1 = rioxarray.open_rasterio("21_32/LC080210322016072801T1/LC08_L1TP_021032_20160728_20170221_01_T1_sr_band3.tif")
rds2 = rioxarray.open_rasterio("CDL_2018_18.tif")

# clip the rasters
with fiona.open(parc_2018, layer='County_Land_Parcels_IGIO_IN_Apr2018') as src:
    geom_crs = src.crs_wkt
    geoms = [feature["geometry"] for feature in src]

rds1_clipped = rds1.rio.clip(geoms, geom_crs)
rds2_clipped = rds2.rio.clip(geoms, geom_crs)

# ensure the rasters have the same projection/transform/shape
rds2_match = rds2_clipped.rio.reproject_match(rds2_clipped)

# write to file
rds1_clipped.rio.to_raster("LC08_L1TP_021032_20160728_20170221_01_T1_sr_band3__clipped.tif")
rds2_match.rio.to_raster("CDL_2018_18__clipped_reprojected.tif")

A: The answer was in the gdal.WarpOptions. The two rasters were aligned and had the same shape after targetAlignedPixels was set as False and an additional argument outputBounds was included (corresponding raster image).
def gdal_reproject(src_path, dist_path, dst_crs, bounds, dst_res=(30, 30), interp=0, align=True):
    opt = gdal.WarpOptions(dstSRS=dst_crs,
                           outputBounds=bounds,
                           polynomialOrder=interp,
                           targetAlignedPixels=align,
                           xRes=dst_res[0], yRes=dst_res[1])
    gdal.Warp(srcDSOrSrcDSTab=src_path,
              destNameOrDestDS=dist_path,
              options=opt)

tif_1 = join(landsat_dir, "21_32/LC080210322016072801T1/LC08_L1TP_021032_20160728_20170221_01_T1_sr_band3.tif")
summarize_tif(tif_1)

with rio.open(tif_1, 'r') as tif:
    dst_crs = tif.crs # 'EPSG:32616'
    src_bounds = tuple(tif.bounds) # (minX, minY, maxX, maxY)

tif_2 = join(CLD_dir, "CDL_2018_18.tif")
summarize_tif(tif_2)

tif_2_reproj = join(tmp_dir, "usda_2018_18_EPSG32616_gdal_py.tif")
if os.path.isfile(tif_2_reproj):
    os.remove(tif_2_reproj)
gdal_reproject(src_path=tif_2, dist_path=tif_2_reproj, bounds=src_bounds,
               dst_crs=dst_crs, dst_res=(30, 30), interp=0, align=False)
summarize_tif(tif_2_reproj)

Thank you Ryan for the hint!