text:
Q: python pickle not consistent I'm using python3.5 on Ubuntu. I trained a model by xgboost sklearn wrapper and save it by pickle.
Here is a link of the pickle file:
https://pan.baidu.com/s/1eSoPWxs
The question is each time I load it, the result is different.
For example:
a = pickle.load(open('mymodel', 'rb'))

b = pickle.load(open('mymodel', 'rb'))

print(a == b)

I got result False, but I think it should be True.
Can anybody explain this? Is there any way to solve this?
Thanks a lot!

A: When sklearn is not installed, the base class of the XGBoostModel is the same as object:
XGBModelBase = object
And you probably already know that two instances of object are not equal:
>>> import pickle
>>> pickle.dump(object(), open('test.txt', 'wb'))
>>> a = pickle.load(open('test.txt', 'rb'))
>>> b = pickle.load(open('test.txt', 'rb'))
>>> a == b
False

>>> object() == object()
False

I'll expect the behavior of __eq__ on the base class XGBModelBase to be consistent in the case sklearn is installed.
Also note that __eq__ was not overriden in the model class, so the behavior you have is as expected.
You may try comparing the dictionaries of the unpickled models and see if that works for you: a.__dict__ == b.__dict__

A: Finally I found the problem, which is nothing to do with pickle. There is something else which causes some randomization in each running.
Thanks for help! Sorry for bothering!
Ben


text:
Q: How to play a youtube video in side-by-side view on Android WebView I'm trying to make an Android App and I need help.
Do you have any idea how to play a online video (like a video on Youtube) in side-by-side view at the very same time by using Android WebView?
so, when I watch a Youtube video, I want to be able to have two views on left and right side on My Android SmartPhone Screen, and play and control the same video both on left and right views at the very same time.
Regards.
----2nd Feb, edited----
following things I've tried and failed.
・using Youtube API, get 3gp address, and try to play it with VideoView
・Using draw method and getDrawingCache method of WebView
・using onShowCustomView of WebView

A: Look at using a html5 video player like Video.js or Sublime Video.  You will need to create some javascript with each of these that fires the left and right video at the same time.
You can also look at what this guys did for some more inspiration.
http://html5demos.com/two-videos
The trick is getting the videos to fire at the same time if you need them in sync. It's not easy to achieve if you don't control the source video and server as you are relying on an outside party to do this. YouTube is NOT a good choice for serving your videos if you need them to be in sync as you can't guarantee the video load and launch times, or control if an ad will get injected into the video stream.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permissions to get facebook page ID via API? I need to get a Page ID from a page URL (ex: Facebook.com/Nike).
Facebook API returns a message saying I need a permission (Page Public Metadata or Page Public Content access) that is only available to apps with a Verified Business. Is this accurate? Is there no way to get Page ID from URL without an app that has a verified biz?

A: yes you can and without permission but it may fail when you deploy your app but give it a try

const fetch = require('node-fetch') // use 1.7.3 version
const getPageId = async (pageUrl) => {
    const res = await fetch(pageUrl)
    const html = await res.text()
    try {
        const id = JSON.parse("{" + html.match(/"pageID":"[\d+]*"/g)[0] + "}").pageID
        console.log(id);
    } catch (error) {
        console.log('something went wrong');
    }
}
getPageId('https://facebook.com/Nike') // id => 15087023444

good luck


text:
Q: javax.naming.NameNotFoundException I am running an example of ejb using JBoss5 Container. I am using an example
from here(Part one).
In the example I deployed bean in JBoss and an application in Tomcat(to acces the bean from JBoss). I am getting the error in the screen of tomcat server
javax.naming.NameNotFoundException: greetJndi not bound
( greetJndi is the jndi-name in jboss.xml file )
Is there any specific directory structure to deploy in JBoss?
Thanks

A: The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class
/com/mypackage/MyEJBInterface.class
/com/mypackage/etc... etc... java classes
/META-INF/ejb-jar.xml
/META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".

A:
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
├── greetBean.java
├── greetHome.java
├── greetRemote.java
└── META-INF
    ├── ejb-jar.xml
    └── jboss.xml

But as already mentioned, this tutorial is full of mistakes:

*

*there is an extra character  (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)

*a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)

*the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.


text:
Q: Playback large files on Windows Media Player during download My question is about writing a video file to the hard drive that is being downloaded from the network and playing it at the same time using Windows Media Player. The file is pretty big and will take awhile to download. It is necessary to download it rather than just stream it directly to Windows Media Player.
What happens is that, while I can write to the video file and read it at the same time from my own test code, it cannot be done using Windows Media Player (at least I haven't figured it out). I know it is possible to do because Amazon Unbox downloads does it. Unbox lets you play WMVs while it is downloading them. And Unbox is written in .NET so...
I've read the "C# file read/write fileshare doesn't appear to work" question and answers for opening a file with the FileShare flags. But it's not working for me. Process Monitor says that Media Player is opening the file with Fileshare flags, but it errors out.
In the buffering thread I have this code for reading the file from the network and writing it to a file (no error handling or other stuff to make it more readable):
// the download thread
void StartStreaming(Stream webStream, int bufferFullByteCount)
{
    int bytesRead;
    var buffer = new byte[4096];
    var fileStream = new FileStream(MediaFile.FullName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
    var writer = new BinaryWriter(fileStream);
    var totalBytesRead = 0;
    do
    {
        bytesRead = webStream.Read(buffer, 0, 4096);
        if (bytesRead != 0)
        {
            writer.Write(buffer, 0, (int)bytesRead);
            writer.Flush();
            totalBytesRead += bytesRead;
        }
        if (totalBytesRead >= bufferFullByteCount)
        {
            // fire an event to a different thread to tell
            // Windows Media Player to start playing
            OnBufferingComplete(this, new BufferingCompleteEventArgs(this, MediaFile));
        }
    } while (bytesRead != 0);
}

This seems to work fine. The file writes to the disk and has the correct permissions.
But then heres the event handler in the other thread for playing back the video
    // the playback thread

private void OnBufferingComplete(object sender, BufferingCompleteEventArgs e)
{
    axWindowsMediaPlayer1.URL = e.MediaFile.FullName;
}

Windows Media Player indicates that its opening the file and then just stops with an error that the file can't be opened "already opened in another process."
I have tried everything I can think of. What am I missing? If the Amazon guys can do this then so can I, right?
edit:
this code works with mplayer, VLC, and Media Player Classic; just not Windows Media Player or Windows Media Center player. IOW, the only players I need them to work with. ugh!
edit2:
I went so far as to use MiniHttp to stream the video to Windows Media Player to see if that would "fool" WMP into playing a video that is being download. Nothing doing. While WMP did open the file it waited until the mpeg file was completely copied before it started playing. How does it know?
edit3:
After some digging I discovered the problem. I am working with MPEG2 files. The problem is not necessarily with Windows Media Player, but with the Microsoft MPEG2 DirectShow Splitter that WMP uses to open the MPEG2 files that I am trying to play and download at the same time. The Splitter opens the files in non-Shared mode. Not so with WMV files. WMP opens them in shared mode and everything works as expected.

A: I've decided to answer my own question in case someone else runs into this rare situation.
The short answer is this: Windows Media Player (as of this writing) will allow a file to be downloaded and play at the same time as long as that functionality is supported by CODECS involved in rendering the file.
To quote from the last edit to the question:
After some digging I discovered the problem. I am working with MPEG2 files. The problem is not necessarily with Windows Media Player, but with the Microsoft MPEG2 DirectShow Splitter that WMP uses to open the MPEG2 files that I am trying to play and download at the same time. The Splitter opens the files in non-Shared mode. Not so with WMV files. WMP opens them in shared mode and everything works as expected.

A: Updated 16 March after comment by @darin:
You're specifying FileShare.ReadWrite when you're writing the file, which theoretically allows another process to open it for writing too.
Try altering your code to only request FileShare.Read:
var fileStream
    = new FileStream(
        MediaFile.FullName,
        FileMode.Create,
        FileAccess.Write,
        FileShare.Read); // Instead of ReadWrite

To quote MSDN:

FileShare.Read: Allows subsequent
  opening of the file for reading.
FileShare.ReadWrite: Allows subsequent
  opening of the file for reading or
  writing.

A: When you open the file for writing you shouldn't use FileShare.ReadWrite. You should instead use FileShare.Read:
var fileStream = new FileStream(
    MediaFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read);

When mplayer.exe process open the file for reading it will first try to open it with FileShare.Read which will fail but it then will reattempt with FileShare.ReadWrite which will succeed.


text:
Q: Resizing partitions without moving or losing data (dual boot) I have a Dell Studio 1555 currently dual booting Windows 7 & Ubuntu with a dedicated NTFS partition that serves as a bridge between OSes for my files, music, videos etc.
My Windows HDD is running low on disk space and would like to shrink the NTFS partition (bridge) and add to my Windows HDD as there is zero unallocated space left on my machine. The ext4 partition in which Ubuntu lies is small and does not need to be touched.
Is it possible to do this without reinstalling Windows and losing data?  I simply need to shrink an NTFS partition and add to my Windows HDD.

A: Windows 7 include a built-in functionality in Disk Management to shrink and expand partitions. I have used this feature several times, and it works great.

Here are a couple of guides on how to resize a partition in windows 7:

*

*Resize a Partition for Free in Windows 7 or Vista [HowtoGeek.com article]

*How to Resize a Partition in Windows 7 or Vista by Britec [YouTube video tutorial]

A: Yes. It is possible to resize it without losing data.  You can simply use Google to find out a how-to.
Using software like Partition Magic might make your life slightly easier, but I doubt it; as the built-in Windows 7 Disc Management software works great by itself.


text:
Q: Handle CustomTextEditor after opening I want to open a file with my custom text editor and after opening, the editor should scroll to a position given by an element id.
I use the vscode command
vscode.commands.executeCommand('vscode.openWith', fileURI, EditorProvider.viewType); to open the file, but the command does not return the opened editor like showTextDocument.
Is there a way to open the file like the following example but with my custom editor?
vscode.workspace
        .openTextDocument(path)
        .then((textDocument) => {
            vscode.window.showTextDocument(textDocument, 2, false)
                .then((editor) => {
                    //scroll to element
                });

Or alternatively: Is there a possibility to pass on the element id and to handle the parameter after opening the file?
Like this:
vscode.commands.executeCommand('vscode.openWith', fileURI, EditorProvider.viewType, scrollToElement);


text:
Q: How to open an url as a website with request python? I am trying to make a google map direction system with user accounts. However, I don't know how to open a url on a web browser with python. I know there is webbrowser.open() but my code contains a view.py request which needs the username and password to pass through POST in order to access the user information.
This is my view.py file
def maps(request):
    username = password = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username = username, password = password)

        if user is not None:
            if user.is_active:

                login(request, user)

                traffic_start = Auth.objects.get(user = user).traffic_start
                traffic_end = Auth.objects.get(user = user).traffic_end
                print traffic_start

    return render_to_response('maps.html', {'start':traffic_start, 'end': traffic_end})

And I am trying to open "localhost:8000/maps" with the request info after dismissing my GUI.
I know about urllib, urllib2, and webbrowser, but none of those seem to satisfy what I want to do, please help!!


text:
Q: My Div background is not turning blue when I hover a specific bullet line I want the div background to be blue when I hover Line 2.
I have also tried adding a class for the second li, but it was not working. Is there anything I have missed out?

ul {
  font-size: 2em;
}

div {
  background: pink;
  width: 200px;
  height: 200px;
  font-size: 5em;
  display: flex;
  justify-content: center;
  align-items: center;
}

ul li:nth-child(2):hover + div {
  background: blue;
}

Line 1

Line 2

Line 3

2


text:
Q: Firebase user displayName is null I'm running this code in my react app:
  componentDidMount() {
    modelInstance.addObserver(this);
    modelInstance.getSignInStatus().then((user)=>{
      this.setState({
        userName: user !== false ? user.displayName : "Sign in",
        logged_in: user !== false ? true : false

      });
    });
  }

And here is modelInstance.getSignInStatus():
  this.getSignInStatus = function () {
    return new Promise((resolve, reject)=>{
      firebase.auth().onAuthStateChanged(function(user){
        if (user){
          resolve(user);
        }
        else {
          resolve(false);
        }
      });
    });
  }

What happens is that this.state.userName is set to null, meaning that user.displayName is null. Why is this?

A:   state = {
    username: "",
    email: "",
    passwordOne: "",
    passwordTwo: "",
    error: null
  };

  onSubmit = event => {
    const {username, email, passwordOne} = this.state;
    const {history} = this.props;

    auth
      .createUserWithEmailAndPassword(email, password);
      .then(authUser => {
        db.doCreateUser(authUser.uid, username, email).then(() => {
          //you should clear your state fields here, for username / email etc
          console.log(authUser);
          //redirect user
          history.push(routes.HOME);
        });
      })
      .catch(error => {
        this.setState({error});
      });
    event.preventDefault();
  };

const auth = firebase.auth();
const db = firebase.database();
in order to acess doCreateUser
const doCreateUser = (id, username, email) =>
  db.ref(`users/${id}`).set({
    uid:id,
    username,
    email,
  });

A: I would use setState for checking the auth status like so:
firebase.auth().onAuthStateChanged(function(user){
    if (user){
      this.setState({user});
    }
}

Then you want the state of the displayName of the current user
componentDidMount() {
 modelInstance.addObserver(this);
 modelInstance.getSignInStatus().then((user)=>{
   this.setState({
     userName: this.state.user ? this.state.user.displayName : "Sign in",
     logged_in: this.state.user ? true : false
   });
 });
}

Obviously there has to be a name in the displayName property, If not you would have to update it. Let me know how this turns out.


text:
Q: How to highlight a column while filtering? I have been using Angular 4 with primeng 4 . When sorting is done with
p-datatable of primeng it highlights the column header being sorted.
Example : https://www.primefaces.org/primeng/#/datatable/sort
But when filtering is done here, the column header is not highlighted .
Example : https://www.primefaces.org/primeng/#/datatable/filter
When I checked  with chromebug, I was able to see every time sorting is done , a class gets added : ui-state-active , but this class does not get added while filtering .
Can anybody suggest me as to how I can highlight a column header while filtering like it's being done in sort in the example up above ?

A: style="#{car.remarks eq rsm.search ? 'color:red':'color:blue'}"


text:
Q: Sybase "interfaces" file issue There is a strange issue about sybase interfaces file.  We have an application which is run on solaris sparc OS and this application uses open client (sybase OCS-12_5) for database operations. When we upgrade our database server to sybase 15.03, our application didn't work. then I start the research for figure out why it does not work. End of the my research, i found the the reason is sybase15.03's interfaces file. Somehow,15.03's interfaces file is damaged i think. But sybase 12.5 interfaces file and sybase 15.03 interfaces file is same.I checked interfaces file for unknown character or carrige return character but there is no any strange character in it.  When I copied sybase12.5's interfaces file to sybase15 directory, application runs correctly. Is there anyone to explain this?
PS: Sybase libraries looks for $SYBASE env. variable and reads the $SYBASE/interfaces file for gather server information like server host and port
Thanks and regards.

A: Sounds like a minor error in the 15.0.3 interfaces file format.
Suggested approach to diagnosing:

*

*(Unix) diff the working and non-working interfaces files - if the servers they describe is the same the difference should be apparent pretty quickly.

*Check the format against the rules in Sybase documentation.

If the problem is still not manifest, then 'divide an conquer' might be the next step - try a smaller subset of the problem interfaces file.
Failing that, you could post equivalent entries from the two files here and see if the community can spot the problem.

A: Check for the space in between lines and make sure there is a extra empty line at the end of the interface file.
Another thing to make sure is the network setting you have choose. It should be the same. It would be most probably TCP. Some versions in 12.5 used to put other entries.
Another method to correct this is to use a DSCP method. This ensures that the interface file is correct.


text:
Q: How do I pass JavaScript values to Scriptlet in JSP and here is my code

another script is wriitten here which is a datpicker

Here is my jsp code

  <form class="contact_form" name="contact_form">

Extension of Date for Customer :- <%= alias%>

      Extend Date Here:
      <input type="text" id="start" name="start" pattern="\d{4}/\d{1,2}/\d{1,2}"  value='<%= sdf.format(edate) %>' required />

      <input name="env_id" type="hidden" value= '<%= rs.getInt(6) %>' />

   <%
    Date exp_date = start ;
        java.util.Date cur_date = new java.util.Date();
        long   diff= exp_date.getTime() - cur_date.getTime();
        long diff1=diff/(24 * 60 * 60 * 1000);
        System.out.println(diff1);
       %>

   <button id="submit" class="submit" value='<%= diff1 %>>' > Submit </button>

 Note: You can extend only upto one month

</form>

Can you suggest me how can i calculate diff and pass its result in script where the condition should check.Is any other way to perform this action?

A: If you want to do this then
create two hidden fields in you jsp and assign the values of them by your java script.
Then you submit the page or ajax call pass as querystring to jsp/servlet so you will have such values in jsp/servlet.


text:
Q: What test statistic should I use for this scenario? Context: The crankshaft bearings can be made from steel alloys with three different levels of densities,
namely, high, medium and low. A test was carried out to examine whether the
proportion of defective bearings using the aluminium oxide abrasive are the same across all
three densities of steel alloys. The results from a total sample of 300 bearings are summarised
in the table below:

Suppose I want to know whether the rates of defective bearings the same across the three densities of steel alloy. What test statistic should I use for this situation? Can I use a contingency table chi square test for this?
But I have only known/taught chi squared statistics for testing an association between categorical variables not the whether the rates are equal. So I am really conflicted, I don't recognise any other method. Many thanks


text:
Q: Why Angular HttpClient response is null? My Environments:

*

*Shop RestController : Spring Boot

*

*on localhost laptopn ubuntu 18:04

*ShopService: Angular HttpClient

*

*on localhost desktop pc windows 10

Problem:
My get request via HttpClient got the response null.
But if I use postman or on browser, I got my expected response body.
Angular Code:
const BASE_URL = 'http://pc01:8081/shopsystem/shops';
const  SHOP_NAME = 'Muster Shop';

@Injectable({
  providedIn: 'root'
})
export class ShopService {

  shop$: Shop;
  address$: Address;
  owner$: Owner;

  //header = new HttpHeaders({ 'Content-Type': 'application/json' });

  constructor(private http: HttpClient) { }

  public getShop(): Observable<Shop>{
    return this.http.get<Shop>(BASE_URL + '/' + SHOP_NAME);
  }

Response-Header:

Response:

Request on postman:

Spring Boot controller:

I have already tried with Observable with any and HttpHeaders with application/json
but same response.
Another thing: If my Spring Boot controller returns a List then I got the response body with contents.
Question:
Why I got a null or empty body in my HttpClient request?
How can I solve this?
Thank you

A: Your Angular HttpClient encodes the space in the path variable so it comes to the RestController as Muster%20Shop.
Then you try to find a record with that exact name which does not exist.
You have to decode the @PathVariable before you send it to your query as Muster Shop.

A: add annotation @CrossOrigin to your Controller class
@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class UserController {

    private final FileStorageService fileStorageService;
    private final GameService service;

    @GetMapping("{id}")
    public GameDTO getUserbyID(@PathVariable Long id) {
        log.info("get {} at {}", service.getUserbyID(id), Calendar.getInstance().getTime());
        return service.getUserbyID(id);
    }


text:
Q: SH file under Windows Ubuntu - Change directory not working I created a test.sh file and tried to run sudo ./test.sh
In that SH file, CD does not work, not able to find path.  CD to a mounted drive like CD /mnt/e/myfolder/myfolder1
I am running Ubuntu inside Windows.


text:
Q: does there exist example of this paticular type of function? consider $f:[a,b]\to \mathbb{R}$ such that $f(x) \in \mathbb{Q}$ when $x \in \mathbb{R} \setminus \mathbb{Q} \cap [a,b]$ and $f(x) \in \mathbb{R} \setminus \mathbb{Q}$ when $x \in \mathbb{Q} \cap [a,b]$. Then does there exist continuous function of this type ? I need an example ..if not then why?

A: Sure. Choose your favorite [the second-favorite works just as well] rational number $a$ and irrational numbers $b$, then define $f$ via
$$f(x) = \begin{cases} a & x \in \mathbb{R} \setminus \mathbb{Q} \\ b & x \in \mathbb{Q}\end{cases}.$$


text:
Q: JSON on Swift: Array to String/TextField Text I have problem with JSON Array that I want to be display on textfield. JSON is taken from URL. This is JSON structure:
    {
    description = "This is short decripton";
    );
    more-description =     (
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    );
    one-more-description =     (
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    );

And this is my code:
    import UIKit

    class RecipeViewController: UIViewController {
    @IBOutlet weak var descriptionTextField: UITextView!
    @IBOutlet weak var more-descriptionTextField: UITextView!
    @IBOutlet weak var one-more-descriptionTextField: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

    let urlAsString = "http://JSON-Address.com"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()

    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data,   response, error -> Void in
    do {
        if let jsonDate = data, let jsonResult = try      NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
            print(jsonResult)

            let jsonDescription = jsonResult["description"] as? String
            print("result: \(jsonDescription)")

            let jsonMoreDescrp: AnyObject? = jsonResult["more-description"] as? Array<AnyObject>
            print("result: \(jsonMoreDescrp)")

            let jsonOneMoreDescrp: AnyObject? = jsonResult["one-more-description"] as? Array<AnyObject>
            print("result: \(jsonOneMoreDescrp)")

            dispatch_async(dispatch_get_main_queue(),{

              self.descriptionTextField.text = jsonDescription
               self.more-descriptionTextField.text = jsonMoreDescrp as? String
                self.one-more-descriptionTextField.text = jsonOneMoreDescrp as? String

            });

        }
    } catch let error as NSError {
        print(error)
    }

    })
    jsonQuery.resume()
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

The problem is with jsonMoreDescrp & jsonOneMoreDescrp. Althought I've changed it to String, after running Xcode the result is empty. jsonDescription of course works, but this is just simple string.
I know I'm doing something wrong with Array, but - can you tell me what?

A: jsonMoreDescrp & jsonOneMoreDescrp are array. so, you can call like this
  self.more-descriptionTextField.text = jsonMoreDescrp[indexValue] as? String
  self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue] as? String

Hope this will help you.

A: [Updated] As Sudhir noticed there is also error in code, try this to show comma separated strings:
dispatch_async(dispatch_get_main_queue(),{

              self.descriptionTextField.text = jsonDescription
               self.more-descriptionTextField.text = (jsonMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
                self.one-more-descriptionTextField.text = (jsonOneMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
            });

Validate JSON structure online before using http://jsonlint.com/
Valid JSON:
{
    "description": "This is short decription",
    "more-description": [
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    ],
    "one-more-description": [
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    ]
}

A: Try this way, if it not works comment me the error you come across.
self.more-descriptionTextField.text = jsonMoreDescrp[indexValue].stringValue
self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue].stringValue

indexValue is the key of the value you want in the json.

A: try this code, it is much easy to use.
First of all parse all elements of map to the variables and than do what you want with knowing structure of just created variables.
let task = session.dataTask(with: url!) {
        (data, response, error) in
        do {
           let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
            if let desc = json["description"] as? String,
               let moreDesc = json["more-description"] as? [String],
               let oneMoreDesc = json["one-more-description"] as? [String] {
               dispatch_async(dispatch_get_main_queue(),{

           self.descriptionTextField.text = moreDesc
           self.more-descriptionTextField.text = moreDesc.joinWithSeparator("/n")
           self.one-more-descriptionTextField.text = oneMoreDesc.joinWithSeparator("/n")

        });

               }

        } catch let error {
            print (error)
        }
    }

    task.resume()

I have not tested it, but it should work. Feel free to ask.


text:
Q: Sed command writes the expression in outer ifmodule my config file has this
<IfModule mod_dir.c>
    DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>

I want to change index.php to index.temp
I created this
sed -i -e '/s/index.php/index.temp/' dir.conf

It makes this,
<IfModule mod_dir.c>
    DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
ndex.php/index.temp/

A: Your s/// command is prefixed by a / which would make sed misunderstand it.  It also looks as if the terminating single quote is not an ordinary single quote (' instead of '), but that may be an issue in just this question.
To change all instances of the string index.php to index.temp in some file dir.conf, use
sed -i 's/index\.php/index.temp/g' dir.conf

The dot in the pattern needs to be escaped as it is special in regular expressions (you could also have used [.] in place of \.). Also note that this is using -i for "in-place editing", which is not generally portable.
To make sure that you don't change myindex.php into myindex.temp or index.php3 into index.temp3, use \< and \> (or \b in place of both) to match the word boundaries:
sed -i 's/\<index\.php\>/index.temp/g' dir.conf


text:
Q: Cocos2d: Is it ok to have a pointer to a parent's class pointer? Silly question. Cocos2d is build around the parent-child hierarchy. I was wondering if it is ok to have a parent class (e.g. GameScene) and initialize a child class (e.g. SpriteHandler) with a pointer to a member of the parent class (e.g. CCSpriteBatchNode*).
I am trying to do this to optimize the number of CCSpriteBatchNodes. Here is a code snippet of my main class (GameScene style).
#import <Foundation/Foundation.h>
#import "cocos2d.h"

enum ShooterSceneLayerTags {
    HudLayerTag = 0,
    };

@interface ShooterScene : CCLayer {
    CCSpriteBatchNode* sharedSpriteBatchNode;
}

-(id) initWithSharedBatchNodeReference:( CCSpriteBatchNode*) sharedSpriteBatchNode;
+ (id) sceneWithId:(int)sceneId;
 @end

#import "ShooterScene.h"
#import "MainMenuScene.h"

//Layers
#import "LevelSpritesLayer.h"
#import "HudLayer.h"

@interface ShooterScene (PrivateMethods)
-(void) addLayers:(int)sceneId;
-(void) loadGameArtFile;
-(BOOL) verifyAndHandlePause;
@end

@implementation ShooterScene

+ (id) sceneWithId:(int)sceneId
{
    CCScene *scene = [CCScene node];

    ShooterScene * shooterLayer = [[self alloc] initWithId:sceneId];
    [scene addChild:shooterLayer];

    return scene;
}

-(id) initWithId:(int)sceneId
{
    if ((self = [super init]))
    {
        //Load game art before adding layers - This will initialize the batch node
        [self loadGameArtFile:sceneId];

        //Will add sprites to shared batch node for performance
        [self addLayers:sceneId];
        [self addChild:sharedSpriteBatchNode];

        //Do other stuff..
        [self scheduleUpdate];

    }
    return self;

}

-(void) addLayers:(int)sceneId
{
    LevelSpritesLayer * levelData = [LevelSpritesLayer node];
    [levelData initWithSharedBatchNodeReference:sharedSpriteBatchNode];

    [self addChild:levelData];

    switch (sceneId) {
        case 1:
            [levelData loadLevelOneSprites];
            break;
        case 2:
            [levelData loadLevelTwoSprites];
            break;
        default:
            break;
    }

    HudLayer * hud = [HudLayer node];
    [hud setUpPauseMenu];
    [self addChild:hud z:1 tag:HudLayerTag];
}

-(BOOL) verifyAndHandlePause
{
    HudLayer * hud = [self getChildByTag:HudLayerTag];
    if(hud.pauseRequested){
         [[CCDirector sharedDirector] replaceScene:[MainMenuScene scene]];

        return true;
    }
    else {
        return false;
    }

}
-(void) update:(ccTime)delta
{
    if([self verifyAndHandlePause]==false)
    {
        //Continue with animation etc..

    }
}

/**
 This is tricky. Could have loaded this in LevelData but as I am expecting to use the same SpriteSheet for HudLayer as well then
 I prefer to have the control here of this. Also, the same sheet could be used for more level, hence specific function is not bad
 **/
-(void) loadGameArtFile:(int) sceneId
{
    CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
    [frameCache addSpriteFramesWithFile:@"game-art-hd.plist"];

    sharedSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"game-art-hd.png"];
}

//As dealloc is deprecated, I prefer to remove unused sprites and texture on cleanup
-(void) cleanup
{
    [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
}

And here is one of the loadLevelData methods, it uses the sharedSpriteBAtchNodeReference
-(void) loadLevelOneSprites
{
    //Just a proof of concept example
    testSprite = [CCSprite spriteWithSpriteFrameName:@"File0.png"];
    testSprite.anchorPoint = CGPointMake(0.5f, 0.5f);
    testSprite.position = CGPointMake(160.0f, 240.0f);
    [sharedSpriteBatchNodeReference addChild:testSprite];
}

A: You can do that but if you are using ARC you should make your sharedSpriteBatchNode a weak pointer. If you don't you could end up with a circular reference.
What will happen with the circular reference is when the Director releases your game scene after it has finished running  your game scene will still have your child retaining it and your game scene will still be retaining that child. This circle will float off and never be able to be released as it is abandoned.

A: What [Ben] said. It should not be a retaining or strong reference, the latter being the default in ARC for instance variables.
There is one way to ensure under ARC that you're retain-cycle-safe even if you use a strong reference. Override the cleanup method and nil the reference there (under MRC you should also call release here, if you retained the reference):
-(void) cleanup
{
    sharedSpriteBatchNode = nil;
    [super cleanup];
}

Doing this in dealloc won't work. As long as a child node has a strong reference to a parent, it will not be deallocated. So you need to do this in cleanup, and ensure that all method calls where you can set the cleanup flag has that parameter set to YES.
But there are other, and I think better, solutions than passing a parent node in the initializer. For example you could get the shared batch node via a common tag from the parent, and either do that every time you need it (wrap it into a small function) or store it in a weak (non-retaining) instance var:
// onEnter is typically called right after init (during addChild)
// parent is already set here
-(void) onEnter
{
    [super onEnter];

    CCSpriteBatchNode* sharedBatchNode = [parent getChildByTag:kSharedBatchNodeTag];
}

Or get the parent and cast it, assuming the sharedBatchNode to be a property of the parent class:
-(void) whereEver
{
    ShooterScene* scene = (ShooterScene*)parent;
    CCSpriteBatchNode* sharedBatchNode = scene.sharedSpriteBatchNode;
    …

    // you can also reduce the above to a single line:
    CCSpriteBatchNode* batch = ((ShooterScene*)parent).sharedSpriteBatchNode;
}

Especially this latter solution is recommended. Even if you need to do that often it's fast. Casting is free, property access no more than a message send. Just be sure that the parent is in fact an object of the class you're casting it to.


text:
Q: P/Invoke - call unmanaged DLL from C# I'm attempting to call an unmanaged DLL from C#.  I've very little experience with unmanaged code and P\Invoke so I was hoping for an extra pair of eyes.
I don't have much information of the DLL except the function:
int Initialize(char *FileName, int Driver, int(*InfoLine)(char*), char *Message);

Infoline can be null.
So this is what I did in C#.
The import call:
[DllImport(@"c:\Core\initialization.dll", EntryPoint="Initialize", CharSet = CharSet.Auto)]
private static extern int Initialize([MarshalAs(UnmanagedType.LPStr)] string FileName, int Driver, System.IntPtr InfoLine, [MarshalAs(UnmanagedType.LPStr)] string Message);

The method call is:
IntPtr infoLine = IntPtr.Zero;
string message = "";
int success = Initialize(@"c:\config.dat", -1, infoLine, message);

The error message that Visual Studio gives back to me in debug mode is:

A call to PInvoke function 'Initialize' has unbalanced the stack.
  This is likely because the managed PInvoke signature does not match
  the unmanaged target signature. Check that the calling convention and
  parameters of the PInvoke signature match the target unmanaged
  signature.

Which parameter have I passed incorrectly?
I am fairly certain that the call to the DLL is correct because there is another function that has no parameters passed and similar import and method code worked.
Thanks for the help.

A: Try putting in the DllImport(... , CallingConvention=CallingConvention.Cdecl)
There are 4 methods of passing parameters to a "native" function. You have to know which one is the right one (where to put them in memory, who has to remove them from memory after the function...). The default one is the StdCall. Your function probably uses Cdecl. See here: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx
If/when you decide to use the Infoline callback,
[UnmanagedFunctionPointer(CallingConvenction.Cdecl)]
private delegate int InfolineDelegate(
        [MarshalAs(UnmanagedType.LPStr)] string str);

private static extern int Initialize(
        [MarshalAs(UnmanagedType.LPStr)] string fileName,
        int driver,
        [MarshalAs(UnmanagedType.FunctionPtr)] InfolineDelegate infoLine,
        [MarshalAs(UnmanagedType.LPStr)] string message);

If Initialize will use the delegate but won't store it:
Initialize("FileName", 1, MyMethod, "Message");

But if Initialize will store the delegate to use it at a later time, after returning:
// Put it outside the function... As a property/field of the class, for example
InfolineDelegate method = MyMethod;

Initialize("FileName", 1, method, "Message");

The InfolineDelegate method MUST have a guaranteed lifetime greater than the method you are using. So not a local variable. Normally a field/property of the calling class.


text:
Q: WCF Read DataMember Name attribute I have a very simple class called person.
public class Person{
   [DataMember(Name="MyName")]
   public string Name { get;set;}
}

If I try to serialize or de-serialize, everything works great. In the XML I can see a tag called "MyName" and in the object I see with the VS Intellisense a property called Name.
What I need now is to access, from the object, the serialized name of the property.
For example, I can do object.GetType().GetProperty("Name"); but if I try to do object.GetType().GetProperty("MyName"), the reflection says that the property does not exist. How I can read the serialized name of the property? Is there a way?

A: It seems that the only way is to access, using reflection, the attributes of the property in this way:
var att = myProperty.GetType().GetAttributes();
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute;
Console.WriteLine(attribute.Name);

This works on both, client and server, without the need of serialize and deserialize the object.


text:
Q: C# ASP.Net MVC RegularExpressionAttribute validation: negative look-behind assertion: rendering '<' instead of '<' The following Attribute:
[RegularExpression(@"(?<!Unknown).*", ErrorMessage = "value cannot be Unknown")]

is rendered into the following html:
<select name="ChannelName" id="ChannelName" data-val-regex-pattern="(?<!Unknown).*" data-val-regex="value cannot be Unknown" data-val="true">

This is obviously not what I wanted. Is there a way to write the Pattern property of the RegularExpressionAttribute so that it would be rendered correctly? Once I succeeded to solve quite similar problem with @Html.Raw(), but that was on the client-side.

A: Why is it not what you want. < is an escape sequence, when someone (the validation framework) read the attribute value they will see <

A: I think you regular expression is wrong. (?<!Unknown).* will succeed if there's any position in the text that doesn't have "Unknown" in front of it. I think you're looking for the following expression instead:
^(?!Unknown)

^ for the start of the string.
Then (?!Unknown) to prevent any string that starts with Unknown.


text:
Q: Angular2 (ngSubmit) not working I've just started Angular2 and facing following error when add (ngSubmit) attribute to my form
Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("

    <form [ERROR ->]#form="ngForm" (ngSubmit)="onSubmit()" novalidate>

Following are some of my dependencies from package.json.
"dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "core-js": "^2.4.1",
    "ie-shim": "^0.1.0",
    "jquery": "^3.1.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23"
  }

I've following html form.
<form #form="ngForm" (ngSubmit)="onSubmit()" novalidate>

        Title
        <input [(ngModel)]="model.Title" #title="ngModel" name="title" id="title" type="text" class="form-control" value="">

        Description
        <textarea [(ngModel)]="model.Description" #description="ngModel" class="summernote form-control" name="description" id="description"></textarea>

</form>

And following category.component file
import { Component } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Category } from '../../../models/cms/Category';

@Component({
    selector: 'category',
    templateUrl: 'category.template.html'
})
export class CategoryComponent{

    model = new Category("dummyTitle","dummyDescription");

    onSubmit() {
        console.log(this.data);
    }
}

Can someone please guide how to deal with this problem.

A: you are missing a import file import { NgForm } from '@angular/forms';
and you are using template Driven forms so you don't need FormBuilder.
try this way
signup-form.component.html
<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
  Email
  <input type="text" name="email" id="email" ngModel>

  Password
  <input type="password" name="password" id="password" ngModel>

  <button type="submit">Sign Up</button>
</form>

signup-form.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'signup-form',
  templateUrl: 'app/signup-form.component.html',
})
export class SignupForm {
  registerUser(form: NgForm) {
    console.log(form.value);
  }
}

A: In my case, my <button type="submit">Ok</button> was outside form tag.
It must be inside form tag to work.
<form [formGroup]="myForm" (ngSubmit)="submitHandler()">

    <button type="submit">Ok</button>
</form>

A: Make sure that button is inside the form and has type="submit". For example,
<ion-button type="submit"></ion-button>

A: If you want to bind submit button outside of the form you have to give an id to the form and link this id to the button with form property and type submit:
<form id="myForm" [formGroup]="form" (ngSubmit)="onSubmit()">
...
</form>

<button form="myForm" type="submit">
  Submit Form
</button>

Note: id doesn't have to be the same as formGroup name


text:
Q: Inno Setup - Get Data from CreateInputDirPage for putting files in folder selected I have written a script that is supposed to install in Program Files folder and add a file to another folder chosen
[Code]
var
  OutputProgressWizardPage: TOutputProgressWizardPage;
  OutputProgressWizardPageAfterID: Integer;
  PythonHome: String;
procedure InitializeWizard;
var
  //InputQueryWizardPage: TInputQueryWizardPage;
  //InputOptionWizardPage: TInputOptionWizardPage;
  InputDirWizardPage: TInputDirWizardPage;
  PrimaryServerPage: TInputQueryWizardPage;
  InputFileWizardPage: TInputFileWizardPage;
  OutputMsgWizardPage: TOutputMsgWizardPage;
  OutputMsgMemoWizardPage: TOutputMsgMemoWizardPage;
  AfterID: Integer;
begin
  //WizardForm.PasswordEdit.Text := '{#Password}';

  AfterID := wpSelectTasks;

  //AfterID := CreateCustomPage(AfterID, 'CreateCustomPage', 'ADescription').ID;

  //InputQueryWizardPage := CreateInputQueryPage(AfterID, 'CreateInputQueryPage', 'ADescription', 'ASubCaption');
  //InputQueryWizardPage.Add('&APrompt:', False);
  //AfterID := InputQueryWizardPage.ID;

  //InputOptionWizardPage := CreateInputOptionPage(AfterID, 'CreateInputOptionPage', 'ADescription', 'ASubCaption', False, False);
  //InputOptionWizardPage.Add('&AOption');
  //AfterID := InputOptionWizardPage.ID;

  InputDirWizardPage := CreateInputDirPage(AfterID, 'Choose Python Home Folder', '', '', False, '');
  InputDirWizardPage.Add('&Location of Python Home:');
  InputDirWizardPage.Values[0] := 'C:\Python27';
  AfterID := InputDirWizardPage.ID;
  ...
  ...
 end

function NextButtonClick(CurPageID: Integer): Boolean;
var
  Position, Max: Integer;
begin
  if CurPageID = OutputProgressWizardPageAfterID then begin
    try
      Max := 25;
      for Position := 0 to Max do begin
        OutputProgressWizardPage.SetProgress(Position, Max);
        if Position = 0 then
          OutputProgressWizardPage.Show;
        Sleep(2000 div Max);
      end;
    finally
      OutputProgressWizardPage.Hide;
    end;
  end;
  Result := True;
end;

function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
  if SuppressibleMsgBox('Do you want to stop Setup at the Preparing To Install wizard page?', mbConfirmation, MB_YESNO, IDNO) = IDYES then
    Result := 'Stopped by user';
end;

function GetPythonHome(Param: String): string;
begin
  Result := PythonHome;
end;

No matter what I change as the folder in The Installer Page that asks me to choose the Python Folder, It always picks to the default suggestion - C:\Python27.
How do I overcome this? What change must I make? There seems to be no manual online for Inno Setup Scripting as well. Please help me
The [Files] section -
[Files]
  Source: "C:\Users\pnarendr\Desktop\API_DAST\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
  ; NOTE: Don't use "Flags: ignoreversion" on any shared system files
  **; Not taking in changed PythonHome**
  Source: "C:\Users\pnarendr\Desktop\output.log"; DestDir: "{code:GetPythonHome}";


text:
Q: How to make two objects have the same id in python? If I have a class like below:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

And have 2 objects:
a = Point(1,2)
b = Point(1,2)

How can I modify class Point to make id(a) == id(b)?

A: class Point(object):
    __cache = {}
    def __new__(cls, x, y):
        if (x, y) in Point.__cache:
            return Point.__cache[(x, y)]
        else:
            o = object.__new__(cls)
            o.x = x
            o.y = y
            Point.__cache[(x, y)] = o
            return o

>>> Point(1, 2)
<__main__.Point object at 0xb6f5d24c>
>>> id(Point(1, 2)) == id(Point(1,2))
True

When you need a really simple class like Point, always consider collections.namedtuple
from collections import namedtuple
def Point(x, y, _Point=namedtuple('Point', 'x y'), _cache={}):
    return _cache.setdefault((x, y), _Point(x, y))

>>> Point(1, 2)
Point(x=1, y=2)
>>> id(Point(1, 2)) == id(Point(1, 2))
True

I used a function alongside namedtuple because it is simpler IMO but you can easily represent it as a class if needed:
class Point(namedtuple('Point', 'x y')):
    __cache = {}
    def __new__(cls, x, y):
        return Point.__cache.setdefault((x, y),
                                         super(cls, Point).__new__(cls, x, y))

As @PetrViktorin noted in his answer you should consider the use of a weakref.WeakValueDictionary so deleted instances of the class (doesn't work with namedtuple apparently) don't remain in memory since they remain referenced in the dictionary itself.

A: You need to have a global dictionary of objects, and get them through a factory function (or a custom __new__, see the other answers). Additionally, consider using a WeakValueDictionary so that you don't unnecessarily fill up memory with objects that are no longer needed.
from weakref import WeakValueDictionary

class _Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

# Cache of Point objects the program currently uses
_points = WeakValueDictionary()

def Point(x, y):
    """Create a Point object"""
    # Note that this is a function (a "factory function")
    # You can also override Point.__new__ instead
    try:
        return _points[x, y]
    except KeyError:
        _points[x, y] = point = _Point(x, y)
        return point

if __name__ == '__main__':
    # A basic demo
    print Point(1, 2)
    print id(Point(1, 2))
    print Point(2, 3) == Point(2, 3)

    pt_2_3 = Point(2, 3)

    # The Point(1, 2) we created earlier is not needed any more.
    # In current CPython, it will have been been garbage collected by now
    # (but note that Python makes no guarantees about when objects are deleted)
    # If we create a new Point(1, 2), it should get a different id

    print id(Point(1, 2))

Note that a namedtuple won't work with WeakValueDictionary.

A: If you need to compare whether your two objects house the same values, you can implement the eq operator:
>>> class Point(object):
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...     def __eq__(self, other):
...         return self.x == other.x and self.y == other.y
...
>>> a = Point(1,2)
>>> b = Point(1,2)
>>> a == b
True
>>> b = Point(2,2)
>>> a == b
False


text:
Q: Cannot mount external USB 3.0 Hard Disk I have a USB 3.0 external hard disk which I am unable to mount. The entry appears in the "lsusb" command, but I do not exactly understand how to mount it.
This is the output for my lsusb command. "ASMedia Technology Inc." is the USB 3.0 device. I would appreciate some help in mounting and accessing the hard disk.
This the relevant output of my "sudo fdisk -l" when I connect the USB 3.0 HDD to a normal USB 2.0 port:
Disk /dev/sdb: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x8e0eee9e

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *           1          13      102400    7  HPFS/NTFS
Partition 1 does not end on cylinder boundary.
/dev/sdb2              13       38914   312466432    7  HPFS/NTFS

As you can see the sdb drive and paritions are listed accurately.
However when I connect the USB 3.0 HDD to the (ExpressCard34) USB 3.0 port and run the same "sudo fdisk -l" command, the sdb drives are not detected. They only seem to appear in the "lsusb" output. I have given the "sudo fdisk -l" output below:
Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000b441f

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1       37434   300686336   83  Linux
/dev/sda2           37434       38914    11882497    5  Extended
/dev/sda5           37434       38914    11882496   82  Linux swap / Solaris

This the relevant output of my "lsusb" :
lsusb
Bus 009 Device 002: ID 174c:5106 ASMedia Technology Inc.
Bus 008 Device 002: ID 0a5c:2150 Broadcom Corp. BCM2046 Bluetooth Device
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 5986:0205 Acer, Inc
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

This the relevant output of my "lsusb -v" :
Bus 009 Device 002: ID 174c:5106 ASMedia Technology Inc.
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.10
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x174c ASMedia Technology Inc.
  idProduct          0x5106
  bcdDevice            0.01
  iManufacturer           2 ASMedia
  iProduct                3 AS2105
  iSerial                 1 00000000000000000000
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           32
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xc0
      Self Powered
    MaxPower                0mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk (Zip)
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
            bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.10
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  bNumConfigurations      1
Device Status:     0x0001
  Self Powered

Bus 009 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               3.00
  bDeviceClass            9 Hub
  bDeviceSubClass         0 Unused
  bDeviceProtocol         3
  bMaxPacketSize0         9
  idVendor           0x1d6b Linux Foundation
  idProduct          0x0003 3.0 root hub
  bcdDevice            2.06
  iManufacturer           3 Linux 2.6.35-28-generic xhci_hcd
  iProduct                2 xHCI Host Controller
  iSerial                 1 0000:04:00.0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           25
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xe0
      Self Powered
      Remote Wakeup
    MaxPower                0mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass         9 Hub
      bInterfaceSubClass      0 Unused
      bInterfaceProtocol      0 Full speed (or root) hub
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0004  1x 4 bytes
        bInterval              12
Hub Descriptor:
  bLength               9
  bDescriptorType      41
  nNbrPorts             4
  wHubCharacteristic 0x0009
    Per-port power switching
    Per-port overcurrent protection
    TT think time 8 FS bits
  bPwrOn2PwrGood       10 * 2 milli seconds
  bHubContrCurrent      0 milli Ampere
  DeviceRemovable    0x00
  PortPwrCtrlMask    0xff
 Hub Port Status:
   Port 1: 0000.0100 power
   Port 2: 0000.0100 power
   Port 3: 0000.0503 highspeed power enable connect
   Port 4: 0000.0503 highspeed power enable connect
Device Status:     0x0003
  Self Powered
  Remote Wakeup Enabled

This is the error given when I try to mount the hard drive:
shinso@shinso-IdeaPad:~$ sudo mount /dev/sdb /mnt
[sudo] password for shinso:
mount: /dev/sdb: unknown device

This the output of "dmesg|tail":
[30062.774178] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO
[30535.800977] usb 9-4: USB disconnect, address 3
[30659.237342] Valid eCryptfs headers not found in file header region or xattr region
[30659.237351] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO
[31259.268310] Valid eCryptfs headers not found in file header region or xattr region
[31259.268313] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO
[31860.059058] Valid eCryptfs headers not found in file header region or xattr region
[31860.059062] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO
[32465.220590] Valid eCryptfs headers not found in file header region or xattr region
[32465.220593] Either the lower file is not in a valid eCryptfs format, or the key could not be retrieved. Plaintext passthrough mode is not enabled; returning -EIO

I am using Ubuntu 10.10 (64 bit).
I have included a screengrab from Disk Utility for people who want extra info.
http://i.stack.imgur.com/mcFRh.png
Any help is appreciated.

A: Depending on the partition format, and the partition number (both of which can be found with sudo fdisk -l), the syntax for the mount command would be something like this:
sudo mount -t ntfs /dev/sdb1 /media/mountPoint
Note that the command listed assumes three things:

*

*That the partition is on sdb, and has the number of 1 (which is how you end up with /dev/sdb1)

*That your partition is of the type ntfs (which most large capacity drives are, unless they're formatted for Macs (in which case they have hfs+ or similar as the formatting)

*That you're trying to mount the drive to the location /media/mountPoint.

Each of those 3 items I just mentioned can be adjusted as is needed based on the type of partition being used, the location you want to mount the drive to, and the partition number of the drive.
EDIT
I just realized I forgot a crucial step.  Assuming you are going to use the above mentioned command, you need to create the mount point first.  So using my above example of using a mount point of /media/mountPoint, you will need to do this command before you attempt to mount the drive:
mkdir /media/mountPoint
If this command requires you to have superuser, prepend the mkdir command with sudo, which will allow the command to be run as superuser.

A: Your USB 3.0 card may claim it has the NEC chipset, which is perfectly compatible with Linux, but lsusb output shows it has a (cheaper, less compatible) AsMedia chipset. This isn't compatible (yet) in USB 3.0 mode with Linux.

A: download ntfs configuration tool from Ubuntu Software center. It will help u to mount and R/W enable disable. its easy and easy. you dont need the use of terminal in this case. Hope it works for u.

A: I wasn't able to get my HDD to work at all when I plugged in a USB 3.0 ExpressCard after the machine had booted. I read somewhere that Ubuntu doesn't seem to detect the ExpressCard properly if the machine is already running, and detects them properly if it's inserted before you turn on the machine.
So basically, try booting with the ExpressCard already inserted, and see if your Hard Drive operates properly after that.


text:
Q: Error in Confusion Matrix :The data contain levels not found in the data I am cross-validating malware families with R caret. I am now trying to generate a confusion matrix and I keep getting the following error:
Error in confusionMatrix.default(crossval[[3]][[1]], data_train[, 1]) :
The data contain levels not found in the data.

Here is my code:
#setwd("Malware/")
library(caret)
library(klaR)
library(randomForest)
# load the iris dataset
malware        <- read.table('C:/Users/awais/Desktop/Malware/1.csv',sep=",",header=TRUE)
malware = na.omit(malware)
malware$labels <- as.factor(malware$labels)
# define an 80%/20% train/test split of the dataset
split=0.80
trainIndex <- createDataPartition(malware$labels, p=split, list=FALSE)
data_train <- malware[ trainIndex,]
data_test  <- malware[-trainIndex,]

# Perform Cross Validation
crossval <- rfcv(data_train[,2:1025],data_train[,1],cv.fold=2, do.trace=TRUE, ntree=100)

# print out OOB error result for number of features
print(crossval[[2]])

# get the resulting confusion matrix for the cross validation
results <- confusionMatrix(crossval[[3]][[1]],data_train[,1])
write.table(results[[2]],file="predict_crossval.csv",sep=",")


text:
Q: MySQL - ORDER BY STR_TO_DATE not working I am trying to run a PDO query with PHP and MySql and then sort it by date.
My query is below:
    $query_params = array(
        ':website' => $site
    );

    $query = "
        SELECT
            DATE_FORMAT(date, '%d/%m/%Y') AS date,
            id
        FROM
            items as bi
        INNER JOIN
            basket as bb ON bi.item_number=bb.basket_item
        INNER JOIN
            orders as bo ON bb.basket_order=bo.order_number
        WHERE
            bi.website = :website
        ORDER BY
            STR_TO_DATE(date,'%d/%m/%Y') DESC
    ";

    try {
        $stmt = DB::get()->prepare($query);
        $stmt->execute($query_params);
        $rows = $stmt->fetchAll();
    }
    catch(PDOException $ex) {}

    foreach($rows as $row):
        $output .= "".$row["date"].",";
        $output .= "".$row["id"].",";
        $output .= "\r\n <br />";
    endforeach;

Where my output should be:
13/06/2014, 8676,
12/06/2014, 5765,
12/04/2014, 7683,
08/12/2013, 1098,
06/12/2013, 2003,
06/12/2013, 6755,

It doesn't seem to be sorting by anything:
12/06/2014, 5765,
12/04/2014, 7683,
13/06/2014, 8676,
06/12/2013, 2003,
06/12/2013, 6755,
08/12/2013, 1098,

Should STR_TO_DATE(date,'%d/%m/%Y') DESCnot be sorting as intended?

A: You already have a lovely date column in your table - why on earth try to sort by some formatted string based on that?
    SELECT
        DATE_FORMAT(date, '%d/%m/%Y') AS date,
        id
    FROM
        items as bi
    INNER JOIN
        basket as bb ON bi.item_number=bb.basket_item
    INNER JOIN
        orders as bo ON bb.basket_order=bo.order_number
    WHERE
        bi.website = :website
    ORDER BY
        date DESC

Sure, format the date output to the user however you like - but you are not only making the DB do a lot more by formatting each row of data then sorting by something that could be done natively by the database the way it was meant to be.
Edit: Interesting. I wonder if the fact that date is a semi-reserved word is causing your sort not to happen as expected?
Maybe try this:
    ORDER BY
        bo.date DESC

A: try this
$query = "
    SELECT
        DATE_FORMAT(date, '%d/%m/%Y') AS date,
        id
    FROM
        items as bi
    INNER JOIN
        basket as bb ON bi.item_number=bb.basket_item
    INNER JOIN
        orders as bo ON bb.basket_order=bo.order_number
    WHERE
        bi.website = :website
    ORDER BY
        date DESC
";


text:
Q: Actual Display Comparison Feature for Edit Review I have had a few rejects of edits which improved formatting of code blocks on the basis that the improvement was minor.
Looking at the representation of the edit in both 'rendered output' and 'markdown', it is difficult to visualize the actual formatting improvement as it would display in the question or answer.
I suspect that other formatting improvements may also be difficult to visualize, and are not supported by the render output (like color coding of code). Other posts have suggested that the diff markup in certain instances makes it difficult to visualize the changes.
Would it not be beneficial to add an additional view 'actual display' rendering the before and after as it would display?
That way if it is not immediately apparent to the reviewer the benefit of the edit, they can check the actual display to make sure that there indeed is no benefit.


text:
Q: Cannot find modules when deploying express + typescript to heroku First, My current setup works locally. I've been stuck on this problem for days.
Second, I'll describe it by sections

*

*directory structure

*typescript setup (tsconfig + path mappings)

*setup related to module-alias package + package.json

*step how i deploy to heroku

*the error log by heroku

Directory structure
├── client/
│   ├── src
│   └── package.json
├── server/
│   ├── tsconfig.json
│   └── package.json
└── shared/
    ├── helpers/validators.ts
    ├── constants/tags.ts
    └── models/bookmark.ts

tsconfig setup

Note:
I'm using path mappings/alias set in tsconfig.json. I installed the package module-alias for the compiled files to be able to find the path mappings.

On my tsconfig, i'm importing a file that is outside the typescript project where tsconfig.json is located
As you can see on the directory structure, the tsconfig.json is under server folder and i'm importing files from the shared folder
So here's my tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@models/*": ["../shared/models/*"],
      "@constants/*": ["../shared/constants/*"],
      "@helpers/*": ["../shared/helpers/*"]
    },
    "target": "es2018",
    "module": "commonjs",
    "moduleResolution": "node",
    "rootDir": "../",
    "outDir": "./build",
    "esModuleInterop": true,
    "strict": true,
    "typeRoots": ["node_modules/@types"],
    "sourceMap": false,
    "removeComments": true
  },
  "include": ["**/*", "../shared/**/*"]
}

package.json + setup related to module alias package

Note: the path for _moduleAliases is based on the path of the compiled javascript file

{
  "name": "pocketlite-server",
  "version": "1.0.0",
  "engines": {
    "node": "14.x",
    "npm": "6.x"
  },
  "description": "",
  "main": "index.js",
  "_moduleAliases": {
    "@models": "build/shared/models",
    "@constants": "build/shared/constants",
    "@helpers": "build/shared/helpers"
  },
  "scripts": {
    "start:prod": "node build/server/index.js",
    "start:staging": "export NODE_ENV=staging && nodemon -r tsconfig-paths/register index.ts",
    "start:dev": "export NODE_ENV=development && nodemon -r tsconfig-paths/register index.ts",
    "build": "tsc -p .",
    "heroku-prebuild": "npm i --only=dev",
    "lint": "eslint . --ext .ts",
    "csrf": "npx http-server -c-1 -d false -o /csrf-test"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/cookie-parser": "^1.4.2",
    "@types/cors": "^2.8.7",
    "@types/express": "^4.17.7",
    "@types/jsdom": "^16.2.3",
    "@types/mongoose": "^5.7.36",
    "@types/mongoose-delete": "^0.5.1",
    "@types/mozilla-readability": "^0.2.0",
    "@types/node": "^14.0.27",
    "@types/passport": "^1.0.4",
    "@types/passport-google-oauth20": "^2.0.3",
    "@types/passport-jwt": "^3.0.3",
    "@types/puppeteer": "^3.0.1",
    "@types/turndown": "^5.0.0",
    "@typescript-eslint/eslint-plugin": "^3.8.0",
    "@typescript-eslint/parser": "^3.8.0",
    "dotenv": "^8.2.0",
    "eslint": "^7.6.0",
    "nodemon": "^2.0.4",
    "ts-node": "^8.10.2",
    "tsconfig-paths": "^3.9.0"
  },
  "dependencies": {
    "@mozilla/readability": "^0.3.0",
    "@types/cookie-session": "^2.0.41",
    "@types/csurf": "^1.9.36",
    "cookie-parser": "^1.4.5",
    "cookie-session": "^1.4.0",
    "cors": "^2.8.5",
    "csurf": "^1.11.0",
    "express": "^4.17.1",
    "isomorphic-dompurify": "^0.6.0",
    "jsdom": "^16.4.0",
    "jsonwebtoken": "^8.5.1",
    "module-alias": "^2.2.2",
    "mongoose": "^5.9.28",
    "mongoose-delete": "^0.5.2",
    "passport": "^0.4.1",
    "passport-google-oauth20": "^2.0.0",
    "passport-jwt": "^4.0.0",
    "puppeteer": "^5.2.1",
    "puppeteer-extra": "^3.1.15",
    "puppeteer-extra-plugin-adblocker": "^2.11.6",
    "puppeteer-extra-plugin-stealth": "^2.6.1",
    "turndown": "^6.0.0",
    "turndown-plugin-gfm": "^1.0.2",
    "typescript": "^4.0.3"
  }
}

Steps how I deploy in hero

*

*heroku create pocketlite-server

*heroku buildpacks:set heroku/nodejs

*heroku git:remote -a pocketlite-server

*git subtree push --prefix server heroku master

The error log in heroku
relevent npm scripts for heroku
  "scripts": {
    "start:prod": "node build/server/index.js",
    "start:staging": "export NODE_ENV=staging && nodemon -r tsconfig-paths/register index.ts",
    "start:dev": "export NODE_ENV=development && nodemon -r tsconfig-paths/register index.ts",
    "build": "tsc -p .",
    "heroku-prebuild": "npm i --only=dev"
  }

Error log
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       NODE_VERBOSE=false

-----> Installing binaries
       engines.node (package.json):  14.x
       engines.npm (package.json):   6.x

       Resolving node version 14.x...
       Downloading and installing node 14.13.0...
       Bootstrapping npm 6.x (replacing 6.14.8)...
       npm 6.x installed

-----> Prebuild
       Running heroku-prebuild

       > pocketlite-server@1.0.0 heroku-prebuild /tmp/build_8e06db38
       > npm i --only=dev

       > nodemon@2.0.4 postinstall /tmp/build_8e06db38/node_modules/nodemon
       > node bin/postinstall || exit 0

       Love nodemon? You can now support the project via the open collective:
        > https://opencollective.com/nodemon/donate

       added 194 packages from 194 contributors and audited 665 packages in 7.23s

       19 packages are looking for funding
         run `npm fund` for details

       found 2 high severity vulnerabilities
         run `npm audit fix` to fix them, or `npm audit` for details

-----> Installing dependencies
       Installing node modules

       > puppeteer@5.2.1 install /tmp/build_8e06db38/node_modules/puppeteer
       > node install.js

       > nodemon@2.0.4 postinstall /tmp/build_8e06db38/node_modules/nodemon
       > node bin/postinstall || exit 0

       Love nodemon? You can now support the project via the open collective:
        > https://opencollective.com/nodemon/donate

       added 661 packages in 19.572s

-----> Build
       Running build

       > pocketlite-server@1.0.0 build /tmp/build_8e06db38
       > tsc -p .

       helpers/link-scraper.ts(12,26): error TS2307: Cannot find module '@models/bookmark.model' or its corresponding type declarations.
       helpers/validators.ts(1,23): error TS2307: Cannot find module '@constants/patterns' or its corresponding type declarations.
       models/bookmark-favorite.ts(2,34): error TS2307: Cannot find module '@models/bookmark-favorite.model' or its corresponding type declarations.
       models/bookmark.ts(7,26): error TS2307: Cannot find module '@models/bookmark.model' or its corresponding type declarations.
       models/tag.ts(2,21): error TS2307: Cannot find module '@models/tag.model' or its corresponding type declarations.
       models/user.ts(2,22): error TS2307: Cannot find module '@models/user.model' or its corresponding type declarations.
       routes/bookmarks.ts(4,32): error TS2307: Cannot find module '@constants/tags' or its corresponding type declarations.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! pocketlite-server@1.0.0 build: `tsc -p .`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the pocketlite-server@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.tNTfH/_logs/2020-10-04T01_44_27_692Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - A module may be missing from 'dependencies' in package.json
         https://devcenter.heroku.com/articles/troubleshooting-node-deploys#ensure-you-aren-t-relying-on-untracked-dependencies

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

Update:

*

*I have also tried to dockerize my app, and the same error still occurs.

*I've discovered that it is related to typescript not resolving path mappings to their corresponding paths without a module bundler that rewrites path like webpack (w/c i don't use currently).
Here's the relevant discussion in typescript's github issue


text:
Q: resampling a pandas dataframe from almost-weekly to daily What's the most succinct way to resample this dataframe:
>>> uneven = pd.DataFrame({'a': [0, 12, 19]}, index=pd.DatetimeIndex(['2020-12-08', '2020-12-20', '2020-12-27']))
>>> print(uneven)
             a
2020-12-08   0
2020-12-20  12
2020-12-27  19

...into this dataframe:
>>> daily = pd.DataFrame({'a': range(20)}, index=pd.date_range('2020-12-08', periods=3*7-1, freq='D'))
>>> print(daily)
             a
2020-12-08   0
2020-12-09   1
...
2020-12-19  11
2020-12-20  12
2020-12-21  13
...
2020-12-27  19

NB: 12 days between the 8th and 20th Dec, 7 days between the 20th and 27th.
Also, to give clarity of the kind of interpolation/resampling I want to do:
>>> print(daily.diff())
              a
2020-12-08  NaN
2020-12-09  1.0
2020-12-10  1.0
...
2020-12-19  1.0
2020-12-20  1.0
2020-12-21  1.0
...
2020-12-27  1.0

The actual data is hierarchical and has multiple columns, but I wanted to start with something I could get my head around:
                      first_dose  second_dose
date       areaCode
2020-12-08 E92000001         0.0          0.0
           N92000002         0.0          0.0
           S92000003         0.0          0.0
           W92000004         0.0          0.0
2020-12-20 E92000001    574829.0          0.0
           N92000002     16068.0          0.0
           S92000003     60333.0          0.0
           W92000004     24056.0          0.0
2020-12-27 E92000001    267809.0          0.0
           N92000002     14948.0          0.0
           S92000003     34535.0          0.0
           W92000004     12495.0          0.0
2021-01-03 E92000001    330037.0      20660.0
           N92000002      9669.0       1271.0
           S92000003     21446.0         44.0
           W92000004     14205.0         27.0

A: I think you need:
df = df.reset_index('areaCode').groupby('areaCode')[['first_dose','second_dose']].resample('D').interpolate()
print (df)
                         first_dose  second_dose
areaCode  date
E92000001 2020-12-08       0.000000     0.000000
          2020-12-09   47902.416667     0.000000
          2020-12-10   95804.833333     0.000000
          2020-12-11  143707.250000     0.000000
          2020-12-12  191609.666667     0.000000
                            ...          ...
W92000004 2020-12-30   13227.857143    11.571429
          2020-12-31   13472.142857    15.428571
          2021-01-01   13716.428571    19.285714
          2021-01-02   13960.714286    23.142857
          2021-01-03   14205.000000    27.000000

[108 rows x 2 columns]


text:
Q: Python Script to Execute SQL in Loop I am trying to write python script which calls mysql SQL.
I am relying on first query result to run second query. Problem is that it's throwing error.
Error : cursor2.execute(field_sql,id)
import boto3
import importlib
import psutil
import pymysql
import pymysql.cursors
import subprocess
import sys

rdsConn = pymysql.connect(host = 'XXXX'),
                          db = 'XXXX',
                          user = 'XXXX',
                          password = 'XXXX',
                          charset = 'utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)

cursor1 = rdsConn.cursor()
cursor2 = rdsConn.cursor()

name = 'Test'
sql = "select id from Table1 where name = %s"
cursor1.execute(sql,name)
result = cursor1.fetchall()
for id in result:
    field_sql= "select columnname from  Table2 where id = %s"
    cursor2.execute(field_sql,id)
    fieldresult = cursor2.fetchall()
    for fieldrow in fieldresult:
        print(fieldrow)

cursor1.close()
cursor2.close()
rdsConn.close()

A: Your query uses a dict cursor, so it will return a list of dicts, e.g:
[{'id': 1}, {'id': '2'}, ...]

Which means your id* will be a dict, not a tuple as it would be otherwise. Which means you're passing your arguments to the second query as a dict. If you do so, you need to use named parameters using the pyformat style:
for rowdict in result:
    field_sql = "select columnname from  Table2 where id = %(id)s"
    cursor2.execute(field_sql, rowdict)
    fieldresult = cursor2.fetchall()
    for fieldrow in fieldresult:
        print(fieldrow)

You'll see that the printed fieldrows are also dicts.
Also, query parameters should be passed either as dict (named parameters) or as tuple (positional parameters). pymysql accepts the form cursor.execute(sql, "name"), other dbapi2 connectors don't. The canonical form would be cursor.execute(sql, ("name",)).
*btw, you shouldn't use id as name, it hides the builtin id function


text:
Q: Trying to Understand Android's Sax Parser I have used the Java Sax parser, but am trying to implement Android's with this XML.
<?xml version="1.0"  encoding="utf-8"?>
<adc_database xmlns="http://www.weather.com">
    <units>
        <temp>F</temp>
        <dist>MI</dist>
        <speed>MPH</speed>
        <pres>IN</pres>

        <prec>IN</prec>
    </units>

<local>
<city>State College</city>
<adminArea>Pennsylvania</adminArea>
    <country code="US">United States</country>
<lat>40.803</lat>
<lon>-77.894</lon>
<time>14:35</time>
<timeZone>-5</timeZone>

<obsDaylight>
1
</obsDaylight>
</local>

            <watchwarnareas zone="PAZ019" county="PAC027" isactive="1">

                    <warningtype>SEVERE THUNDERSTORM WATCH</warningtype>

                <url>http://www.weather.com/watches-warnings.asp</url>

            </watchwarnareas>

    <currentconditions daylight="True">

            <url>http://www.weather.com</url>

            <observationtime>2:35 PM</observationtime>

            <temperature>84</temperature>

            <realfeel>90</realfeel>

            <humidity>61%</humidity>

            <weathericon>07</weathericon>

            <windgusts>16</windgusts>

            <windspeed>8</windspeed>

            <winddirection>WNW</winddirection>

            <visibility>10</visibility>

    </currentconditions>

        <mapSpace>
        <image resolution="480x480" url="http://vortex.png"/>
        </mapSpace>

        <forecast>

                <url>http://www.weather.com/forecast.asp</url>
                <day number="1">
                        <url>http://www.weather.com/</url>

                <obsdate>7/21/2010</obsdate>
                <daycode>Wednesday</daycode>

                    <sunrise>5:59 AM</sunrise>
                    <sunset>8:37 PM</sunset>

                <daytime>

                        <weathericon>17</weathericon>

                        <hightemperature>85</hightemperature>
                        <lowtemperature>63</lowtemperature>

                        <realfeelhigh>93</realfeelhigh>
                        <realfeellow>65</realfeellow>

                        <windspeed>8</windspeed>

                        <winddirection>W</winddirection>

                        <windgust>32</windgust>

                        <rainamount>0.01</rainamount>

                        <snowamount>0.0</snowamount>

                        <iceamount>0.00</iceamount>

                        <tstormprob>91</tstormprob>

                </daytime>

                <nighttime>

                        <weathericon>35</weathericon>

                        <hightemperature>85</hightemperature>
                        <lowtemperature>63</lowtemperature>

                        <realfeelhigh>93</realfeelhigh>
                        <realfeellow>65</realfeellow>

                        <windspeed>4</windspeed>

                        <winddirection>W</winddirection>

                        <windgust>10</windgust>

                        <rainamount>0.20</rainamount>

                        <snowamount>0.0</snowamount>

                        <iceamount>0.00</iceamount>

                        <tstormprob>24</tstormprob>

                </nighttime>
            </day>
            <day number="2">
                        <url>http://www.weather.com&fday=2</url>

                <obsdate>7/22/2010</obsdate>

                <daycode>Thursday</daycode>

                    <sunrise>6:00 AM</sunrise>
                    <sunset>8:37 PM</sunset>

                <daytime>

                        <weathericon>02</weathericon>

                        <hightemperature>86</hightemperature>

                        <lowtemperature>63</lowtemperature>

                        <realfeelhigh>87</realfeelhigh>
                        <realfeellow>65</realfeellow>

                        <windspeed>8</windspeed>

                        <winddirection>W</winddirection>

                        <windgust>19</windgust>

                        <rainamount>0.00</rainamount>

                        <snowamount>0.0</snowamount>

                        <iceamount>0.00</iceamount>

                        <tstormprob>0</tstormprob>

                </daytime>
                <nighttime>

                        <weathericon>42</weathericon>

                        <hightemperature>86</hightemperature>
                        <lowtemperature>63</lowtemperature>

                        <realfeelhigh>87</realfeelhigh>
                        <realfeellow>65</realfeellow>

                        <windspeed>2</windspeed>

                        <winddirection>N</winddirection>

                        <windgust>8</windgust>

                        <rainamount>0.00</rainamount>

                        <snowamount>0.0</snowamount>

                        <iceamount>0.00</iceamount>

                        <tstormprob>40</tstormprob>

                </nighttime>

            </day>

I am going off of the example at this URL (http://www.ibm.com/developerworks/opensource/library/x-android/index.html
I am not sure how I grab different levels within the XML.  I have a WeatherData class that stores all the info that I need:
public class WeatherData {
//instance data
@SuppressWarnings("unused")
private final String DEB_TAG = "WeatherData.java";

public Location location;
public Current current;
public List<Forecast> forecast;

public WeatherData(){
    location    = new Location();
    current     = new Current();
    forecast    = new ArrayList<Forecast>();
}

public class Location {
    public String time;
    public String city;
    public String state;

    public Location(){

    }
    public Location(String time, String city, String state){
        this.time   = time;
        this.city   = city;
        this.state  = state;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
}

public class Current {
    public String temp;
    public String realfeel;
    public String humidity;
    public String icon;

    public String getTemp() {
        return temp;
    }
    public void setTemp(String temp) {
        this.temp = temp;
    }
    public String getRealfeel() {
        return realfeel;
    }
    public void setRealfeel(String realfeel) {
        this.realfeel = realfeel;
    }
    public String getHumidity() {
        return humidity;
    }
    public void setHumidity(String humidity) {
        this.humidity = humidity;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }

    public Current(){

    }
    public Current(String temp, String realfeel, String humidity, String icon){
        this.temp       = temp;
        this.realfeel   = realfeel;
        this.humidity   = humidity;
        this.icon       = icon;
        Log.d("DEB_TAG", "Value of temp inside Current is " + temp);
    }
}

public class Forecast{
    // Forecast member variables
    public String day_d;
    public String icon_d;
    public String high_d;
    public String low_d;
    public String obsDate_d;

    public String getDay_d() {
        return day_d;
    }
    public void setDay_d(String dayD) {
        day_d = dayD;
    }
    public String getIcon_d() {
        return icon_d;
    }
    public void setIcon_d(String iconD) {
        icon_d = iconD;
    }
    public String getHigh_d() {
        return high_d;
    }
    public void setHigh_d(String highD) {
        high_d = highD;
    }
    public String getLow_d() {
        return low_d;
    }
    public void setLow_d(String lowD) {
        low_d = lowD;
    }
    public String getObsDate_d() {
        return obsDate_d;
    }
    public void setObsDate_d(String obsDateD) {
        obsDate_d = obsDateD;
    }
}

public Forecast createForecast(){
    return new Forecast();
}

}
What I am not understanding is how to step into the different levels of my XML.  I have my root tag adc_database that contains my opening and closings of LOCAL, CURRENTCONDITIONS, and FORECAST, where FORECAST has multiple daily forecasts. Here is my code so far...
public class AndroidSaxFeedParser extends BaseFeedParser {

    public AndroidSaxFeedParser(String feedUrl) {
        super(feedUrl);
    }

    public List<WeatherData> parse() {
        final WeatherData currentData       = new WeatherData();
        RootElement root                    = new RootElement("rss");
        final List<WeatherData> conditions  = new ArrayList<WeatherData>();
        Element adc_database                = root.getChild("adc_database");
        Element item                        =  adc_database.getChild(LOCAL);

        item.setEndElementListener(new EndElementListener(){
            public void end() {
                conditions.add(currentData.copy());
            }
        });
        item.getChild(CITY).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentData.location.setCity(body);
            }
        });
        item.getChild(ADMINAREA).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentData.location.setState(body);
            }
        });

        try {
            Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8,
root.getContentHandler());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return conditions;
    }
}

If anyone can help explain the SAX code and how I would go into the different levels or could point me to another example that goes deeper than one level would be great!

A:
What I am not understanding is how to
  step into the different levels of my
  XML

Would like to know a better way, but currently my approach is just to parse once as a single doc, with the nested levels using multiple getChild's.
i.e.:
item.getChild(LOCAL).getChild(ADMINAREA).setEndTextElementListener(new EndTextElementListener(){


text:
Q: calling a function with require but variables and arrays are undefined Why aren't my variable seen when called with require ?
function.php
<?php
function paginator(){

    $links  = array("index.php", "services.php", "content.php","contact_us.php" );
    $trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);

        foreach ($links as $key => $value) {
            if ($value == $trimslug ) {
                $GLOBALS['$page'] = $key;
            }
        }
    $page = $GLOBALS['$page'];
    $next = $page+1;
    $previous = $page-1;
}

?>

content.php
<?php
session_start();
require './functions.php';
paginator();
?>

<!doctype html>

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

Now on Page : <?php echo $page?>

<a href="<?php echo $links[$next] ?>" >Next

<a href="<?php  echo $links[$previous]?>" >Previous

I would like to be able to see my variables, when using the require function as this piece of code will be on every page. This might be a very noobish concept to grasp but I would really like someone to illustrate the concept properly.
This seemed to work, Thank you everyone.
<?php

    $links  = array("index.php", "services.php", "content.php","contact_us.php" );
    $trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
    $page = null;

    function paginator(){
    global $links,$trimslug,$next,$previous,$page;

        foreach ($links as $key => $value) {
        if ($value == $trimslug ) {
            // $GLOBALS['$page'] = $key;
            $page = $key;
        }
    }
$next = $page+1;
$previous = $page-1;
}

?>

A: This is because the variables are defined in the scope of the function paginator();
If you want them to be accesible in the scope of content.php, either declare them like this:
global $variable = 'value';

Or, just declare them in function.php without the need of the function & it's subsequent call in content.php.

A: Variables in PHP are limited to the scope of the function, unless called via an argument or by adding to the global array.
Global arrays are bad practice, just sayin.
You could always make the variables into a private class and call it as needed, though that's pretty tricky for beginners.

A: The variables inside paginator are only in the scope of the function, not the php file. If you want to access them outside that function, just move those variables outside of it. Eg
$page=null;
$links=...
function paginator(){
...
}


text:
Q: Specify minimum number of generated files from Hive insert I am using Hive on AWS EMR to insert the results of a query into a Hive table partitioned by date. Although the total output size each day is similar, the number of generated files varies, usually between 6 to 8, but some days it creates just a single big file. I reran the query a couple of times, just in case the number of files happens to be influenced by the availability of nodes in the cluster but it seems it's consistent.
So my questions are
(a) what determines how many files are generated and
(b) is there a way to specify the minimum number of files or (even better) the maximum size of each file?

A: The number of files generated during INSERT ... SELECT depends on the number of processes running on final reducer (final reducer vertex if you are running on Tez) plus bytes per reducer configured.
If the table is partitioned and there is no DISTRIBUTE BY specified, then in the worst case each reducer creates files in each partition. This creates high pressure on reducers and may cause OOM exception.
To make sure reducers are writing only one partition files each, add DISTRIBUTE BY partition_column at the end of your query.
If the data volume is too big, and you want more reducers to increase parallelism and to create more files per partition, add random number to the distribute by, for example using this: FLOOR(RAND()*100.0)%10 - it will distribute data additionally by random 10 buckets, so in each partition will be 10 files.
Finally your INSERT sentence will look like:
INSERT OVERWRITE table PARTITION(part_col)
SELECT *
  FROM src
DISTRIBUTE BY  part_col, FLOOR(RAND()*100.0)%10; --10 files per partition

Also this configuration setting affects the number of files generated:
set hive.exec.reducers.bytes.per.reducer=67108864;

If you have too much data, Hive will start more reducers to process no more than bytes per reducer specified on each reducer process. The more reducers - the more files will be generated. Decreasing this setting may cause increasing the number of reducers running and they will create minimum one file per reducer. If partition column is not in the distribute by  then each reducer may create files in each partition.
To make long story short, use
DISTRIBUTE BY  part_col, FLOOR(RAND()*100.0)%10 -- 10 files per partition

If you want 20 files per partition, use FLOOR(RAND()*100.0)%20; - this will guarantee minimum 20 files per partition if you have enough data, but will not guarantee the maximum size of each file.
Bytes per reducer setting does not guarantee that it will be the fixed minimum number of files. The number of files will depend of total data size/bytes.per.reducer. This setting will guarantee the maximum size of each file.
But much better use some evenly distributed key or combination with low cardinality instead of random because in case of containers restart, rand() may produce different values for the same rows and it may cause data duplication or loss(same data which is already present in some reducer output will be distributed one more time to another reducer). You can calculate similar function on some keys available instead of rand() to get more or less evenly distributed key with low cardinality.
You can use both methods combined: bytes per reducer limit + distribute by to control both the minimum number of files and maximum file size.
Also read this answer about using distribute by to distribute data evenly between reducers: https://stackoverflow.com/a/38475807/2700344