text:
Q: Python request.get fails on specific site I just finished automate the boring stuff with python, now i'm just practicing.
I try running the code below but it fails . Other sites has no issue connecting .
Searched for other questions they say add user:agent, it works for amazon.com but not for this site .
I tried allow_redirects = False and ,verify=False too , they are not working
I am using Windows 10 , Python 3.8.5 , requests 2.24.0
my code ;
import requests

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
print('1')
res = requests.get('https://freida.ama-assn.org/search/list?spec=42931',headers=headers)
print('2')
print(res.status_code)
res.raise_for_status()

This code does not prints '2' fails at requests.get
Error code as follows :
C:\Users\User198\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/User198/PycharmProjects/pythonProject/amaResidency.py
1
Traceback (most recent call last):
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 978, in _validate_conn
    conn.connect()
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connection.py", line 362, in connect
    self.sock = ssl_wrap_socket(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\ssl_.py", line 384, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
OSError: [Errno 0] Error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 726, in urlopen
    retries = retries.increment(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\retry.py", line 403, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\packages\six.py", line 734, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connectionpool.py", line 978, in _validate_conn
    conn.connect()
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\connection.py", line 362, in connect
    self.sock = ssl_wrap_socket(
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\urllib3\util\ssl_.py", line 384, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\User198\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError(0, 'Error'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/User198/PycharmProjects/pythonProject/amaResidency.py", line 6, in <module>
    print(res.status_code)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\User198\PycharmProjects\pythonProject\venv\lib\site-packages\requests\adapters.py", line 498, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError(0, 'Error'))

A: So, seems like i fixed the issue .
In my case code was working via my cellphone internet but Wi-Fi connection was failing for this particular site .
I unchecked "Microsoft LLDP Protocol Driver" from Control panel => network and internet => network connections => LeftClick your connection and properties => Networking tab => Uncheck "Microsoft LLDP Protocol Driver"
Everything was checked except "microsoft network adapter multiplexor protocol"
Now "Microsoft LLDP Protocol Driver" is not checked too.
This solution worked for me

A: You may try ignoring SSL certificate verification using verify = False. It drastically reduced my count of similar ConnectionErrors.
res = requests.get('https://freida.ama-assn.org/search/list?spec=42931', headers=headers, verify=False)
Note that when verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks.


text:
Q: Strange behaviour when breakpoint in visual studio 2005 I have to maintain a C# project built in VS 2005 (.NET 2.0), but when I put a breakpoint in specific line during debug, something strange happens:

I have found that Resharper could cause those kind of "problems", but its licence has been expired from more than six months.

A: Finally, I solved the issue uninstalling completely resharper from my laptop.
Here is the reference link (for me, point 2 worked):
https://resharper-support.jetbrains.com/hc/en-us/articles/206545359-Uninstalling-ReSharper-Ultimate-tools-from-Visual-Studio

To completely remove ReSharper Ultimate tools from Visual Studio,
  please try the following:

*

*Run ReSharper Ultimate installer once again - do you have any products with status Repair? If so, please select Remove for them and
  select Skip for others.

*If there are no items with Repair action, please remove the following folder manually
  %LocalAppData%\Microsoft\VisualStudio{Visual Studio
  version}\Extensions\JetBrains

*If Visual Studio still thinks ReSharper is installed, try deleting the following Windows Registry branch
  HKEY_CURRENT_USER\Software\Microsoft\VisualStudio{VS version}_Config

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to provide the functionalities/features of an android app without the user having to explicitly install it I'm trying to provide certain functionalities for an android phone that could help people in times of emergencies. (These functionalities are dependent on the phone's sensors.) The only/main approach to achieve this seems to be that of developing an app (and I am currently in the process of developing one). But, what concerns me is that the number of people using an application specifically for emergency purposes is quite low. Even if they do install, when "Insufficient Memory" pops up, an emergency app is very likely to be booted out of the phone.
Are there other ways of providing the functionalities/features of an emergency app, without the users having to explicitly install the app? Or should I just stick with the app?
Certain OEMs provide emergency features as part of their settings. Like for example, in a Samsung phone you can toggle to enable the "Send SOS messages", and then, in case of an emergency, press the power button thrice. In what way could I achieve the same?
Any help would be much appreciated...
Thanks in advance!

A: Without a proper application installed in user device, you cannot provide the functionality you want.
OEM's also have their applications build and packaged with the system image. If you want it, you need to be in contact with them to include your application in new devices.


text:
Q: How can we enable encryption for a particular folder in S3 I have created a S3 bucket.I want to encrypt a  objects inside a specific folder in S3 bucket.How can I do that?

A: *

*We have Server-Side Encryption and Client-Side Encryption

*Protecting Data Using Server-Side Encryption You have three mutually exclusive options depending on how you choose to manage the encryption keys aws docs

*Use Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3)

*Use Server-Side Encryption with Keys Stored in AWS KMS (SSE-KMS)

*Use Server-Side Encryption with Customer-Provided Keys (SSE-C)
Protecting Data Using Server-Side Encryption (SSE-S3)

*You can set the policy on the specific bucket to only allow encrypted data in for all the objects inside that bucket aws doc

*Note in your case for S3 policy would be like this assuming this as the bucket structure outbound/globalscape/dlearn.

*Go on to the aws console--> click on outbound folder --> and then on permissions --> bucket policy --> and paste the below policy and save
S3 policy for the bucket
{
  "Version": "2012-10-17",
  "Id": "PutObjPolicy",
  "Statement": [
    {
      "Sid": "DenyIncorrectEncryptionHeader",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::outbound/globalscape/dlearn/*",
      "Condition": {
        "StringNotEquals": {
          "s3:x-amz-server-side-encryption": "AES256"
        }
      }
    },
    {
      "Sid": "DenyUnEncryptedObjectUploads",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::outbound/globalscape/dlearn/*",
      "Condition": {
        "Null": {
          "s3:x-amz-server-side-encryption": "true"
        }
      }
    }
  ]
}

*

*The bucket policy denies permissions to upload an object unless the request includes the x-amz-server-side-encryption header to request server-side encryption.

"s3:x-amz-server-side-encryption": "AES256"

*

*This aws blog How to Prevent Uploads of Unencrypted Objects to Amazon S3 which is basically doing the same to check go to  (Implementing use case #1: Using SSE-S3 managed keys) in the blog.

*In the above blog go to Testing the solutions where in they are using Policy Simulator to test. There as well the user policy which they have given you will have to replace this bit "Resource": "arn:aws:s3:::outbound/globalscape/dlearn/*" object in the image attached again has to be your bucket arn:aws:s3:::outbound/globalscape/dlearn/.

*you can then test it once keeping the value AES256 and once keeping it blank.

A: Encrypting a folder using the Amazon S3 console

*

*Open the Amazon S3 console.

*Navigate to the folder that you want to encrypt.

*Select the folder, and then choose Actions.

*Choose Change encryption.

*For Change encryption, select AWS-KMS.

*For Select a key, select the AWS KMS key that you want to encrypt the folder with.

*Choose Save.


text:
Q: I'm trying to make a python script that removes unwanted words and punctuation from a txt file. However, it is not good enough for the grader? I'm trying to make a word cloud. I need to strip a txt file of uninteresting words and punctuations. The grader just isn't giving me any feedback. I think my script removes some extra words and I can't figure out why. Can someone point me in the right direction?
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

def count(file_contents):
    frequencies = {}
    word_list = file_contents.split()
    final_list = []
    #remove all uninteresting words
    for word in word_list:

        new_word = ""
        for character in word:
            if character not in punctuations and character.isalpha():
                new_word += character

        if word.lower() not in uninteresting_words:
            final_list.append(new_word)

    for word in final_list:
        if word not in frequencies:
            frequencies[word] = 0
        frequencies[word] += 1
    return frequencies

A: I don't know if I wasn't getting the answer wrong because I was uploading it wrong or if coursera was bugged because I submitted this code twice in two different ways. One I directly clicked submit assignment through; The other, I downloaded the notebook and submitted through coursera. This worked and it gave me the correct answer. Regardless, this is correct code.
# Here is a list of punctuations and uninteresting words you can use to process your text
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and","or", "an","in", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

# LEARNER CODE START HERE

file_no_punct = ""

#remove all punctuation
for char in file_contents:
    if char.isalpha() == True or char.isspace():
        file_no_punct += char

boring_list = file_no_punct.split()
zesty_list =[]
#remove all uninteresting words
for word in boring_list:
    if word.lower() not in uninteresting_words and word.isalpha()==True:
        zesty_list.append(word)

frequencies = {}
for word in zesty_list:
    if word not in frequencies:
        frequencies[word] = 0
    frequencies[word] += 1


text:
Q: What happens when redirecting with 3>&1 1>/dev/null? I'm playing around with file descriptors to better grok them and I'm failing to understand the following.
$ grep "..." 3>&1 1>/dev/null
1
12
13
123
321
3

The above does not show in the shell any of the matches, this is obviously happening because I'm redirecting to /dev/null. What I don't understand is why 3>&1 doesn't make it so that I still see the output, since I made a copy of it in fd 3.
What am I missing?

A: Your redirections do make FD 3 a copy of FD 1, so FD 3 will point to standard output and anything written to it will go to (by default) the TTY. You then redirect FD 1 to /dev/null, so anything written to FD 1 will be discarded. Because grep doesn't ever write to FD 3, nothing visible happens with it.
These happen in sequence: firstly a copy (dup2) of FD 1 is made to FD 3, so FD 3 henceforth points at what FD 1 currently points at, and secondly FD 1 is replaced by a pointer to /dev/null.
The end result is shown in the following diagram:

Standard error (in pink, FD 2) and FD 3 are to the TTY, and standard output is to /dev/null. FD 3 still points at the TTY because that's where FD 1 pointed when the copy was made. However, the grep command will not try to write anything to FD 3, so the copy never gets any use.
The "copying" is directional: after 3>&1 is processed, anything written to FD 3 will go to where FD 1 pointed at the time of processing. It doesn't "preserve" anything beyond that: if you subsequently redirect FD 1, anything written to it goes to the new place. What you've done is held on to the original destination of FD 1 in case you wanted to use it later. The only redirection that affects where grep's standard output ends up is the one 1>... that explicitly talks about where it goes.
If grep were to write to FD 3, it would appear in the terminal as expected. Because it only outputs to FD 1 normally, all of its actual output is being discarded.

We could make a grep outputting to FD 3 if we wanted:
( grep "..." >&3 )

That will take the regular output on FD 1 and point it at (the newly-created) FD 3 instead. This won't work if you run it directly, because FD 3 doesn't go anywhere, but we can incorporate it into something like this that makes use of it:
( grep "..." >&3 ) 3>&1 1>/dev/null

The command in parentheses outputs to FD 3. The redirections afterwards 1) point FD 3 (which now actually has content on it) at FD 1, and 2) then direct FD 1 away again (which has no effect). The end result is that you'll get the grep "..." output to standard output again, exactly where it would have been without all the fuss.
A practical use of this sort of redirection is something like
cmd 3>&1 1>&2 2>&3 3>&- | foo

which swaps FDs 1 and 2, using FD 3 as a temporary storage spot. It's also sometimes used for shell-script tricks, like faking process substitution in POSIX sh with ( cmd1 | ( cmd2 | ( main_command /dev/fd/3 /dev/fd/4 ) 4<&0 ) 3<&0 ). Otherwise, it's fairly rare that commands innately use any non-standard file descriptor by number (of course many open a file themselves and get one).

A: You're redirecting file-descriptor 3 to file-descriptor 1, and you're redirecting 1 to /dev/null. You're not making a copy of anything.
The normal way to copy a file-descriptor is with tee.
Also, I don't know what your context is, but 3 isn't a built-in file descriptor. Presumably you'd already set it up to point to something?


text:
Q: Facebook API 1.0 new platform Just want to make sure I understand how the Facebook API versioning policy works with v1.0 deprecation.  If I have an existing Facebook app that was created prior to April 30th 2014, can I create a new platform (e.g. IOS or Android) today and still use the v1.0 API?
Thanks.

A: Platforms don´t matter, if your App was created before April 30, 2014 and if it was active before that date, you can still use v1.0 until April 30, 2015.


text:
Q: Are type hint and default param value also method signature? Example :
The interface is
public function doFoo($bar);

Can I have a class implementing the interface with method
public function doFoo(array $bar = array('test')) { }

What does the method signature mean in PHP?
Is it just the method name and parameter name ?
Or, type hinting and default values for parameters also included ?

A: The default value for an argument isn't fixed with a interface (To clarify: The value isn't fixed, but if the interface has a default value then the class which implements the interface also needs a default value, but the value is not fixed by the interface).
However when an interface defines a method with a type hint the class must use the same type hint! You can also see this in the manual.
And a quote from there:

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.

A: You can type-hint in several ways. The formatting of a method signature in PHP goes:
class -> type -> variable -> default value
Thus, you can hint that a param must be an instance of a class like:
function foo(someClass $bar)
or you can merely specify that that param must be callable like:
function foo(callable $bar)
Similarly, you can type hint the an array like you did above.
A param not being an instance of the class you specified throws a fatal error.


text:
Q: Prolog: Repeating Sequences I want to make a simple program that repeatedly extends a list by another list, but give a result every step on the way.
I have something like this, it only runs once:
repeat(S, R, X) :- append(S,R,X).

:- repeat([y], [x], X).
X = [y,x].

Then I tried this, which runs forever:
repeat(S, R, X) :- append(S,R,X), repeat(S,R,X).

What ways can i make this program output something like:
:- repeat([y], [x], X).
X = [y,x];
X = [y,x,x];
X = [y,x,x,x];
x = [y,x,x,x,x];
....

I assume I need some kind of base case?

A:
but give a result every step on the way.

As you know, Prolog can step forward or backward.
Then could be better to separate the functional request to extend a list by another, that's already covered by append/3, by the replication part. This last is better coded using difference lists, easily interfaced by phrase/3:
% service 'grammar'
enlist(L), L --> [] ; enlist(L).

that yields
?- phrase(enlist([1,2]), [], L).
L = [1, 2] ;
L = [1, 2, 1, 2] ;
...

then we can write
repeat(S, R, X) :-
    append(S, P, X),
    phrase(enlist(R), [], P).

and we obviously get
?- repeat([a,b],[1,2],L).
L = [a, b, 1, 2] ;
L = [a, b, 1, 2, 1, 2] ;
...

A: You can try
repeat(S, R, X) :-
    S = X; append(S,R,X1), repeat(X1,R,X).

A: Similar to CapelliC's solution, using DCG, offered here only as a slight variation that doesn't use append and avoids redundant solutions for R = [].
rep(S, _) --> S.
rep(S, R) --> {R \= []}, rep(S, R), R.

repeat(S, R, X) :- phrase(rep(S, R), X).

This yields:
| ?- repeat([y], [x], L).

L = [y] ? ;

L = [y,x] ? ;

L = [y,x,x] ? ;
...

And:
| ?- repeat([a,b],[1,2],L).

L = [a,b] ? ;

L = [a,b,1,2] ? ;

L = [a,b,1,2,1,2] ?

A: Couldn't you just do it the simple way?
repeat(Xs,Ys,Zs) :- append(Xs,Ys,Zs) .
repeat(Xs,Ys,Zs) :- append(Xs,Ys,Ts) , repeat(Ts,Ys,Zs) .

Or
repeat(Xs,Ys,Zs) :-
  append(Xs,Ys,Ts) ,
  (
    Ts=Zs
  ;
    repeat(Ts,Ys,Zs)
  ) .

A: Yes, you do need a base case. If you want to backtrack (press ; for another answer), you at least have to have a choice. You need to be able to the last choice you made and choose differently.
A base case would be
% We append the tail to the head.
repeat(H, T, L) :- append(H, T, L).

A different choice would be
% We repeat H and T (the base case) and then append T to that.
repeat(H, T, L) :-
   repeat(H, T, L1),
   append(L1, T, L).


text:
Q: How to let the AlarmManager not execute my notification if the trigger time I set is in the past? It say in this section of Android dev doc on Scheduling Repeating Alarms that "if trigger time you specify is in the past, the alarm triggers immediately". So if right now is 9am, and I set the AlarmManager to execute my daily notification at 8am, it won't wait until tomorrow at 8am to execute the notification, it will immediately pop up. How do I make it not pop up?
Here is my commented code:
/**
* Show alertDialog to pick time
* @param v
*/
@Override
public void onClick(View v){
   Calendar c=Calendar.getInstance();
   mHour=c.get(Calendar.HOUR_OF_DAY);
   mMinute=c.get(Calendar.MINUTE);
   TimePickerDialog timePickerDialog=new TimePickerDialog(this,
        new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hour, int
              minute) {
                timeSet.setText(hour+":"+minute);
                //storing the inputted hour and time, so they reappear when
                //app reopens
                editor.putInt("Hour",hour);
                editor.putInt("Minute",minute);
                editor.apply();

                scheduleNotification(hour,minute);
            }
        },mHour,mMinute,true);
   timePickerDialog.show();
}

/**
*Building Intent for AlarmReceiver and PendingIntent.
* Give PendingIntent to AlarmManager
* @param hour user-inputted hour of day
* @param minute user-inputted minute of day
*/
public void scheduleNotification(int hour, int minute){
 Intent intent1=new Intent(this,AlarmReceiver.class);
 //FLAG_UPDATE_CURRENT: if the described PendingIntent already exists,
 //keep it but replace its extra data with what is in this new Intent.
 PendingIntent pendingIntent=PendingIntent.getBroadcast(this
        ,0
        ,intent1
        ,PendingIntent.FLAG_UPDATE_CURRENT);
 AlarmManager am=(AlarmManager)this.getSystemService(this.ALARM_SERVICE);
 Calendar calendar=Calendar.getInstance();

 calendar.set(Calendar.HOUR_OF_DAY,hour);
 calendar.set(Calendar.MINUTE,minute);
 //RTC_WAKEUP: wake up the device when it goes off.
 am.setRepeating(AlarmManager.RTC_WAKEUP
        , calendar.getTimeInMillis()
        ,AlarmManager.INTERVAL_DAY
        ,pendingIntent);
  }

AlarmReceiver.class is for making the notification when it Receives the phone receives the pendingIntent and use it to call AlarmReceiver.class (to make notification).

A: You can add a check code with your specific time and current time:
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,hour);
    calendar.set(Calendar.MINUTE,minute);

    long _alarm = 0;
    Calendar now = Calendar.getInstance();
    if(calendar.getTimeInMillis() <= now.getTimeInMillis())
        _alarm = calendar.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
    else
        _alarm = calendar.getTimeInMillis();

    am.setRepeating(AlarmManager.RTC_WAKEUP
    , _alarm
    ,AlarmManager.INTERVAL_DAY
    ,pendingIntent);


text:
Q: Assign variable inside ajax request How do I make this js function work? The log shows "forwarded", but the forward value is still 0.
   function getDayForward(day, time) {
      var product_id = {!! json_encode($product->id ?? null) !!};
      var daysEnabled = {!! json_encode($days_available ?? null) !!};
      var forward = 0;
      $.ajax({
        url: '/products/' + product_id + '/days/' + day + '/times/values',
        method: 'GET',
        success: function(data) {
          for(let j = 0; j < data.value.length; j++) {
            if (time == data.value[j]) {
              // If no time available, the day will be forwarded
              if(j == data.value.length - 1) {
                console.log('forwarded');
                for (let k = 0; k < daysEnabled.length; k++) {
                  if(daysEnabled[k] == day) {
                    if(k == daysEnabled.length - 1) {
                      forward = 7 - daysEnabled[k] + daysEnabled[0];
                      // console.log(forward);
                    } else {
                      forward = daysEnabled[k + 1] - daysEnabled[k];
                      // console.log(forward);
                    }
                  }
                }
              } else {
                console.log('not forwarded');
              }
            }
          }
        }
      });
      return forward;
    }

I want to access the forward value as the return from getDayForward function.


text:
Q: Cron - Check if enabled on boot I have a script and configuration file.

*

*Configuration file contains information about if script will run or not (enabled or disabled).

*If enabled, script must run in predetermined intervals.

I can write a cron job to run script in preset intervals and when script runs I can read the config file and if it is not enabled then I can exit.
However, I'm looking a more convenient way to do this. Is there any way to tell the cron's itself that this job is not activated in boot time? So cron will not start the job if it's not enabled (or the otherwise). Or is it possible to enable/disable job in runtime?
Thanks in advance.

A: Ah, now I undersand! That's a fairly common request:
All you need is to test for the existence of a given file, not its content.
E.g. if you want to run the cron job, create a file say in yr home directory: $ touch /home/you/cronjob_enable.
Then edit yr user crontab:
$ crontab -e
*/5 * * * *  /bin/bash -c 'test -e /home/you/cronjob_enable && /home/linux/test.sh'

That's it. As long as the file is there (empty or not, it's irrelevant) and you have permission to run /home/linux/test.sh, the script test.sh will run.
When you erase the file /home/you/cronjob_enable, the script test.sh will not be executed.


text:
Q: How to capture all the conversation happend in the Chat - using Bot framework I am trying out the Bot framework examples (Sandwich sample) and I want to check is there a way we can capture the complete conversation on the completion of chat.
Example:
I am trying to capture the complete conversation between both parties on the "OnCompletionAsyncDelegate" event.
Is there any alternative to capture all the conversation?
Thank You.

A: If you're using LUIS, one solution is to create your own Dialog class that extends LuisDialog,  override MessageReceived to transcribe the incoming message's Text, and have your other Dialogs extend this new class instead of LuisDialog.
If you're not using LUIS then your new class can just implement this logic in your own implementation of IDialog's MessageReceived.
The transcribing logic would need to log this text somewhere, perhaps table storage or dynamo db.
Does that help?

A: I have a tutorial that shows how to capture the conversation to a database:
Implementing A SQL Server Database With The Microsoft Bot Framework
The key piece of code that captures the conversation is:
// *************************
// Log to Database
// *************************
// Instantiate the BotData dbContext
Models.BotDataEntities DB = new Models.BotDataEntities();
// Create a new UserLog object
Models.UserLog NewUserLog = new Models.UserLog();
// Set the properties on the UserLog object
NewUserLog.Channel = activity.ChannelId;
NewUserLog.UserID = activity.From.Id;
NewUserLog.UserName = activity.From.Name;
NewUserLog.created = DateTime.UtcNow;
NewUserLog.Message = activity.Text.Truncate(500);
// Add the UserLog object to UserLogs
DB.UserLogs.Add(NewUserLog);
// Save the changes to the database
DB.SaveChanges();


text:
Q: What can be the filename of uploading location for ImageField? Whenever I create Cloth Model with cloth_image, the image uploads to upload_location.
My problem is instance.id returns None because the instance is not yet created. What can be the best upload_location for ImageField?
def upload_location(instance, filename):
    new_id = instance.id
    ext = filename.split('.')[-1]
    return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) #  <- Right Here!

class Cloth(models.Model):
    cloth_image = models.ImageField(upload_to=upload_location,
                                null=True,
                                blank=True)

I'm using AWS S3.

A: Just use the filename and not the id, e.g.
os.path.join('clothes', instance.user.id, filename)

Don't worry if filename already exists, Django automatically appends random strings at the end to avoid file replacements.

A: if you want unique filename, i think you can use uuid for it, for example
import uuid
import os

def get_file_path(instance, filename):
    base_dir = 'clothes'
    user.id = str(instance.user.id)
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join(base_dir, user_id, filename)


text:
Q: Icon is not displaying in android studio APK file hey there I have created an android application and I have set an icon to it in the Image asset and it worked well. When I run the emulator it displays the icon but the problem is that when I build an APK file of it and I transfer it to my mobile and run it it is not displaying the icon instead the same android logo is displaying.
Thanks if anyone can help me to sort out

A: Have you tried changing android:roundIcon and android:icon in your manifest file?
<application
    android:allowBackup="true"

    /*Change these*/
    android:icon="@drawable/yourIcon"
    android:roundIcon="@drawable/yourIcon"

    android:label="GPS Test"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


text:
Q: Passing String Type data to .NET PUT WEBAPI through Ajax I used to code in this way and it works fine:
C#:
[HttpPost]
public object Query([FromBody]string sql)
{
    // ...
}

Js:
$.ajax({
    url : "/api/controllerName/query",
    data : "=SELECT * FROM table1",
    dataType : "JSON",
    type : "POST",
    success : function(res){ console.log(res); },
    error : function(req, stat, err){ console.log(stat + ": " + err); }
});

So now I do it in the same way for a PUT API, but it doesn't work:
C#:
[HttpPut]
public object dispatchProduct(int id, [FromBody]string dispatchStatus = "dispatched")
{
    // ...
}

Js
$.ajax({
    url: "/api/auction/dispatchProduct/2",
    type: "PUT",
    data: "=blablabla",
    dataType: "JSON"
}).done( function createBiditem_doneHandler(result){
    console.log(result);
}).fail( function createBiditem_failHandler(req, stat, err){
    console.log(req);
    console.log(stat);
    console.log(err);
});

I got an exception:

{     "Message": "An error has occurred.",    "ExceptionMessage": "Optional
  parameter 'dispatchStatus' is not supported by
  'FormatterParameterBinding'.",    "ExceptionType":
  "System.InvalidOperationException",   "StackTrace": null }

Could anyone help? I have googled for quite a while, but all the cases are different than mine.
Thanks so much!

A: I think optional parameters are fully supported in WebApi but not sure 'FormatterParameterBinding could support it too.
May be you could remove that optional parameter and you can do in this way
[HttpPut]
public object dispatchProduct(int id, [FromBody]string dispatchStatus)
{
   if (dispatchStatus == null)
   {
        //..works same as before but without a exception
   }
}


text:
Q: Notepad++ Define Script to Save, Compile and View [Windows 10] I am able to successfully compile using XeLaTeX and view the resulting PDF in Sumatra with the following run code in Notepad++:
cmd /c cd /d "$(CURRENT_DIRECTORY)" && xelatex.exe "$(FILE_NAME)" & "C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe" "$(CURRENT_DIRECTORY)\$(NAME_PART).pdf"

However, I have to manually save the file each time before running the script. Is there an additional command that I can insert at the beginning that saves the .tex file to the current directory? I'm not a programmer, so I'm probably missing something very simple. Here's an MWE for testing purposes:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{lipsum}
\begin{document}
\section{Notepad++ and \LaTeX}
\lipsum[3]
\end{document}

A: Alright, the NPP_SAVEALL hint directed me to this question. I downloaded the NppExec plugin, manually extracted it to the plugins folder in Notepad++, and revised the run script to:
NPP_SAVEALL
cmd /c cd /d "$(CURRENT_DIRECTORY)" && xelatex.exe "$(FILE_NAME)" & "C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe" "$(CURRENT_DIRECTORY)\$(NAME_PART).pdf"

Now it works: save, compile and view in one keyboard shortcut! Hope this helps someone else!


text:
Q: Numerical Integration error for simpson's rule through taylor series I am looking at the derivation of the simpson's rule as well as an error analysis in my textbook and I am slightly confused over two things. Firstly, in the derivations, the text uses a taylor expansion of up to $ O(h^4)$. I am not exactly sure why it is only expanded up until this term.
Secondly, in terms of the integral, I am not sure where the first term $f(x_{1})(x-x_{0})$ comes from.

I understand the fact that he integrated the left hand side of the [4.22] equation and how he got every term except for the part about $f(x_{1})(x - x_{0})$, which I am not sure about.
Would someone please help me clarify ? is this a definition that if you have 3 points, you can only do a taylor expansion up to the 4th order ?
Thanks

A: That $f(x_1)(x-x_0)$ term is easy to explain: the author started with
$$\int f(x_1)dx=f(x_1)\int dx=f(x_1)(x+C)$$
wher C is the constant of integration. He could have chosen any constant here, but he went with $C=-x_0$. Then he gets
$$\int_{x_0}^{x_2}f(x_1)dx=\left.f(x_1)(x-x_0)\right|_{x_0}^{x_2}=f(x_1)(x_2-x_0)=2hf(x_1)$$
assuming $x_2-x_1=x_1-x_0=h$. The choice for the constant of integration $C$ is pretty much arbitrary, and I might have chosen $C=x_1$ so that the zero-order term looked consistent with the higher order terms, but the answer would have still been the same,
$$\int_{x_0}^{x_2}f(x_1)dx=\left.f(x_1)(x-x_1)\right|_{x_0}^{x_2}=f(x_1)\left((x_2-x_1)-(x_0-x_1)\right)=2hf(x_1)$$
He only took the expansion to third order because the first and third order terms integrate for $0$ and the zero and second order terms produce the integration formula, and we can get a really nice estimate of the error from the fourth order term; higher order terms would not give us such a clean estimate. Since $(x-x_1)^4\ge0$,
$$\int_{x_0}^{x_2}\min\left(f^{(4)}(\xi(x))\right)(x-x_1)^4dx\le\int_{x_0}^{x_2}f^{(4)}(\xi(x))(x-x_1)^4dx$$ $$\le\int_{x_0}^{x_2}\max\left(f^{(4)}(\xi(x))\right)(x-x_1)^4dx$$
So we can pull those extrema out of the integrals to get
$$\frac25h^5\min\left(f^{(4)}(\xi(x))\right)\le\int_{x_0}^{x_2}f^{(4)}(\xi(x))(x-x_1)^4dx\le\frac25h^5\max\left(f^{(4)}(\xi(x))\right)$$
So then we know that the error in Simpson's rule is
$$\frac1{24}\int_{x_0}^{x_2}f^{(4)}(\xi(x))(x-x_1)^4dx=\frac{h^5}{60}f^{(4)}(\xi)$$ for some $x_0<\xi<x_2$
Hmm, that's not the right answer because it should be $\frac{h^5}{90}f^{(4)}(\xi)$. I guess the difference is that we only have an estimate for $f^{\prime\prime}(x_1)$, not the true value.


text:
Q: how to perform migration for django table created without any app I have a django project in which I have not created any app, I directly wrote models for the project in models.py file inside project folder.
But whenever I perform
python manage makemigrations

it says : No changes detected
so when I perform
python manage migrate

it says :   No migrations to apply.
So is there any different way to perform migrations if you are directly writing your models without creating any App for django project

A: You should add your app to django INSTALLED_APPS settings, if not, then, you dont have an django app.

A: migration on django is an app basis.

migrations are created and run on a per-app basis, https://docs.djangoproject.com/en/1.8/topics/migrations/

so you should create an app and add it to INSTALLED_APPS as levi suggest. However, it is possible if you're kind a want to only use one app to manage all the models for your db under models.py, BUT it's messy.
i recommend to use the migration on app basis.


text:
Q: Incorrect Email send from address We have all the email address set in System -> Config -> Store Email Addresses.
However, the emails are being sent from the mail server.
Is there another setting that I am missing for send from Email address?


text:
Q: How to implement pagination with a limited number of pages visible and Previous and Next page buttons I have written a pagination code in PHP which displays all page numbers at once. I want to limit the number of pages shown by the script so when there are 200 pages, only the first 10 pages will be visible when the first one is selected. Then I want to add Previous and Next page buttons to switch between active pages.

/* Pagination Code starts */
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_POST["page"])) {
    $page = $_POST["page"];
    $start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($sql);
$pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();

$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
    $per_page_html .= "
";
    $page_count=ceil($row_count/ROW_PER_PAGE);
    if($page_count>1) {
        for($i=1;$i<=$page_count;$i++){
            if($i==$page){
                $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page current" />';
            } else {
                $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />';
            }
        }
    }
    $per_page_html .= "
";
}

$query = $sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();

A: Add 'Previous' and 'Next' before and after the for loop respectively.
See the code below:

/* Pagination Code starts */
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_POST["page"])) {
    $page = $_POST["page"];
    $start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($sql);
$pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();

$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
    $per_page_html .= "
";
    $page_count=ceil($row_count/ROW_PER_PAGE);
    if($page_count>1) {
        $prevpage = 1;
        $nextpage = $page_count;
        if($page_count> 10){
            $prevpage = ($page-5>0)?($page-5):1;
            $nextpage = ($page+5<=$page_count)?($page+5):$page_count;
        }
        if($page>1){
            $per_page_html .= '<button type="submit" name="page" value="1" class="btn-page" >First Page</button><button type="submit" name="page" value="'.($page-1).'" class="btn-page" >Previous Page</button>';
        }
        for($i=$prevpage;$i<=$nextpage;$i++){
            if($i==$page){
                $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page current" />';
            } else {
                $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />';
            }
        }
        if($page<$page_count){
            $per_page_html .= '<button type="submit" name="page" value="'.($page+1).'" class="btn-page">Next Page</button><button type="submit" name="page" value="'.$page_count.'" class="btn-page" >Last Page</button>';
        }
    }
    $per_page_html .= "
";
}

$query = $sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();

Happy coding :)


text:
Q: Get all parameters from url and insert on all hrefs except one friends, I'm in need of your help. I need to get parameters from the url
ex: www.test.com/?s=1&param=2&param=3

and put in all hrefs on the page, minus the parameter = s. then it would look like this:
ex: href='www.test.com/?param1&param=2'

This is already happening, the problem is that I don't want to pass to hrefs: the s parameter
complete code:
$(document).ready(function() {
 function querystringToDict(querystring){
    if (querystring.length === 0) {
       return {};
     }
   let queryDict = {}
   querystring.split("&").forEach(function(item) {
      queryDict[item.split("=")[0]] = item.split("=")[1]
   });
      return queryDict;
   }

  var queryDict = querystringToDict(location.search.substr(1));
  var queryHref, queryFinal = {};
  var lctSearch = location.search;

  $('html a').each(function() {
      // if the href contains www.test.com insert params
     if ($(this).prop('href').includes('www.test.com')){
        if(lctSearch != ''){
           param = $(this).attr('href').split('?')[1] === undefined ? '' :
                   $(this).attr('href').split('?')[1];

           queryHref = querystringToDict(param);
           queryFinal = Object.assign({}, queryHref, queryDict);
           paramFinal = Object.keys(queryFinal).map(key => key + '=' + queryFinal[key]).join('&');
           $(this).attr('href',$(this).attr('href').split('?'[0].concat('?',paramFinal));
           }
        }
    });
});

A: You can exclude it in the function you have written:
querystring
  .split("&")
  .filter(el => el.split("=")[0] != 's')
//              ^^^^^^^^^^^^^^^^^^^^^^^---- exclude the "s" parameter
  .forEach(function(item) {
  queryDict[item.split("=")[0]] = item.split("=")[1]
});


text:
Q: Hypothesis testing two unfair coins to see if they have 'equal' bias Consider tossing two unfair coins 100 times:
How can I know using the two sets of Heads or Tail results whether the two coins have an equal (or similar) bias with a 95% confidence?
I am currently thinking the way is to do this through a student's t-test, though the p-value is off when both coins have a probability 1 of flipping to heads. (Resulting in no variance between the sets of coins)
The student's t-test assumes that the data is normally distributed, is it ok anyway to use this data because of the central limit theorem? (or should I repeat these 100 flip experiments and use those for a t-test)
My current null hypothesis is that both coins are equally biased, so the alternate hypothesis would be that the coins are differently biased.

A: For exact inference on each coin you can invert the CDF of a binomial distribution to construct a confidence interval.  Here is a related thread that discusses this idea.  For comparing the coins to each other to see if there is evidence that the long-run probability of heads differs between the two coins you can invert either the two-sample Wald, score, or likelihood ratio test to construct a confidence interval.  You could consider using a log or logit link function to improve the operating characteristics of the test.  This will have you investigating whether the rate ratio or the odds ratio equals 1 instead of the difference in rates equalling 0.  Here is an example investigating a single proportion by inverting a Wald test with a log link or a logit link.
If you prefer ease of implementation and your sample size is not small then you can use an identity link function while inverting a one-sample and two-sample Wald test:
$100(1-\alpha)\%$ CI for $p_1$ and $p_2$:
$$\hat{p}_j\pm z_{1-\alpha/2}\sqrt{\hat{p}_j(1-\hat{p}_j)/n_j}, \hspace{3mm}j=1,2 $$
$100(1-\alpha)\%$ CI for $p_2-p_1$:
$$\hat{p}_2-\hat{p}_1 \pm z_{1-\alpha/2}\sqrt{\hat{p}_2(1-\hat{p}_2)/n_2 + \hat{p}_1(1-\hat{p}_1)/n_1} $$
where $z_{1-\alpha/2}$ is the $100(1-\alpha/2)^{th}$ percentile of the standard normal distribution and $j$ indexes the two coins.  For a 95% CI you would use $z_{1-\alpha/2}=1.96$.
If the $100(1-\alpha)\%$ confidence interval for the difference in proportions contains 0 then the hypothesis $H_0: p_2-p_1=0$ is plausible at level $\alpha$, as are all of the other hypotheses that make up the confidence interval.


text:
Q: How to hide ImageView in ListView correctly? I want to add to ListView information about widgets:
public class Widget {
    String w_type;
    String title;
    String desc;
    String img;
    //....
}

I want to show image in listview if img field isn't empty and hide ImageView in ListView if it's empty. There is current code of getView method from my adapter for listview:
public View getView(int i, View someView, ViewGroup arg2) {
    LayoutInflater inflater = LayoutInflater.from(context);
    if (someView == null) {
        someView = inflater.inflate(R.layout.widgets_list, arg2, false);
    }

    ImageView img = (ImageView) someView.findViewById(R.id.pic);

    if (!img_url.equals("")){
       Picasso.with(context).load(img_url).into(img);
       }
       else {
           img.setVisibility(View.GONE);
       }

    return someView;
}

It hiding ImageView not only when img field is empty but sometimes when it's not empty too. How can I fix it?

A: I think your ImageView is still hidden from an earlier call to img.setVisibility(View.GONE); so just re-show it again.
   if (!img_url.equals("")){
       Picasso.with(context).load(img_url).into(img);
           img.setVisibility(View.VISIBLE);
       }
       else {
           img.setVisibility(View.GONE);
       }

A: Usually Picasso makes a thread and load the images. The easiest way but instead you can make some call back functions like.
in here
Picasso.with(context)
        .load(imageUrl)
        .into(img, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                    }
                });


text:
Q: Designing a simple controller for a hot plate I have a hotplate with a TS port meant for an external temperature control unit. The manufacturer's customer service told me that this port is not connected to anything internally in the model I own. Upon opening the appliance I found that it is in fact connected to an opto-TRIAC on the heating element control board.
Using the values listed in the opto-TRIAC's datasheet, I cobbled together my own controller with a black-box temperature hysteresis module, a 12 V power supply, and a current limiting resistor.
It works initially, but if it's left on for an extended period of time one (or both?) of the TRIACs stick on and will not shut off until the entire appliance is turned off for about a minute.
I am not savvy enough to diagnose this alone, but I thought I might find help here. I attached pictures of the heating element control board, back and front, as well as diagrams of the control board circuit and my controller. I did my best to transcribe the circuit into a diagram but it's possible that there are errors.

Here are links to the full resolution images:
Heating control board picture
Heating control board diagram
Hysteresis controller diagram
Opening the thumbnails in a new tab will also display the full resolution source.

A: I have solved the issue, here is my solution for reference.
Initially I believed that the TRIAC was only latching on when I used my external controller. After testing the hotplate a second time without my controller I found that the TRIAC latched on even when using the manual potentiometer control if it was left on long enough.
My first step after testing it again was to replace the BTA06 TRIAC, this did not resolve the issue. However, mounting a small heatsink to the new TRIAC fixed the issue immediately.


text:
Q: Selenium web driver not able to inspect/find the "Select" html tag (combo box) I am using SeleniumChrome Driver. I used Xpath, id, and name attributes to inspect "Select" HTML tag. but for some reason it not able to find this tag. Attached is the image .
I tried with xpath:
WebElement aSelectWebEleAccountNumber = achromeDriver.findElement(By.xpath("//*[@id='accountNumberGroupSelect']"));

Tried with CSSSelector:
WebElement ass = achromeDriver.findElement(By.cssSelector("#accountNumberGroupSelect"));

Tried with the name attribute. It canf't find the "select" tag.
WebElement ass = achromeDriver.findElement(By.name("sections(ACCOUNT_INFO).accountNumberGroup.selectedLookupKey"));

Here is the HTML source,
Select Element tag
Any suggestions?

A: Try  achromeDriver.findElement(By.id(...)) ?
In C#, there is a SelectElement class to wrap the select element operations, there might be implementation in your language as well.

A: You can implement combobox by using Select class directly.
But at first check that the element which you are trying to locate is enabled or not


text:
Q: Select values from R dataframe column I'm working on a class project using a Chicago crime data set and R. One of the attributes in the data set is Block which contains partial addresses where the incident occurred. For example:
+--------------------------+
|           Block          |
+--------------------------+
|  45xx N Locust Grove St  |
|   65xx Hawthorne Ave     |
+--------------------------+

The values in Block vary in length but I am wanting to create a new variable with the street type, St, Ave, Blvd, etc. I have tried using the separate function from tidyr.
df <- df %>%
   separate(Block, into = c("partial.address, "type"),
           sep = " ", extra = "merge", fill = "left")

However, this returns the number, 45xx, as the partial.address value and the remaining value is in type. How can I select the street type from the address?
I'm hoping to get something like this as output:
+--------------------------+-------------+
|     partial.address      |     type    |
+--------------------------+-------------+
|  45xx N Locust Grove     |      St     |
|   65xx Hawthorne         |     Ave     |
+--------------------------+-------------+

A: You can use extract :
tidyr::extract(df, Block, c("partial.address", "type"), "(.*)(St|Ave)")

#      partial.address  type
#1 45xx N Locust Grove    St
#2      65xx Hawthorne   Ave

Or using stringr :
library(dplyr)
library(stringr)

df %>%
  mutate(type = str_extract(Block, '(St|Ave)'),
         partial.address = str_remove(Block, type))

You can include more patterns in (St|Ave) if you have more.

If we want to capture the last word of each Block we can use :
df %>%
  mutate(type = str_extract(Block, '\\w+$'),
         partial.address = str_remove(Block, type))

data
df <- structure(list(Block = c("45xx N Locust Grove St", "65xx Hawthorne Ave"
)), class = "data.frame", row.names = c(NA, -2L))


text:
Q: Stone-Cech compactification and discrete space Suppose $X$ is a discrete space and $A$ and $B$ are disjoint subspaces of $X$.
Then consider $\beta(X) \times \beta(X)$,
We can think of $A \times A, B \times B$ as a subspace of $ \beta(X) \times \beta(X)$, where $\beta(X)$ is Stone-Cech compactification of $X$.
Then it's not true that $\overline{A \times A} \cap \overline{B \times B}$ is empty. So $\overline{A} \cap \overline{B}$ is non-empty.
But in Munkres' Introduction to topology,
There's an exercise which says that

If $X$ is discrete space and $A$ is a subspace of $X$, then show that $\overline{A}$ and $\overline{X \setminus A}$ are disjoint.

It seems to me that those are contradicting to each other. Is there any missing point I couldn't see? Any comment will be appreciated.

A: Closures are taken in the (product of) compactification, not in the original $X$. And the compactification is not discrete. Hence no contradiction with Munkres.
The fundamental reason is that if $A\subseteq B\subseteq C$ then the closure of $A$ in $B$ need not be equal the closure of $A$ in $C$. In fact the latter may be bigger. To visualize this consider $X=\{0, 1\}$ with the antidiscrete topology $\{\emptyset, X\}$ and $A=B=\{0\}$. Note that $A,B$ are discrete and so the closure of $A$ in $B$ is just $A$. But the closure of $A$ in $X$ is whole $X$.
The situation when the intermediate closure is equal to the outer closure is when the middle subspace $B$ is closed in $X$. In your situation that would require $X$ to be closed in $\beta(X)$ and this can only happen when $X$ is compact to begin with (and so it is equal to its own Stone-Cech compactification).


text:
Q: How to calculate distance with lat long dynamically using php and mysql? In location table i have these columns:lat,long,date,userid
i want to display how much distance covered by particular user with my
location table.
How to calculate distance in kilometer with help of lat long and query
 for this to display this data front side.
please refer below image for the same.

A: I would consider this a duplicate question.
Please see: Measuring the distance between two coordinates in PHP
Or google the Haversine formula.


text:
Q: jQuery Navigation - need help with positioning and accordion behavior The sidebar navigation here: http://dev.southernlivingplants.com/in_the_garden needs some TLC.
There are a couple of issues that I am trying to resolve and could use some assistance:

*

*The accordion action works fine but the single line item links (that do not accordion) do not link correctly to their pages. What is preventing that?

*With an accordion open (like The Collection) if you mouse over the parent link below it Find your Zone, it highlights the entire section before it.

*Is there a way to keep a section open while on a specific page?
here is the code:
The HTML

the collection

shrubs

groundcovers/
grasses

trees

tropicals

fall bulbs

spring bulbs

annuals

perennials

find your zone

in the garden

care tips

color guide

common pests

where to buy

    about us

history

media room

events

botanical gardens

testimonials

plant videos

contact us

The Javascript:
function initMenus() {
    $('ul.menu ul').hide();
    $.each($('ul.menu'), function(){
        $('#' + this.id + '.expandfirst ul:first').show();
    });
    $('ul.menu li a').click(
        function() {
            var checkElement = $(this).next();
            var parent = this.parentNode.parentNode.id;

            if($('#' + parent).hasClass('noaccordion')) {
                $(this).next().slideToggle('normal');
                return false;
            }
            if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                if($('#' + parent).hasClass('collapsible')) {
                    $('#' + parent + ' ul:visible').slideUp('normal');
                }
                return false;
            }
            if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                $('#' + parent + ' ul:visible').slideUp('normal');
                checkElement.slideDown('normal');
                return false;
            }
        }
    );
}
$(document).ready(function() {initMenus();});

The CSS:
ul.menu, ul.menu ul {
  list-style-type:none;
  margin: 0;
  padding: 0;
  width: 10em;
  float: left;

}

ul.menu a {
  display: block;
  text-decoration: none;
  font-size: 15px;
  color: #54301A;
}

ul.menu li {
  margin-top: 1px;
  border-bottom: 1px solid #54301A;
}

ul.menu li a {
 /* background: #f8f2e3; */
  color: #000;
  padding: 0.5em;
}

ul.menu li a:hover {
  background: #f8f2e3;
}

ul.menu li ul li {
  border-bottom: 1px dotted #54301A;
 }

ul.menu li ul li a {
  /* background: #f8f2e3; */
  color: #000;
  padding-left: 15px;
}

ul.menu li ul li a:hover {
  background: #f8f2e3;
 /* border-left: 5px #000 solid; */
  padding-left: 15px;
}

Thanks!

A: Here are the answers to your issues:
1) The return false; statement in the following code is preventing the normal behavior:
if($('#' + parent).hasClass('noaccordion')) {
            $(this).next().slideToggle('normal');
            return false;
        }

2) Add clear: left; to the following CSS selector ul.menu li
3) Yes, this is possible using Javascript, but requires a little bit of work :)

A: http://jsfiddle.net/JVwTB/

*

*Removed the third if block, and return false;

*Added > to some of your CSS rules

A: Wish I had a clearer answer, but it looks like your .click() function is consuming the click event, and not passing it on to the element itself. Usually this is done explicitly via a call to stopPropagation(), but since you're not doing that here, I would think the event would still trigger the href.
Maybe you could explicitly redirect the browser in your javascript near the if statement if($('#' + parent).hasClass('noaccordion')) ... as a workaround.


text:
Q: Defining an atomic<> as a static variable inside a function C++11 mandates that static variables inside a function are atomically initialized for the first run of the function. The only way to do that efficiently is double-checked locking to prevent an expensive mutex-lock all the time.
I just had the necessity to have an static atomic<size_t> inside a function. It wouldn't make sense if such an atomic would be atomically initialized through double-checked locking. Instead it should be handled like another static initialized non-const native variable.
I checked the generated code with VC++ and Intel C++ under Windows and clang++ and g++ under Linux and all generated code according to my expectations. But is this really reliable and mandated by the standard that atomics should be handled independent of other objects here ?

A: The default constructor of std::atomic is constexpr, although until C++20 that's because it's trivial and the object can't yet be used.  That means that no dynamic initialization is required, which is as close as the standard gets to saying that this is efficient.

A: Davis Herring is mostly right, it's because the datatype is a trivial datatype and the compiler can inspect its initialization to not have any side-effects (constexpr construction actually isn't necessary). I checked that with the following code:
#include <iostream>

using namespace std;

struct S
{
    S( int i ) : i( i ) {}
    operator int() { return i; }
    ~S() {}
private:
    int i;
};

S &f();

int main()
{
    cout << f() << endl;
}

#if defined(_MSC_VER)
__declspec(noinline)
#elif defined(__llvm__) || defined(__GNUC__)
__attribute((noinline))
#endif
S &f()
{
    static S s( 123 );
    return s;
}

The above code generates the usual double-checked locking initialization. If you comment out the destructor of S the code in f() just returns a reference to statically initialized data in modifiable memory.


text:
Q: dmidecode showing less Memory Capacity than Motherboard spec? We got a supermicro server, http://www.supermicro.com/products/system/1u/5016/sys-5016i-ur.cfm, according spec, the server supports up to 32G memory when using ECC Register Memory.
However, when I tried the dmidecode command, it says 24G max memory:
[root@c1 ~]# dmidecode | grep Maximum
Maximum Size: 256 kB
Maximum Size: 1024 kB
Maximum Size: 8192 kB
Maximum Memory Module Size: 4096 MB
Maximum Total Memory Size: 24576 MB
Maximum Capacity: 24 GB
Maximum Value: Unknown

Which one I should trust?

A: Trust the manufacturer. But the supported memory arrangements are quite complex, so be careful. For example, the only way to get 32GB is with 4 x 8GB Quad Rank RDIMMs.


text:
Q: How Backbone.js with rest based service using Asp.NET MVC 4 I implemented some code using backbone.js in Asp.NEt MVC3  and found backbone.js very helpful. Actually I am developing  the data warehouse application where user at view side can run/save his data analysis. And after relogin can re-run the saved analysis.  On clicking the save button at toolbar system persist the analysis in DB.
My question is that can someone point links where backbone.js  interacts with  rest based service using Asp.NET MVC 4 so to save/retrieve the data in DB .
Please do advice me the better way as well.

A: I've built several very large systems on top of ASP.NET MVC4 and WebAPI, with Backbone, recently. I highly recommend WebAPI. It's very easy to use, and works very well with Backbone.
http://www.asp.net/web-api
As one example of an app that I've built with it:
https://ravenhq.com/
The registration, login, management, and account settings are all Backbone on top of WebAPI.


text:
Q: How to program Lattice iCE40 ultra with a microcontroller I am trying to program a iCE40 ultra FPGA with a stm32F4 microcontroller and I am trying to figure out how to load the configuration file onto the micro so that it can be sent to the FPGA by SPI to program it. The application note says that this can be done and has some pseudo code but it seems like it is for use with a computer and not a microcontroller. Both the micro and FPGA are on a PCB that I designed and have a SPI channel between them. This will get used after the programming for just communication between the two.
The configuration file is a .bin file or .hex file and I am unsure of how to load one of these files onto the stm32 and send it to the FPGA. I am trying to do it this way because I was hoping to not have to buy a programming cable and include flash memory on my PCB to store the program since I already need SPI communication between the micro and FPGA for the application I was hoping to make things easier on my self and may have done the opposite...
Here is the function that I have written to send the file across. I know that I need to open the file somehow and send it across. All of the other timing comes from the programming guild for the FPGA.
static void FPGA_Programming(void){

    char FPGA_TimeOut = 0; // Error timeout
    uint8_t dummyBits[7];
    for(char i = 0; i < 7; i++){ // loads dummy bits to be transmitted
        dummyBits[i] = 0b01010101;
    }
    /* Write FPGA config pin and SS to low for at least 200 ns to reset and start FPGA
     * in SPI Slave Configuration
     */
    HAL_GPIO_WritePin(FPGA_Config_GPIO_Port, FPGA_Config_Pin, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(FPGA_SS_GPIO_Port,FPGA_SS_Pin, GPIO_PIN_RESET);
    HAL_Delay(1);
    HAL_GPIO_WritePin(FPGA_Config_GPIO_Port, FPGA_Config_Pin, GPIO_PIN_SET); // Set high to turn on FPGA THIS PIN SHOULD STAY HIGH!
    HAL_Delay(2); // Wait for FPGA to clear sys memory
    // SEND FPGA CONFIG FILE
    while(!HAL_GPIO_ReadPin(FPGA_CDone_GPIO_Port, FPGA_CDone_Pin)){ // wait for CDone to go high when config is done and successfull
        HAL_Delay(1);
        if (FPGA_TimeOut == 5) { // if 5 milliseconds have passed and CDone has not gone low
            // send to debug FPGA ERROR Programming
            break;
        }
        FPGA_TimeOut++;
    }
    HAL_SPI_Transmit(&hspi1, dummyBits, 7, 10 ); // wait for FPGA to start

}

Any help with loading the file and opening it with the micro would be a great help.

A: The ice40 image needs to be included in the stm32F4 image. There are at least two possibilities.

*

*As suggested in an other answer. Let the linker do the job. The GCC linker can include arbitrary binary data, several ways to do this are outlined here. This require use of objcopy, or modifications to the linker script.

*Make a small utility to transform the binary ice40 image to a C data object, something like this (warning, code not well tested):
#include <stdio.h>
int main( void ) {
        int i=0,c;
        printf( "#include <stdint.h>\nconst uint8_t ice40image[] = {\n" );
        while ( (c = getchar()) != EOF )
                printf( "%#2.2x%s", c, (++i & 15) ? "," : ",\n" );
        printf( "};\n#define ICE40IMAGE_LEN %d\n", i );
        return 0;
}

The binary ice40 image is transformed into a header file:

./bin2uint8_t < ice40image.bin > ice40image.h

and ice40image.h is included in your stm32F4 program.  I prefer this method, it lends itself to later refinements such as compressing the FPGA image (it often has long runs of 0x00). In my opinion, a very good utility for this is 'icecmpr' in project iceStorm, see https://github.com/cliffordwolf/icestorm/tree/master/icecompr

A: If you use GCC and binutils as compiler/linker system you can use objcopy to generate a linkable module from any binary file. This can then be linked into your controller's readonly data space and accessed from your program.


text:
Q: Unable to parse date from curl output I am currently having issues when I try to parse a date. Basically, I am trying to parse the data from a curl output.
Here's my curl function :
function curlFunction(){
        $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://localhost/querydate.php" );
            curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);
            if(curl_exec($ch) === false){
                echo "Connection Error : Please Try Again!";
            } else {
                $h_output = $output;
            }
              curl_close($ch);

        return $h_output;

}

Here's the output from the curl function:
May 23, 2017

Here's how I declare it from my code :
$curlOutput = curlFunction();

Here's my PHP code for parsing :
var_dump(date_parse_from_format('F j, Y', $curlOutput) );

Here's the output :
array(12) { ["year"]=> int(2017) ["month"]=> bool(false) ["day"]=> int(23) ["hour"]=> bool(false) ["minute"]=> bool(false) ["second"]=> bool(false) ["fraction"]=> bool(false) ["warning_count"]=> int(0) ["warnings"]=> array(0) { } ["error_count"]=> int(3) ["errors"]=> array(2) { [0]=> string(22) "Unexpected data found." [32]=> string(13) "Trailing data" } ["is_localtime"]=> bool(false) }

Year and the Day are getting parsed except for the month.
Any help?
Thanks in advance!

A: Your code seems to be fine. A more simplified version is:
$curlOutput = 'May 23, 2017';

print_r(date_parse_from_format('F j, Y', $curlOutput) );

And this returns:
Array
(
    [year] => 2017
    [month] => 5
    [day] => 23
    [hour] =>
    [minute] =>
    [second] =>
    [fraction] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] =>
)

I can correctly see the year, month and day in the response.

A: Why make it so hard?
Use strtotime and use date to "parse" it.
$d ="May 23, 2017";
Echo strtotime($d) ."<br>\n";
Echo date("Y-m-d", strtotime($d));

https://3v4l.org/qSEID


text:
Q: Not sure what's wrong here, no matter what I try it returns the TypeError: 'NoneType' object is not iterable The assignment requires me to store the new values in a list and then update the list of lists with them. The program seems to work fine until I call 'monthly' after calling 'edit.' I'm assuming my problem is somewhere in the 'edit' function, but just in case I'm being a doof I've included the entirety of my code.
The functions and main method are in separate files
def Monthly(mSales):
    for row in mSales:
        print(row[0] + ' - ' + row[1])
    print()

def Yearly(mSales):
    total = sum(int(monthlySales) for _, monthlySales in mSales)
    average = total/ len(mSales)
    print("Yearly Total:       ",total)
    print("Monthly Average:    ",round(average, 2))
    print()

def Edit(mSales):
    editMonth = input("Three-letter Month: ")
    #index = 0
    months = ['Jan','Feb','Mar','Apr',
              'Jun','Jul','Aug','Sep',
              'Oct','Nov','Dec']
    if editMonth not in months:
        print("Invalid three-letter month.")
        print()
        return
    new_sales = input("Sales Amount: ")
    #index = months.index(month)
    #print(index)
    new_list = [editMonth, str(new_sales)]
    #mSales[index][1] = new_list
    for i in range(len(mSales)):
        if mSales[i][0] == editMonth:
            mSales[i] = new_list
            break

    print("Sales amount for {} was modified".format(editMonth))
    print()

import ch06_Monthly_Sales_commandFunctions_CJR as Func

def main():
    #initialize monthly sales list of lists
    monthlySales = [['Jan','616'],['Feb','466'],['Mar','796'],
                    ['Apr','238'],['May','310'],['Jun','726'],
                    ['Jul','987'],['Aug','604'],['Sep','951'],
                    ['Oct','958'],['Nov','238'],['Dec','610']]
    print("Monthly Sales program")
    print("")
    print("COMMAND MENU")
    print("monthly - View monthly sales")
    print("yearly  - View yearly summary")
    print("edit    - Edit sales for a month")
    print("exit    - Exit program")
    print(" ")

    while True:
        command = input("Command: ")
        #if statements correlating to command functions
        if command == 'exit':
            print("Bye!")
            break
        elif command == 'monthly':
            Func.Monthly(monthlySales)
        elif command == 'yearly':
            Func.Yearly(monthlySales)
        elif command == 'edit':
            monthlySales = Func.Edit(monthlySales)
        elif command != 'exit' or 'monthly' or 'yearly' or 'edit':
            print("Invalid command.")

A: You don't return anything from Edit and that None result gets assigned to monthlySales, which you pass into Monthly() on the next call, causing the error.
If you add return mSales to your Edit() function, your code works as expected.
Your code has some style issues as well, but that's well beyond the scope of what you're asking :).


text:
Q: Randomly distribute people into groups based on condition I have a list of people with their departments. I'm trying to distribute them into groups of equal size with the condition that they are not with people from their own departments where possible. I've got a list of 417 people with 19 departments and trying to put them in groups of 10.
Here is an example to illustrate what I mean:

Name   Department
 1   |     A
 2   |     B
 3   |     B
 4   |     C
 5   |     C
 6   |     C
 7   |     D
 8   |     D
 9   |     D
10   |     E

So here for example, if grouping in 3s I'd get something like
[1, 4, 7], [3, 6, 9], [2, 10], [5, 8]
Is there any known algorithm that fixes this problem. I currently have a dataframe that has a similar list to the one illustrated above but unsure on how to proceed from there.

A: Since you already have them sorted by department, with numeric "names", the solution is short.
df.groupby(int("Name")%10)

If my pre-conditions are wrong, then sort your DF by department, and then distribute by row instead of the numeric name.


text:
Q: How to convert super- or subscript to normal text in C# I'm writing a slug generator for making nice urls. I'd like to convert m² to m2, but in a generic way that does this for all superscript (or subscript), not just a simple replace statement.
Any ideas?

A: Thanks Johannes, you set me on the right track. The code with which I got it to work looks as follows:
public string ConvertSuperscript(string value)
{
    string stringFormKd = value.Normalize(NormalizationForm.FormKD);
    StringBuilder stringBuilder = new StringBuilder();

    foreach (char character in stringFormKd)
    {
        UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(character);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(character);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormKC);
}

I tried the canonical decomposition before, but it needed the compatibility decomposition to work properly.

A: If your string is going in the URL, then I assume it is some kind of regular non-formatted text in the form of unicode characters (as opposed to an MS Word doc for example). In unicode, you can only have certain characters as superscript or subscript. They are not that many and a simple switch statement would do the job.
If you are trying to convert formatted text that could contain all kinds of characters as superscript or subscript, that means they are not directly represented as unicode, and it would depend a lot on the format of the text. If so, please give more information in the question.


text:
Q: How long is the 60 days of Game Time Cards? I was looking into the subscription prices for Final Fantasy 14 and saw this on the product page

60-day game time cards and game time codes are available at participating video game retailers. They serve as a payment option that allows players to add 60-days of game time to their account at the Standard subscription rate, subject to account limits.

Sixty days of game time will be added to your account once you redeem the game time code on the Mog Station, the FINAL FANTASY XIV Account Management System. The 20-digit code can be found on the physical card, printed on a purchase receipt, or delivered via the digital retailer.

When I read "Sixty days of game time" I imagine I can clock up 1440 hours of gameplay before I am locked out (like a count down) but when it says "at the Standard subscription rate" I get confused as those show a monthly price and to me, that sounds like if I paid for 30 days they tick down even if I don't play the game.
How long are the 60 days of Game Time Cards? Is it 1440 hours of gameplay or 60 real-time days that count down even if I don't play?

A: It's just 60 days, all online subscription games do this.
(Or 30/90 half year or full year)
So if you are not logged in on that day, that day is technically speaking "wasted"

A: It's 60 real-time days
If you look at the page you quoted in French, the text you quoted is a bit different :

Les cartes prépayées 60 jours sont un moyen de paiement alternatif qui permet aux joueurs de prépayer leur abonnement. Elles sont disponibles pour les versions Windows, Mac et PlayStation®4.
Votre période de jeu de 60 jours commence au moment où vous enregistrez le code de 20 caractères qui se trouve sous le panneau à gratter au verso de la carte prépayée.

The part that is interesting here is the second part, which could be translated to (emphasis mine) :

Your game duration of 60 days begins when you register your 20 characters code located under the scratch panel on the back of the prepaid card.

Adding to this that most MMO nowadays have this subscription system, so it isn't surprising.

A: The standard model for MMO games is to encourage play hours/lingering inside the game, not discourage it. That is for social reasons: MMO marketing is largely social, and they want your friends to be online when you log in.
As such, they charge for calendar days/months of access, and encourage unlimited play during that time period.  They make you want to play as much as possible.
If the game charged by the minute, first that would discourage play, and people would economize on their play time.    Second, they would have to charge a much higher price per minute, and that would make their product less attractive compared to pay-by-the-month games.

A: A 60 day game card is roughly the equivalent of a two month subscription. It will expire exactly 60 days from when you apply the code, regardless of how many actual hours of gameplay you have over those 60 days.
This is common throughout most MMORPGs, including "Final Fantasy XI", the MMORPG prequel to "Final Fantasy XIV".

There are reasons one may favour buying time cards, as opposed to outright paying for a monthly subscription:

*

*The time card does not have to be used straight away. You can choose to start the 60 days whenever you want. By applying the code immediately before playing, you do not lose the days you might have lost between an automatic subscription payment and the next time you played the game.

*Time cards often do not require a credit card for automatic resubscription. You can prepay your subscription, without worrying about another payment being taken out if you later forget and are not otherwise playing the game.

*As mentioned in the quote, you can buy the time card from a physical retailer. Some people prefer purchasing from a physical retailer, while others may be restricted to it. As a great example, one of my favourite games of all time is "World of Warcraft"; as a sixteen year old child, I did not have access to online payments, and neither did my carer. Even then, there was no way they would allow me to have an online subscription. I was allowed to play "World of Warcraft" because I could save up my money and buy time cards from a physical video game store.

*You can give time cards to someone else; this makes it a lot easier, and a lot more convenient. You don't have to have their account details; you do not even need to tip them off that you're buying them the gift. All you need to do is buy a time card, and give this to them, instead.

Always check the price of the card versus the time it provides and the other subscription options. Often, MMORPG subscriptions are slightly cheaper on the recurring monthly payment model, as opposed to the prepaid time card model. If you can afford it, there are often discounts and further benefits for outright purchasing a yearly subscription, if this is at all available and applicable to your playing habits.
If it is your first time playing the game, there are usually also trials to try the game for free. This allows you to play the game before submitting to a monthly payment, saving you the additional costs if you decide the game isn't for you within the first week. Final Fantasy XIV has a free trial that lasts up to level 60.
Lastly, ask your friends before playing. There may be additional bonuses for signing up friends, and if your friends are playing, they will both know of these bonuses and be interested in signing you up with their refer code. These bonuses can both enhance your starting experience and provide additional time. If you are referred to "World of Warcraft" by a friend, for example, you gain bonuses to make it easier to level when playing with that friend. Your friend also gets free game time, which depending on the circumstance, they may be willing to share.


text:
Q: Deployment items in .runsettings I am migrating a large solution from VS 2010 to VS 2013. We have a few thousand tests that do not run when we use a .runsettings file. Our previous test settings file was of the .testsettings type. My understanding (after much frustrated Googling) is that in order to use the new test runner VSTest you need to use a .runsettings file. I haven't been able to find much documentation on what this file can support. This is basically the one resource available: http://msdn.microsoft.com/en-us/library/vstudio/jj635153.aspx
Our previous .testsettings file had a large section for deployment items that now cannot be found and thus the tests fail immediately. The problem is I can't seem to find out if including deployment items is still an option in a .runsettings file.
<Deployment>
  <DeploymentItem filename="C:\Solution\Project\SomeSettings.xml" outputDirectory="C:\Solution\Project\bin" />
</Deployment>

Does the new .runsettings test settings format support doing deployment items?

A: .runsettings does not support deployment items the same way as with .testsettings unfortunately, and I for one find this very frustrating as it was a very clean way of deploying dependencies.  There is a setting related to it in .runsettings (DeploymentEnabled), but all this seems to control is running tests in a separate directory, rather than the application's output directory.
After much trial and error, I ended up just changing all the .csproj files in my test projects to have a CopyIfNewer build action in the Properties window in Visual Studio so that all the dependencies would be copied into the output folder so they'd be found when running the tests.
I think all told I spent about 2-3 hours updating all the tests to get them running again.
On the plus side, things run a lot faster now as there's no need to copy all the binaries to a new directory after they are compiled, as everything runs "in-place".


text:
Q: Does AsyncTask run the doInBackground accordingly to each of its parameter order or randomly? For example there is an AsyncTask of a String... parameters , if I make a call like this :
AsyncTask<String, Void, Void> someTask = new myTask(myActivity.this);
someTask.execute(string1 , string2 , string3);

What is the internal order of execution of the doInBackground inside this task : does it treat string1 first then string2 and so on sequencely as they are provided when called , or does it treat the parameters randomly ?

A: First thing, parameters are not passed randomly. This answer will explain you more about parameters. Also check image from this answer. I am adding same image here for your understanding.

A: It may be serial on one thread or parallel, it actually depends upon which version of Android OS your app is running. For most of the case it would be serial on one background thread.
This is what google document says :-
Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.

Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.

This method must be invoked on the UI thread.

Check this link execute (Params... params) it will help you.
Hope it helps,
Thanks.

A: String... is a "vararg", which in this example converts all individual parameters into a String[], where the entries to the array are in the order they got passed into the method.
So using your example, (String[]) param[0] == string1, param[1] == string2, param[2] == string3 and so forth. This is for the ordering of param entries, as to how each entry in param is used, it depends entirely on your code.


text:
Q: Magento 2 single site to magento 2 multisite database migration We are having 3 different magento 2.0 stores CE functionally migrated to magento 2.4 multisite environment with test data.
We want to migrate actual data from all 3 sites to new portal.

*

*Is there any tool/script available?

*Which tables do we need to migrate?

*How we can avoid duplicate customer id/order id problem?


text:
Q: Is there a way to get value from specific  in Flask? I would like to get the values that are contained in a specific div. The HTML page contains several sections, which are activated when the corresponding button is clicked.
The problem is that having only one route function this is called only once and not every time the button is pressed to change the section.
I tried using value = request.args.get("home") but it returns None as soon as it loads the first section and then it doesn't return anything anymore.
Specifically I would like to get the values of the name, email, subject and message fields contained in the form.
Below I leave the code:
HTML (index.html):

Hello to everyone

Lorem ipsum dolor sit amet consectetur adipisicing elit.
               Eveniet labore nihil obcaecati consequatur. Debitis error doloremque,
               vero eos vel nemo eius voluptatem dicta tenetur modi.

About Me

 Lorem ipsum dolor sit amet consectetur adipisicing elit.
                     Eveniet labore nihil obcaecati consequatur. Debitis error doloremque,
                     vero eos vel nemo eius voluptatem dicta tenetur modi.

              <form method="POST" action="" class="contact-form">
                  <input type="text" id="name" name="name" required placeholder="YOUR NAME">
                  <input type="email" id="email" name="email" required placeholder="YOUR EMAIL">
                  <input type="text" id="subject" name="subject" required placeholder="ENTER SUBJECT">
                  <textarea name="message" id="message" cols="15" rows="8" placeholder="Message Here..."></textarea>

                          Send email

              </form>

.py
@main.route("/")
def home():
   # These do not return anything
   name = request.form.get('name')
   email = request.form.get('email')
   subject = request.form.get('subject')
   message = request.form.get('message')
   return render_template('index.html')

Thank you very much!

A: HTML
<form method="POST" action="/submit" class="contact-form">
  <input type="text" id="name" name="name" required placeholder="YOUR NAME">
  <input type="email" id="email" name="email" required placeholder="YOUR EMAIL">
  <input type="text" id="subject" name="subject" required placeholder="ENTER SUBJECT">
  <textarea name="message" id="message" cols="15" rows="8" placeholder="Message Here..."></textarea>

      Send email

</form>

Python
@main.route("/submit", methods=["POST"])
def form_submit():
   name = request.form.get('name')
   email = request.form.get('email')
   subject = request.form.get('subject')
   message = request.form.get('message')
   return name


text:
Q: using htaccess to remove .php from URL MY URL: http://localhost/test.php
I am using:
.htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

PHP:
$url = $_GET['url'];
echo var_dump($url);

But all I get for $url is:NULL NULL NULL NULL NULL NULL

A: Edit: adjusted to handle both the redirect and the rewrite.
RewriteEngine On
RewriteBase /

# Redirect .php URLs to rewritten URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.php$ $1 [L,QSA,R=301]

# Rewrite URLs for processing by router (index.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L,NC]

You should exclude the RewriteCond %{REQUEST_FILENAME} !-d condition, as it will attempt to access a directory if your URL matches it.  Probably not desirable when doing url rewriting.
index.php
$url = isset($_GET['url']) ? $_GET['url'] : null;
var_dump($url);

A: I just wanted to leave this somewhere for future users. This removes both HTML and PHP extensions from URLS.
#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]


text:
Q: Adding more features in perl script In the below perl script, I check my folder name (which is in the date format like 11-08-31) with the current date. If it matches, I process the folder. It also checks the previous day folder if there is no folder in today's date. I already asked this type of question here but I need to make some changes here and add new features as well:

*

*The script checks for the previous date if todays not find. But I need to check if the previous date has already been processed or not so that I donot process it again. So, Do I need to create a list for it?

*This script checks only for the one previous date. What if I have to check for the 2 previous days? Thanks for your help. hope you understand my doubts.
Updated: This perl script run automatically when It checks the curent date with the folder name. The folder is a tar folder which is loaded from other server.
So, basically I need to run the script if it matched with the folder name and current date.
Problem: Sometimes, I used to get the folder next day and my perl script checks only for the current date. The folder i get has the name which is previous date (not the current date).So, I need to do processing of the folder manually. I need to automate it in my perl script

#!/usr/bin/perl
use strict;
use warnings;
use Cwd;
use DateTime;
use File::Copy;

# set to your desired time zone
my $today = DateTime->now( time_zone => "America/New_York" );
my $td = $today->strftime("%y-%m-%d");

# strongly recommended to do date math in the 'floating'/UTC zone
my $yesterday = $today->set_time_zone('floating')->subtract( days => 1);
my $yd = $yesterday->set_time_zone('America/New_York')->strftime("%y-%m-%d");

my $dir = shift or die "Provide path on command line. $!";

if ($dir eq '.') {
    $dir = cwd;
}
elsif ($dir !~ /^\//) {
    $dir = cwd() . "/$dir";
}

opendir my $dh, $dir or die $!;
my @dir = sort grep {-d and /$td/ || /$yd/} readdir $dh;
closedir $dh or die $!;
@dir or die "Found no date directories. $!";

my $dday = "$dir/$dir[-1]"; # is today unless today not found, then yesterday
my $fdir = '/some/example/path/';
my @gzfiles = glob("$dday/*tar.gz");

foreach my $zf (@gzfiles) {
    next if (($zf =~ /BMP/) || ($zf =~ /LG/) || ($zf =~ /MAP/) || ($zf =~ /STR/));
    print "$zf\n";
    copy($zf, $fdir) or die "Unable to copy. $!";
}

A: If you want to persist the status of whether these directories were processed beyond a single run of your app, you could create a .processed file in each directory and check for the existence of this file before you process the directory.
If you just need to store the status of these directories (processed or unprocessed) during the execution of your script, you could use a hash keyed with the directory name:
my %PROCESSED = ();

if ($processing_done) {
  %PROCESSED{$dirname} = 1;
} else {
  %PROCESSED{$dirname} = 0;
}

You can check to see if each directory has been processed by reading the key value from the hash:
if (%PROCESSED{$dirname} == 0) {
 ... do some processing
} else {
 ... this one is already done
}

A: This solution finds all directories yet to be processed that are newer than the most recent direcory-date processed. You have manually record it the first time, (before the script is run). The script will update it from that point on.
The file could be named like my $last = 'dir_last.dat'; I just entered a file at the command line like:
C:\Old_Data\perlp>echo 11-07-14 > dir_last.bat

C:\Old_Data\perlp>type dir_last.bat
11-07-14

C:\Old_Data\perlp>

This assumes the newest directory was 11-07-14. You must find out this yourself before running the script.
#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;

my $dir = shift or die "Provide path on command line. $!";

my $last = 'dir_last.dat';

open my $fh, "<", $last or die "Unable to open $last $!";
chomp(my $last_proc = <$fh>);
close $fh or die "Unable to close $last $!";

opendir my $dh, $dir or die "Opening failed for directory $dir $!";
my @dir = sort grep {-d && /^\d\d-\d\d-\d\d$/ && $_ gt $last_proc} readdir $dh;
closedir $dh or die "Unable to close $dir $!";
@dir or die "Found no date directories after last update: $last_proc";

my $fdir = '/some/example/path';

for my $date (@dir) {
    my $dday = "$dir/$date";
    my @gzfiles = glob("$dday/*tar.gz");

    foreach my $zf (@gzfiles) {
        next if $zf =~ /BMP/ || $zf =~ /LG/ || $zf =~ /MAP/ || $zf =~ /STR/;
        print "$zf\n";
        copy($zf, $fdir) or die "Unable to copy $zf to $fdir. $!";
    }
}

open  $fh, ">", $last or die "Unable to open $last $!";
print $fh "$dir[-1]\n"; # record the newest date-directory as processed
close $fh or die "Unable to close $last $!";

Notice that I didn't rely on cwd like the first script. It really wasn't needed there and isn't needed here. opendir, glob and copy all can handle the dot (cwd) directory and relative paths.
The header includes the lines use strict; and use warnings;. Their purpose is to alert you of errors in your code (most all perl scripts should use them unless an expert decides to exclude them - for what reason I don't know). The first line tells unix where to find the interpreter (perl).

A: Well, another way to do it, as suggested by mugen kenichi, is to use Storable. This way stores a hash with all processed directories in it. Then when you run your program, it can check the hash to see if they have been processed.
You would need a one-time script to set up the hash of processed directories.
#!/usr/bin/perl
use strict;
use warnings;
use Storable;

# This script to be run 1 time only. Sets up 'processed' directories hash.
# After this script is run, ready to run the daily script.

my $dir = '.'; # or what ever directory the date-directories are stored in

opendir my $dh, $dir or die "Opening failed for directory $dir $!";
my @dir = grep {-d && /^\d\d-\d\d-\d\d$/ && $_ le '11-04-21'} readdir $dh;
closedir $dh or die "Unable to close $dir $!";

my %processed = map {$_ => 1} @dir;

store \%processed, 'processed_dirs.dat';

Then, a script to be run periodically to find and process your date directories.
#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
use Storable;

my $dir = shift or die "Provide path on command line. $!";

my $processed = retrieve('processed_dirs.dat'); # $processed is a hashref

opendir my $dh, $dir or die "Opening failed for directory $dir $!";
my @dir = grep {-d && /^\d\d-\d\d-\d\d$/ && !$processed->{$_} } readdir $dh;
closedir $dh or die "Unable to close $dir $!";
@dir or die "Found no unprocessed date directories";

my $fdir = '/some/example/path';

for my $date (@dir) {
    my $dday = "$dir/$date";
    my @gzfiles = glob("$dday/*tar.gz");

    foreach my $zf (@gzfiles) {
        next if $zf =~ /BMP/ || $zf =~ /LG/ || $zf =~ /MAP/ || $zf =~ /STR/;
        print "$zf\n";
        copy($zf, $fdir) or die "Unable to copy $zf to $fdir. $!";
    }
    $processed->{ $date } = 1;
}

store $processed, 'processed_dirs.dat';