text:
Q: Qualitative study of the solution of a system I am having serious troubles understanding what I need exactly to solve this exercise. Here it is.
Let x($\cdot$),y($\cdot$): (${t_-},{t_+})\mapsto\mathbb{R}^2$ be the maximal solution of the system:
\begin{aligned}
 & x'(t)= -x(t)+y^2(t)\\
 & y'(t)= x(t)-y^2(t)
\end{aligned}
with initial condition $({x_0},{y_0})\in$ ${R_+}\times{R_+}$
I proved that x(t)>0 and y(t)>0 for every t in [0,${t_+}$) and now it says to prove, knowing that $V(x,y)=x+y$  is a first integral of the system ( i.e. that $\frac{dV}{dt}$=0) that ${t_+}=\infty$ and that x($\cdot$),y($\cdot$) are monotone functions.
Here is my doubt. What should I do with a first integral? What informations it gives to me? I actually do not understand the intuition behind that. I read it suggests us something about the orbits, but I do not understand why and I to use the information about the orbits to answer this question. Can someone suggest me an idea? Or telling me where I can learn more about that, I find nothing at all on internet.

A: You can use $x+y=c$ to make the second equation a scalar one,
$$
y'=c-y-y^2.
$$
As $c>0$ the right side has a positive and a negative root. By general principles for scalar equations any solutions that starts above the negative root extends to $+\infty$. Then insert into the first equation which is linear in $x$ with continuous coefficients and thus extends as far as $y$ exists.


text:
Q: Object reference not set to an instance of an object when using css styling with xamarin forms I tried to set style to my page using css but i got this exception

Object reference not set to an instance of an object

MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XRetailMobile.Views.MainPage"
             xmlns:local="clr-namespace:XRetailMobile.Views.ContentViews"
             NavigationPage.HasNavigationBar="False">
    <ContentPage.Resources>
        <StyleSheet Source="/Styles/style.css"/>
    </ContentPage.Resources>
    <ContentPage.Content>
        <Grid HorizontalOptions="Fill" VerticalOptions="Fill">
            <local:ProductBackToolbar StyleClass="toolbarStyle" VerticalOptions="Start">
            </local:ProductBackToolbar>

        </Grid>
    </ContentPage.Content>

</ContentPage>

ProductBackToolbar.xaml(contentview)
<ContentView.Content>
    <StackLayout HorizontalOptions="Fill" Orientation="Horizontal">
        <Image Source="back" HeightRequest="35" VerticalOptions="Center" WidthRequest="35" HorizontalOptions="StartAndExpand"></Image>
        <Image Source="share" HeightRequest="35" VerticalOptions="Center" WidthRequest="35" HorizontalOptions="End"></Image>
        <Image Source="shoppingbag" HeightRequest="35" WidthRequest="35" VerticalOptions="Center" HorizontalOptions="End"></Image>
    </StackLayout>
</ContentView.Content>

style.css Located in Style Folder and its build action is EmbeddedResources
^contentpage {
    background-color: greenyellow;
}
.toolbarStyle {
    background-color: blue;
    margin: 20px;
    padding:20px;
}

if i comment margin and padding it's work fine
what's the wrong ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: handle garbage text in rasa-3 I have created basic project using rasa-init. Just changed the config.yml like this.
 pipeline:
  - name: SpacyNLP
    model: "en_core_web_md"
  - name: SpacyTokenizer
  - name: SpacyEntityExtractor
  - name: CountVectorsFeaturizer
    analyzer: char_wb
    min_ngram: 1
    max_ngram: 4
  - name: DIETClassifier
    epochs: 100
    constrain_similarities: true
  - name: EntitySynonymMapper
  - name: ResponseSelector
    epochs: 100
    constrain_similarities: true
  - name: FallbackClassifier
    threshold: 0.7
    ambiguity_threshold: 0.1

policies:
  - name: MemoizationPolicy
  - name: RulePolicy
  - name: UnexpecTEDIntentPolicy
    max_history: 5
    epochs: 100
  - name: TEDPolicy
    max_history: 5
    epochs: 100
    constrain_similarities: true

when i run rasa shell nlu and enter some garbage text like hsadfkj asjfs; adjf;lksajf ;lkjsf, i am getting output like this, and mood_unhappy, intent is getting selected:
{
  "text": "hsadfkj asjfs; adjf;lksajf ;lkjsf",
  "intent": {
    "name": "mood_unhappy",
    "confidence": 0.9950998425483704
  },
  "entities": [
    {
      "entity": "ORG",
      "value": "hsadfkj asjfs",
      "start": 0,
      "confidence": null,
      "end": 13,
      "extractor": "SpacyEntityExtractor"
    },
    {
      "entity": "PERSON",
      "value": "lkjsf",
      "start": 28,
      "confidence": null,
      "end": 33,
      "extractor": "SpacyEntityExtractor"
    }
  ],
  "text_tokens": [
    [
      0,
      7
    ],
    [
      8,
      13
    ],
    [
      13,
      14
    ],
    [
      15,
      26
    ],
    [
      27,
      28
    ],
    [
      28,
      33
    ]
  ],
  "intent_ranking": [
    {
      "name": "mood_unhappy",
      "confidence": 0.9950998425483704
    },
    {
      "name": "affirm",
      "confidence": 0.0013542941305786371
    },
    {
      "name": "mood_great",
      "confidence": 0.0010085614630952477
    },
    {
      "name": "greet",
      "confidence": 0.0008558280533179641
    },
    {
      "name": "bot_challenge",
      "confidence": 0.0005977358086965978
    },
    {
      "name": "goodbye",
      "confidence": 0.0005875211209058762
    },
    {
      "name": "get_meterial_number",
      "confidence": 0.0003199029597453773
    },
    {
      "name": "deny",
      "confidence": 0.00017638926510699093
    }
  ],
  "response_selector": {
    "all_retrieval_intents": [],
    "default": {
      "response": {
        "responses": null,
        "confidence": 0.0,
        "intent_response_key": null,
        "utter_action": "utter_None"
      },
      "ranking": []
    }
  }
}

Can anyone please explain why mood_unhappy is getting selected, and how can i do some fallback here.
Thanks


text:
Q: Calling Instance Method from the Objective C Selector Is it possible to call the instance method of an object from the selector? Is the below possible? It gives me compilation error that ":" is missing or something:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(([self.person dance]))
                                       userInfo:nil
                                        repeats:YES];

A: Change target to self.person and use the dance selector:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self.person
                                   selector:@selector(dance)
                                   userInfo:nil
                                    repeats:YES];

A: Have you tried changing the target? Like this:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self.person
                                       selector:@selector(dance)
                                       userInfo:nil
                                        repeats:YES];


text:
Q: Computer gets IP from DHCP server but has no internet connection I've installed an isc-dhcp-server on Ubuntu 12.10 and I'm trying to setup a DHCP server on a head node for six worker computers in the local network. The head node itself is a DHCP client receiving the IP-address 192.168.20.1 (on eth0) from an other computer in the network.
IPv4 IP forwarding is enabled on the head node. In /etc/sysctl.conf the following line was added:
net.ipv4.ip_forward = 1

The following rules are set in /etc/rc.local:
/sbin/iptables -P FORWARD ACCEPT
/sbin/iptables --table nat -A POSTROUTING -o eth0 -j MASQUERADE

Furthermore, INTERFACES="eth0" is set in /etc/default/isc-dhcp-server.
The dhcpd.conf file contains (for the moment only one worker computer is in the file):
ddns-update-style none;

default-lease-time 3600;
max-lease-time 7200;

authoritative;

subnet 192.168.20.0 netmask 255.255.255.0 {
  range 192.168.20.2 192.168.20.200
  host hostName {
    hardware ethernet macOfHost;
    fixed-address 192.168.20.20;
  }
  option subnet-mask 255.255.255.0;
  option broadcast-address 192.168.20.255;
  option routers 192.168.20.1;
}

The worker node effectively gets the IP address 192.168.20.20, but it has no internet connection. A ping to 192.168.20.1 is successful, as well as a ping to the computer that serves as a DHCP server for the head node (a ping to 192.168.1.1). The problem doesn't seem to have something to do with DNS as a ping to an IP-address (such as 8.8.4.4) fails.
Update
The network topology is as follows. There is switch connecting a computer (with internet access and running a DHCP server, IP address 192.168.1.1) and 7 other computers. One of these 7 computers gets an IP from the 192.168.1.1 computer. The IP it gets is 192.168.20.1 and the internet on that computer works fine. Now we have a DHCP server running on 192.168.20.1 in order to provide internet access to the other 6 computers, but that fails. They get IP addresses but have no internet access. We are not allowed to modify anything on the 192.168.1.1 node so it should be feasible to make internet work with this setup.
Does someone know what the problem could be?

A: Everything is working now. It turned out to be a DNS problem; changing the option routers to option routers 192.168.1.1 fixed the issue.
Pings must have been blocked somewhere in the network as responses never came through, but surfing in the browser to a specific IP-address was possible, which made me realise that DNS was the problem. Thanks everyone for your help.

A: Looks like eth0 is your internal interface. If that is the case, what is your external interface? On your "router" server, the external interface, not the internal one (which should forward the packets), needs to MASQUERADE.


text:
Q: LUNs and snapshot pool size Typical mail server, let's say 20GB of mails, partition size 100GB. I'm transferring to a LUN on shared storage P2000 and designing the whole thing. What it is typical snapshot size in this situation ? Requirement is to have 2,3 days of incremental backup. Considering the fact, that the space is not for free in this world, the snapshot size should be only 20GB or do I have to add another 100GB in case I would do the full backup ?
So the question is if the snapshot size should be (partition_size)+(size of 2,3 days of incremental backups) or only the size of the second part?

A: The snapshot space is a "copy-on-write" area - everything that needs to be changed on the disk is first copied to the CoW before it gets overwritten (or the "clean" space from the snapshot is re-referenced for this purpose depending on the snapshotting algorithm and its implementation). You only would need to dedicate the space to the snapshot which is likely to be needed for your changes.
Bear in mind though that most algorithms operate with a certain allocation unit size (depends on the implementation and sometimes on the configuration), so any change, no matter how small, would require at least one allocation unit of the CoW area.


text:
Q: High gain antenna: set wifi router to single antenna or two I recently replaced my wireless router with a newer model.  The older model has a single antenna, which I replaced with a high gain antenna, which worked great.  I recently acquired a better router, which happens to have 2 antennas.  I hooked the high gain antenna to the new router and it works fine.  However, the router has an option to limit signal to the left or the right antenna.  Is it better to have the router operate on solely the high gain antenna, or have it use both the high gain and the original.  I have another high gain antenna, of a different make and model, attached to a remote WAP, which I assume is best left there.
So whats the best mode of operation?

A: If you're doing a long-distance point-to-point wireless link over 802.11a, b, or g, then you just want the "main" (not "aux") antenna connector to have the high-gain antenna hooked up to it, pointed at the high-gain antenna on the other end of the link. Lock your equipment to using just the main antenna.
Update: Oh, you're using omnis. Read on.
If you're using omni-directional antennas, then shame on your antenna vendor for claiming that they're high-gain. I don't usually consider omni-directional antennas to be high-gain, despite how some vendors choose to advertise them. +3-9 dBi like most omnis get isn't a lot of gain compared to a directional antenna like a typical yagi.
Anyway, in the case of omnis, realize that they get higher gain in a 2-dimensional disc by sacrificing performance in the directions above and below the disc. Yes, it can be kind of confusing that "omnidirectional" doesn't really mean all directions, it means all directions in a 2D plane. An antenna that works equally well in all directions in a 3D sphere is called an "isotropic" antenna. In fact, directional antenna gain is measured in terms of how much more of the signal goes in the primary intended direction as compared to a theoretical perfectly isotropic (spherical coverage) antenna. That's why antenna gain is reported in dBi. That's deciBels referenced to an isotropic antenna. Think of antenna coverage patterns like a water balloon. A typical water balloon is basically spherical. But of you hold it and squeeze it in one direction, it extends in that direction, but contracts on the sides where you're applying pressure. So a directional antenna "gains" performance in one direction by sacrificing performance in other directions. An "omnidirectional" antenna gains performance in a 2D disc by squishing the top and bottom of the sphere. Think of a water balloon squished between two books.
If this is a single-story building or an outdoor application over flat ground, then adding a second pair of omnis isn't going to help much. But if you're dealing with a multi-story building or interesting terrain, then it could help to add another pair of omnis oriented perpendicularly to the omnis you're already using. That way you get more coverage in, say, the "vertical" direction, instead of just the "horizontal" direction.


text:
Q: Why am I getting Nullpointer Exception when starting a Service(implements LocationListener) in android? I am a newbie to Android. I have developed an app in which I am required to track a user's location using either gps, internet or using cellid.I am using 2 Activities(MainActivity and SavelocationsActivity implements LocationListener),a Service(Ser) and a Broadcast Receiver(k).
When I click a Button in the MainActivity it was required to go to SaveLocationsActivity. I used to get that a few days before but now the lattitude and longitude values have become null and I am getting the following errors i.e:
null pointer exception.

As I am a newbie please explain me what to do and where I am going wrong step by step.Thank you in advance. I am posting the code and error log below.
SaveLocationsActivity
 public class SaveLocationsActivity extends Activity implements LocationListener{
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.savelocations);
   locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
    isNetworkEnabled = locationManager
    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    //Toast.makeText(this,"in activity"+isNetworkEnabled ,Toast.LENGTH_LONG).show();
          isGPSEnabled =       locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if(isNetworkEnabled==true && isGPSEnabled==false)
    {
        getLocation(LocationManager.NETWORK_PROVIDER);

    }
    else if(isGPSEnabled==true && isNetworkEnabled==false)
    {
        getLocation(LocationManager.GPS_PROVIDER);
    }
    else if(isGPSEnabled==true && isNetworkEnabled==true )
    {
        getLocation(LocationManager.GPS_PROVIDER);
    }
    private Location getLocation(String provider) {
    // TODO Auto-generated method stub
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                6000, 10, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
              final String t5 = String.valueOf(latitude);
             final String t6 = String.valueOf(longitude);

            e5.setText(t5);
            e6.setText(t6);

            savelocation.put("t5",t5);
            savelocation.put("t6",t6);

            return location;
        }
    }
    return location;
}
@Override
public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    double latitude = l.getLatitude();
    double longitude = l.getLongitude();
    final String t5 = String.valueOf(latitude);
    final String t6 = String.valueOf(longitude);
    //Toast.makeText(SaveLocationsActivity.this,""+t5,Toast.LENGTH_LONG).show();
    e5.setText(t5);
    e6.setText(t6);
}

Error logs:
  03-21 23:34:50.309: E/AndroidRuntime(15368): FATAL EXCEPTION: main
  03-21 23:34:50.309: E/AndroidRuntime(15368): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.broadcast/com.example.broadcast.SaveLocationsActivity}: java.lang.NullPointerException
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread.access$700(ActivityThread.java:143)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.os.Handler.dispatchMessage(Handler.java:99)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.os.Looper.loop(Looper.java:137)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread.main(ActivityThread.java:4960)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at java.lang.reflect.Method.invokeNative(Native Method)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at java.lang.reflect.Method.invoke(Method.java:511)
  03-21 23:34:50.309: E/AndroidRuntime(15368):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at dalvik.system.NativeStart.main(Native Method)
 03-21 23:34:50.309: E/AndroidRuntime(15368): Caused by: java.lang.NullPointerException
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at com.example.broadcast.SaveLocationsActivity.getLocation(SaveLocationsActivity.java:209)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at com.example.broadcast.SaveLocationsActivity.onCreate(SaveLocationsActivity.java:100)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.Activity.performCreate(Activity.java:5203)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
 03-21 23:34:50.309: E/AndroidRuntime(15368):   ... 11 more

A: In the method getLocation() the problem is probably here:
if (locationManager != null) {
    location = locationManager.getLastKnownLocation(provider);
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();

because getLastKnownLocation can return null if the previous location is unknown. So by calling location.getLatitude() you incur in a NullPointerException.
To avoid this you can check the returned value for null like:
if (locationManager != null) {
    location = locationManager.getLastKnownLocation(provider);
    if(location!=null)
         //...etc...


text:
Q: How to catch ENOENT in bluebird? I like to catch ENOENT in bluebird because of the fs.exists deprecation.
So for example:
.then(() => {
    return promisedFs.unlinkAsync(excelPath);
})
.catch(ENOENT ERROR, () => { //do something })
.catch(all other errors, () => {//do something})

A: From the docs:

A filtered variant (like other non-JS languages typically have) that
  lets you only handle specific errors.
[…]
Predicate functions that only check properties have a handy shorthand.
  In place of a predicate function, you can pass an object, and its
  properties will be checked against the error object for a match:
fs.readFileAsync(...)
.then(...)
.catch({code: 'ENOENT'}, function(e) {
    console.log("file not found: " + e.path);
});

The object predicate passed to .catch in the above code
  ({code: 'ENOENT'}) is shorthand for a predicate function
  function predicate(e) { return isObject(e) && e.code == 'ENOENT' },
  I.E. loose equality is used.


text:
Q: CSS Paint API doesn't work with link  elements Didn't find that anyone raised this question here before.
I'm wondering why CSS Paint API  doesn't work with a link elements?

For example. Here is the working example with div element
https://codepen.io/una/pen/xByaoB
And in this one I replaced it with an a tag
https://codepen.io/PavelLaptev/pen/jOydKRO

And it doesn't matter will you or not add display: block. Also, a beautiful carriage is turning into a pumpkin after I add href.
And this effect applies in any case where Pain API is used for an a + href tag .
Thank you


text:
Q: VBA - How to store .SentOn in excel before sending an email in Outlook I have a macro program that sends an email in Outlook. What I want to do is store the date of .SentOn method in Excel after sending the email.
Hope you guys could help me out. Thanks!

A: SentOn is not set before an email is sent, it is only available after it is sent and moved to the Sent Items folder.


text:
Q: MySQL Foreign Keys Batch Queries using SQL Alchemy What is the best way to insert data on two MySQL tables from data frames using SQLAlchemy with a foreign key constraint. I'm inserting daily data across 2 tables and I want that for a specific date, the ID is the same across tables.
Thanks in Advance.
Table 1
| ID | Day          | Info1  |
| -- | ------------ | ------ |
| 0  | 2022-01-01   | apple  |
| 1  | 2022-01-03   | banana |
| 2  | 2022-01-02   | mango  |

Table 2
| ID | Day          | Info2  |
| -- | ------------ | ------ |
| 0  | 2022-01-01   | green  |
| 1  | 2022-01-03   | yellow |
| 2  | 2022-01-02   | orange |

Thanks in Advance


text:
Q: Saving value of one model field count to another field of the same model during save I am working on a pool app and want to add the total_likes attribute to the model which will allow me to count the number of users who liked the question, just like Youtube community question allows.
I just tried to override the save(*args, **kwargs) but got many errors.
What should I do now?
from django.db import models
from django.contrib.auth.models import User

class Question(models.Model):
    text = models.TextField()
    voters = models.ManyToManyField(to=User, blank=True, related_name='voters')
    impression = models.CharField(max_length=30, choices=impression_choices, blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(to=User, related_name='likes', blank=True)
    total_likes = models.IntegerField(default=0)

    def __str__(self):
        return self.text

def save(self, *args, **kwargs):
    self.total_likes = self.likes_set.count()
    super().save(*args, **kwargs)

The Model below works totally fine. In the model above I tried to override the save() method but I don't know how?
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.CharField(max_length=20)
    votes = models.IntegerField(blank=True, default=0)

    def __str__(self):
        return self.text


text: Q: Where is the build.gradle file of the Android application? I'm trying to install the Android Support Library with resources on the Android IDE as described here http://developer.android.com/tools/support-library/setup.html#libs-with-res however I don't find any build.gradle file in the folder, where is it located?


text:
Q: how to get FileName of process.MainModule? Process[] processlist = Process.GetProcesses();
foreach (Process proc in processlist) {
              Console.Write(proc.MainModule.FileName);
}

it give an Win32Exception was unhandled access denied how to fix this? I tried run it as adm but it get same error. Thanks in advance!

A: There are some processes that you aren't allowed to access even as administrator.  You can trap the exception and keep going:
foreach (Process proc in processlist)
{
  try
  {
    Console.WriteLine(proc.MainModule.FileName);
  }
  catch (Win32Exception e)
  {
     Console.WriteLine(proc.ToString() + "  " + e.Message);
  }
}


text:
Q: Detect how close the iPhone is to the Mac using BLE? I'm trying to detect if the iPhone is placed close enough to the Mac using BLE signal strength. I am using the following code to detect if the iPhone is in range(and it works), but I don't know how to detect if the iPhone is 'close enough'. Like -30db for instance. Does anyone know how I can achieve that? Any comments/discussions are welcome :)
import SwiftUI
import AVFoundation
import IOBluetooth
import CoreBluetooth
 import Foundation

  class BluetoothSearchDelegate : NSObject, IOBluetoothDeviceInquiryDelegate {
func deviceInquiryDeviceFound(_ sender: IOBluetoothDeviceInquiry, device: IOBluetoothDevice) {
    print("Found Device \(device.name ?? "nil")")
   }

func deviceInquiryStarted(_ sender: IOBluetoothDeviceInquiry) {
    print("started")
}

func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
    print("completed")
}
   }

 struct ContentView: View {
let delegate = BluetoothSearchDelegate()
let inquiry: IOBluetoothDeviceInquiry

init() {
    self.inquiry = IOBluetoothDeviceInquiry(delegate: delegate)
}

var body: some View {
    Button("Bluetooth") {
        inquiry.start()
    }
}
 }


text:
Q: How do I set custom navigation bar(title + titleView) for all navigation controllers and view controller? I have a tabbed application with navigation controllers in tabs and view controller in them. All of them use the same navigation controller navigation bar: back button + logo image. Currently, I'm placing this code in every view controller:
- (void)viewDidLoad
{
  [super viewDidLoad];
  self.navigationItem.title = @"Back";
  UIImage *headerImage = [UIImage imageNamed:@"Logo.png"];
  self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:headerImage] autorelease];
}

IMHO it's not the best way to do that. I'm thinking about using a category for UIViewController and to override viewDidLoad method, but every view controller has some additional code to execute in viewDidLoad, so I guess overriding is not the solution. What are the other ways?

A: You could create a subclass of UIViewController, MyViewControllerWithBackButtonAndLogo (you can come up with a better name) then implement viewDidLoad to set up the navigation item. Make all your view controllers inherit from this base class. Then just make sure the view controllers call [super viewDidLoad] in their own implementations.
Also note that to set the back button title, you should not change the navigation item's title property, but set an appropriate backBarButtonItem.

A: In proper architecture a UIViewController (or sub class) should not care in which context it is displayed (e.g. within a UINavigationController, UITabController, modal or not). Consider using the coordinator pattern where it's the coordinator's responsibility to perform this kind of configuration.
Example:
class FlowCoordinator {
    ...

    // The coordinator knows about the navigation controller
    // Individual view controllers do not.
    private let navigationController: UINavigationController

    func presentViewController(viewController: UIViewController) {
        // This setup can be common for all view controllers in this flow
        viewController.navigationItem.titleView = ...
        viewController.backBarButtonItem = ...
        viewController.navigationItem.title = ...
        navigationController.pushViewController(viewController)
    }

    ...
}


text:
Q: Facebook SDK - FBSession: No AppID provided I want to integrate with Facebook login SDK in my iOS project. The problem is I got this error message during launching the app.
2015-01-08 18:33:06.591 XXXXX[24994:2533100] *** Terminating app due to uncaught exception 'com.facebook.sdk:InvalidOperationException', reason: 'FBSession: No AppID provided; either pass an AppID to init, or add a string valued key with the appropriate id named FacebookAppID to the bundle *.plist'

I already include this line into my info.plist but it is still not working.
info.list
<key>FacebookAppID</key>
    <string><1025024xxxxxxxx></string>
    <key>FacebookDisplayName</key>
    <string>XXXXXX</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb<1025024xxxxxxxx></string>
            </array>
        </dict>
    </array>

I suspect it has not detected my Facebook ID. I'm using Xcode6.1.

A: There is two info.plist file in your project with same name. one folder for YourProjectTests in which info.plist file and other YourProject is also info.plist file.
Two plist file :

You have to set your FacebookAppID in YourProject info.plist file, but not set YourProjectTests info.plist
This error is occurs because of  YourProjectTests in which info.plist file setting FacebookAppID
Add Your FacebookAppID inabove info.plist file as above image.
Otherwise set also FacebookAppID as below.

A: if you have already added App ID in info.plist and getting crash then make sure you have added this single line code in AppDelegate Class  didFinishLaunchingOption
//Facebook setup
    ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)


text:
Q: Height is ambiguous Using Xcode 8.0 (8A218a)
I get "Height is ambiguous." even though  (in my opinion) I've got constraints all along the Y-axis.
Both of the two subviews inside the view have a height (one have height as constraint, and one as intristic content size).
See the image below for what the "Debug View Hierarchy" says.

The constraints are created in code with the following code:
label is UILabel, underline is UIView
label.translatesAutoresizingMaskIntoConstraints = false
underline.translatesAutoresizingMaskIntoConstraints = false

addSubview(label)
addSubview(underline)

label.topAnchor.constraint(equalTo: topAnchor).isActive = true
label.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
label.rightAnchor.constraint(equalTo: rightAnchor).isActive = true

label.bottomAnchor.constraint(equalTo: underline.topAnchor, constant: -5).isActive = true

underline.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
underline.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
underline.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

underline.heightAnchor.constraint(equalToConstant: 2.0).isActive = true

Here's sample-project extracted from the problematic project:
https://github.com/everlof/LayoutIssue


text:
Q: React  component problem: I can't get it to work I have a React app and I had to use Scroll To Top. I have used this before many times, and never had problems as explained:
https://reactrouter.com/web/guides/scroll-restoration/scroll-to-top
The funny thing is I can't get it working now for some reason. I tried many ways, I changed the structure of my Router, and still doesn't work.
What really happens is I get the last window position of the component before the Route change, and I obviously want to position to top on each Route change
This is my ScrollToTop.js
import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

This is inside my App.js
 <Router  basename={'/'}>
  <NavMobile />
  <Cart />

    <ScrollToTop />

     <Switch>
            <Route exact path="/home" component={Home} />
            <Route exact path="/book" component={Book} />
     </Switch>
</Router>

A: You can use the "scrollIntoView" web API, on the "root" element, adding this on App.js.
useEffect(()=> {
    document.getElementById('root').scrollIntoView();
}, [window.location.pathname])

Also, depending on the use case, you can pass props as: {behavior:'smooth'}, for a nice scroll effect.
useEffect(()=> {
    document.getElementById('root').scrollIntoView({behavior: 'smooth' });
}, [window.location.pathname])

A: You can also just put it  wherever you need it
useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

A: The issue was caused by overflow-x: hidden on the body element.
This helped me:
How to fix Gatsby JS Link component retaining scroll position and not resetting to top


text:
Q: Formulation of $p$-adic Haar measure decomposition $\DeclareMathOperator\GL{GL}\DeclareMathOperator\vol{vol}\DeclareMathOperator\diag{diag}$Suppose:

*

*$F$ is a non-archimedean local field,

*$\mathcal{O} \subset F$ its ring of integers,

*$\pi \in \mathcal{O}$ : a uniformizer,

*if $e \in \mathbb{Z}^n$, I write $\pi^e = \diag(\pi^{e_1}, \ldots \pi^{e_n})$

*$d^{\times}g$ : Haar measure on $\GL_n(F)$ normalized s.t. $\GL_n(\mathcal{O})$ has volume $1$

*Same for the the Haar measure $du$ on the upper-triangular matrices $U_n(F)$ with $1$'s on the diagonal,

*$B_n \subset  \GL_n$ : upper-triangular matrices,

*$T_n \subset  \GL_n$ : torus of diagonal matrices,

*$f$ : an integrable test function in each case.

By Iwasawa, there is the Decomposition $\GL_n(F) = B_n(F) \GL_n(\mathcal{O})$. Since $\GL_n$ is unimodular, I know that there is a nice (let's say left-invariant) Haar measure $db$ on $B_n(F)$, such that $d^{\times}g = db d^{\times}k$, where $d^{\times}k$ is the restriction of $d^{\times}g$ to $\GL_n(\mathcal{O})$, so the integration would look like
$$
\int\limits_{\GL_n(F)} f(g) d^{\times}g = \int\limits_{B_n(F)} \hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(bk) d^{\times}k db \qquad (\ast)
$$
This follows from the 'Quotient Integration Formula', for example Prop.1.5.6. in Anton Deitmar's Principle of Harmonic Analysis. Now if I pick $f = 1_{\GL_n(\mathcal{O})}$ to be the char.function of $\GL_n(\mathcal{O})$, then one has $g = bk \in \GL_n(\mathcal{O})$ iff $b \in \GL_n(\mathcal{O})$, and thus
$$
1_{\GL_n(\mathcal{O})}(bk) = 1_{B_n(\mathcal{O})}(b),
$$
and it follows by comparison that $B_n(\mathcal{O})$ has volume $1$ w.r.t. $db$.
Question
My question is now, I have seen in Cogdell's Lecture Notes on Automorphic L-Function (chapter 7) that $d^{\times}g = du \delta^{-1}(\pi^e)dk$ if one takes the Iwasawa-decomposition and decomposes it further as
$$
\GL_n(F) = \coprod_{e \in \mathbb{Z}^n} U_n(F) \pi^{e} \GL_n(\mathcal{O}),
$$
which I think means that (the author omits this part)
$$
\int\limits_{\GL_n(F)} f(g) d^{\times}g = \sum_{e \in \mathbb{Z}^n} \delta^{-1}(\pi^{e})\int\limits_{U_n(F)} \hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(u\pi^ek) dk du,
$$
The author claims further that, if $f$ is left-$U_n(F)$-invariant, then
$$
\int\limits_{U_n(F) \backslash \GL_n(F)} f(g) d^{\times}_{U \backslash G}g = \sum_{e \in \mathbb{Z}^n} \delta^{-1}(\pi^{e})\int\limits_{\GL_n(\mathcal{O})} f(\pi^ek) dk,
$$
where $d^{\times}_{U \backslash G}g$ is the (unique) $\GL_n(F)$-invariant Radon Measure on $U_n(F) \backslash \GL_n(F)$, s.t. $d^{\times}g = d^{\times}_{U \backslash G}g du$.
It seems believable and intuitive to me, but I have not been able to derive it from my little knowledge on Harmonic Analysis. Can somebody give me a hint?
My attempt
For the first one I tried $B_n(F) = \sum_{e \in \mathbb{Z}^n} U_n(F)T_n(\mathcal{O}) \pi^e$, so by $(\ast)$,
\begin{eqnarray*}
\int\limits_{\GL_n(F)} f(g) d^{\times}g & = & \sum_{e \in \mathbb{Z}^n} \int\limits_{U_n(F)T_n(\mathcal{O}) \pi^e} \hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(b k) dk db \\
& = & \sum_{e \in \mathbb{Z}^n} \int\limits_{U_n(F)T_n(\mathcal{O})} \hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(b' \pi^e k) dk d(b' \pi^e) \\
& = & \sum_{e \in \mathbb{Z}^n} \delta^{-1}(\pi^{e}) \int\limits_{U_n(F)T_n(\mathcal{O})} \hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(b' \pi^e k) dk db'\\
& = & \sum_{e \in \mathbb{Z}^n} \delta^{-1}(\pi^{e})\underbrace{\delta^{-1}(t)}_{=1}\int\limits_{U_n(F)} \hspace{1mm}\int\limits_{T_n(\mathcal{O})} \hspace{1mm} \int\limits_{\GL_n(\mathcal{O})} f(ut \pi^e k) dk d^{\times}t du\\
& \stackrel{k \mapsto t^{-1}k}{=} & \sum_{e \in \mathbb{Z}^n} \delta^{-1}(\pi^{e})\int\limits_{U_n(F)}\hspace{1mm}\int\limits_{\GL_n(\mathcal{O})} f(u\pi^ek) dk du,
\end{eqnarray*}
where in the last equation I have used Fubini, the fact that $t \pi^e = \pi^e t$ and that the measure decomposition of $U_n(F)T_n(\mathcal{O})$ forces me to take $d^{\times}t$ with $\vol(T_n(\mathcal{O}),d^{\times}t) = 1$. Is this correct? And if so, is there an easier way to see it? What about the passage to the quotient if $f$ is left-$U_n(F)$-invariant?


text:
Q: How to create output file using command line? I'm using this command to remove all duplicate lines:
sort file.txt | uniq -u

But it just displays all the unique lines in terminal.  What do I need to change to make it create a new file named newfile.txt that all the unique lines are in?

A: just redirect to a file

sort file.txt | uniq -u > newfile.txt


text:
Q: Docker Machine on Mac: Cannot see mounted Volumes on docker host/docker-machine? Where are volumes physically stored? Am on a Macbook Pro laptop and running docker-machine (0.5.0) and docker-compose (1.5.0) to get my containers going.
This means I'm using docker-machine to create my virtualbox boot2docker driven HOST machines, which will run my docker daemon and host all my containers.
I think I'm missing something critical with the concept of HOSTS and VOLUME, as they refer to Docker and the documentation.
This is my docker-compose.yml file (web simply builds the php:5.6-apache image):
web:
  restart: "always"
  build: ./docker-containers/web
  ports:
    - "8080:80"
  volumes:
    - ./src:/var/www/html
  links:
    - mysql:mysql

mysql:
  restart: "always"
  image: mysql:5.7
  volumes_from:
    - data
  ports:
    - "3306:3306"
  environment:
    - MYSQL_ROOT_PASSWORD=XXX

data:
  restart: "no"
  image: mysql:5.7
  volumes:
    - /var/lib/mysql
  command: "true"

Docker Compose file documention for volumes is here: http://docs.docker.com/compose/compose-file/
It states for volumes - Mount paths as volumes, optionally specifying a path on the host machine (HOST:CONTAINER), or an access mode (HOST:CONTAINER:ro).
HOST in this case refers to my VM created by docker-machine, correct? Or my local macbook file system? Mounting a path on my VM to a container?
Under web I declare:
volumes:
  - ./src:/var/www/html

and this is mapping my local macbook file system ./src folder on my macbook pro to my web container. If my understanding is correct though, shouldn't it be mapping the ./src folder on my VM to /var/www/html within the web container?! In theory I think I should be required to COPY my local mac file system folder ./src to my VM first, and then I do this volume declaration. It seems docker-compose is magically doing it all at once though? confused
Lastly, we can see that I'm creating a data-only container to persist my mysql data. I've declared:
volumes:
   - /var/lib/mysql

Shouldn't this create a /var/lib/mysql folder on my HOST boot2docker VM and I could then navigate to this folder on the VM, yes/no? When I use docker-machine to ssh into my machine, and then navigate to /var/lib, there is NO mysql folder at all?! Why is it not being created? Is there something wrong with my configuration? :/
Thanks in advance! Any explanations as to what I'm doing wrong here would be greatly appreciated!

A: Ok there's a couple of points that need to be addressed here.
Lets start with what a docker volume is(Try to not think about your macbook or the vagrant machine at this point. Just be mindful of the fact that the dockers use a different filesystem, where ever it may reside at this point ):
Maybe imagine it like this, in and of itself every volume in Docker is just a part of the internal file system docker uses.
The containers can use theses volumes, like they were "small harddrives" that can be mounted by them and also shared between them (or mounted by two of them at the same time, like mounting a super fast version of some ftp server to two clients or whatever :P ).
In principal you can declare these volumes ( still not thinking about your computer/vagrant itself, just the dockers ;) ) via the Dockerfile's VOLUME instruction.
Standard example, run one webserver container like so:
FROM: nginx
VOLUME /www

Now everything that goes into /www can in theory be mounted and unmounted from a container and also mounted to multiple containers.
Now Nginx alone is boring, so we want to have php run over the files that nginx stores to produce some more fun content. => We need to mount that volume into some php-fpm container.
Ergo in our compose file we'd do this
web:
  image: nginx
php:
  image: php-fpm
  volumes_from:
    - web

=> voila! every folder declared by a VOLUME directive in the nginx/web container will be visible in the php one. Important point to note here, whatever is in nginx's /www, will override whatever php has in /www.
If you put the :ro, php can't even write to that folder :)
Now moving close to your issue, there's a second way to declare volumes, that does not require them being declared in the Dockerfile. This can be done by mounting volumes from the host (in this case your vagrant/boo2docker thingy). Let's discuss this as though we're running on a native Linux first.
If you were to put something like:
volumes:
 - /home/myuser/folder:/folder

in your docker-compose.yml, then this will mean that /home/myuser/folder will now be mounted into the docker. It will override whatever the docker has in /folder and just like the /www also be accessible from the thing that declared it. Now the Linux machine the docker daemon is running on.
So much for the theory :), in fact you probably just need the following advice to get your stuff going :):
The way boot2docker/docker-machine/kitematic and all these things deal with the issue is simply, that they first of all just mount a volume in the vagrant machine to the docker containers, and them simply also mount this thing into your Mac file system, hoping it will all work out :P
Now for the practical problem all of us using this (or just trying to help their coworkers into the world of sweet sweet Docker :P) on Mac are facing is permissions. I mean think about it ( root or some other user handles files in the container,the user vagrant might handle files in the vagrant host and then your Mac user "skalfyfan" handles those files in Mac. They all have different user id's and whatnot => many problems ensue with that, and somewhat depending on what you're actually running in Docker. Mysql and Apache are especially painful, because they do not run as root within the container. This means, they often have trouble writing to the Mac file system.
Before trying the second approach below, simply try putting your container volumes under you Mac home directory. This will resolve issues with MySQL in most cases as I have found over time.
Btw: No need to declare full paths to volumes ./folder is fine and read relative to the place your docker-compose.yml resides!
Just put the compose-yml in your Mac users folder, that's all that matters. No chmod 777 -R :P will help you here, it just needs to be under your home folder :)
Still some apps ( Apache for example ) will still give you a hard time. The fact that the user id of whatever runs in the container differs from your Mac user id will make your life hell. In order to get around this, you need to adjust the user id as well as the user group in a way that doesn't conflict with your Mac's permissions. The group you want on a Mac is staff, a UID that works would be for example 1000.
Hence you could put this at the end of your Dockerfile:
RUN usermod -u 1000 www-data
RUN usermod -G staff www-data

or
RUN usermod -u 1000 mysql
RUN usermod -G staff mysql

So as you have now learnt:

In theory I think I should be required to COPY my local mac file
  system folder ./src to my VM first, and then I do this volume
  declaration. It seems docker-compose is magically doing it all at once
  though?

Right on, it does that :)

Lastly, we can see that I'm creating a data-only container to persist
  my mysql data. I've declared:
      volumes:
         - /var/lib/mysql

This one you got wrong :) As explained, if you don't give a host folder, then Docker will persist this path. But only for this container and all will stay within the docker file system. Nothing is written to the host at all! This will always only happen if you give a host folder before the container folder!
Hope this helped :)


text:
Q: Display setting in Adjust for TV Mode screws up stylus pen cursor position - solved though I had an issue with the cursor for a Sony Stylus Pen on my X360 2500 Ryzen laptop.
The cursor showed incorrectly.
Checking OFF the setting for adjust for TV solved this problem.
I suspect that the option does allow for changing the screen resolution (or zoom or whatever it does).
I had this matrix with the problem from
xinput --list-props 23
Coordinate Transformation Matrix (149): -0.500000, 0.000000, 0.500000, 0.000000, -0.923867, 0.923867, 0.000000, 0.000000, 1.000000
and when normal again
Coordinate Transformation Matrix (149): -0.500000, 0.000000, 1.000000, 0.000000, -1.000000, 1.000000, 0.000000, 0.000000, 1.000000
so I probably would have needed to correct it by
xinput set-prop "ELAN0732:00 04F3:2536 Pen (0)" --type=float "Coordinate Transformation Matrix
more details on the problem
In the middle of the screen it was ok, to the right the cursor was 1cm to the left of the pen, and to the right the cursor was 1cm to the right.
I noticed that somehow I had Adjust for TV set in the display properties of Ubuntu 19.04. I had checked this for the second monitor TV but do not recall doing so for the laptop screen. I have been experimenting with xrandr though.

A: Press super key
type Display
Go to Screen Display Properties
Select affected Display
Toggle off Display for TV if it is on.


text:
Q: Extrapolating with IDW (Feature Classes) in ArcGIS Pro? I have been struggling to extrapolate beyond the extent of the point features input into the IDW tool of ArcGIS Pro.
I believe IDW interpolation is the method for me, i just need the process to extend beyond the input points slightly to fit a bigger area.
Specifying a mask in the environment settings seems only to clip the same extent (that is that of the input points), to the mask.

A: It appears you cannot extrapolate using IDW interpolation. Spline was a sufficient substitute and can be extrapolated.


text:
Q: Saving VCard contact via intent I want to save a contact data which is in VCard format in user's contacts via sending intent. Is there any way to do it?
NOTE: I don't want to save VCard data in a .vcf file and then give it's uri to intent like the code below.
String scanned = "..." // contact in VCard format
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
File vcfFile = new File(getCacheDir(), "tmp.vcf");
try {
    FileOutputStream fos = new FileOutputStream(vcfFile);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    osw.write(scanned);
    osw.close();
    fos.close();
    i.setDataAndType(Uri.fromFile(vcfFile), "text/vcard");
    startActivity(i);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

A: If the contact is indeed in the contacts database, you could look at the android contacts app's code, to see how to share a vcard out of it (found from here, inside a file called "QuickContactActivity.java" ) :
private void shareContact() {
    final String lookupKey = mContactData.getLookupKey();
    final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, shareUri);

    // Launch chooser to share contact via
    final CharSequence chooseTitle = getText(R.string.share_via);
    final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);

    try {
        mHasIntentLaunched = true;
        ImplicitIntentsUtil.startActivityOutsideApp(this, chooseIntent);
    } catch (final ActivityNotFoundException ex) {
        Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
    }
}


text:
Q: Parallel.ForEach produces inaccurate output I have got a scenario where I have to run nested foreach's to create a list. The pseudo code of what I do is below
foreach(var x in list)           (ForEach1)
   get m // List<string>
   foreach(var k in m)           (ForEach2)
     get t // List<string>
        foreach(var o in t)      (ForEach3)
          // Do some work. and add output to a list
          // which is defined before first for each

However, because I retrieve data from an external system(from Perforce by running Perforce commands) in Foreach2 and Foreach3, this piece of code runs really slow and I do need to speed this up.
I tried to use  Parallel.ForEach to run ForEach1 or ForEach2 in parallel. In my tests, it improved the performance significantly, but produced inaccurate result.

*

*If I run this code with foreach statements, the list I produce has 625 items(which is right)

*If I use Parallel.ForEach for ForEach1, I get 325 added to the list which is well below than I expect.

*and Finally if I use Parallel.ForEach for ForEach2, I get 605 items added to list, still 20 missing.

I am not sure what I am doing wrong, or what I am missing. what are the things needing to be considered when using Parallel foreach or for?
Could anyone help me to sort out please? any other suggestion to improve performance would be appreciated
Thanks

A: I do not know what your 'get' operations are, but it also could be an issue with closures.
You can search the net for it.
For example The foreach identifier and closures and http://www.codethinked.com/c-closures-explained


text:
Q: Codeigniter getinstance() error not loading any library,helpers? i m creating a login system in codeigniter. i m new in codeigniter. i have getting this error when testing my login system
    A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: controllers/login.php

Line Number: 92

Fatal error: Call to a member function userdata() on a non-object in P:\xampp\htdocs\xxxxx\xxxxx\application\controllers\login.php on line 92

here is my login.php controller file
<?php
class Login extends CI_Controller {

    function __construct()
    {
        if($this->is_logged_in() === true){
            redirect('welcome');
        }
    }

    function index()
    {
        $data['main_content'] = 'login_form';
        $data['class_name'] = get_class();
        $data['no_header'] = '1';
        $data['no_footer'] = '1';
        $this->load->view('includes/template', $data);
    }

    function validate_credentials()
    {
        $this->load->model('admin_model');
        $query = $this->admin_model->validate();
        print_r($query);
        if($query) // if the user's credentials validated...
        {
            $data = array(
                'AdminID' => $query,
                'is_logged_in' => true
            );
            $this->session->set_userdata($data);
            redirect('welcome');
        }
        else // incorrect username or password
        {
            echo "here";
            exit;
            $this->index();
        }
    }

    function signup()
    {
        $data['main_content'] = 'signup_form';
        $this->load->view('includes/template', $data);
    }

    function create_member()
    {
        $this->load->library('form_validation');

        // field name, error message, validation rules
        $this->form_validation->set_rules('first_name', 'Name', 'trim|required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
        $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
        $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');

        if($this->form_validation->run() == FALSE)
        {
            $this->load->view('signup_form');
        }

        else
        {
            $this->load->model('membership_model');

            if($query = $this->membership_model->create_member())
            {
                $data['main_content'] = 'signup_successful';
                $this->load->view('includes/template', $data);
            }
            else
            {
                $this->load->view('signup_form');
            }
        }

    }

    function logout()
    {
        $this->session->sess_destroy();
        $this->index();
    }

    function is_logged_in()
    {
        $CI =&get_instance();
        $is_logged_in = $CI->session->userdata('is_logged_in');
        if(isset($is_logged_in) || $is_logged_in === true)
        {
            return true;
        }else{
            return false;
        }
    }
}

i have tried
$CI =&get_instance();

$CI =get_instance();

$this->session->userdata

all three way but getting error.

A: you are calling the is_logged_in() function in the Controller's constructor without calling the parent constructor first. maybe that's probably why some resources aren't loaded yet.
try adding this:
function __construct()
{
    parent::__construct(); //you always have to call parent's constructor before ANYTHING

    if($this->is_logged_in() === true){
        redirect('welcome');
    }
}

A: You're not loading the session library for the new instance you create with get_instance().
Simply do, assuming session is already loaded and, as noted by @jere, you call the parent::__construct() in your controller:
function is_logged_in()
{
    $is_logged_in = $this->session->userdata('is_logged_in');
    if(isset($is_logged_in) || $is_logged_in === true)
    {
        return true;
    }else{
        return false;
    }
}

Don't know why using another instance of the class here.
If you oughta do that, try loading the session library again, like:
$CI->load->library('session')
$is_logged_in = $CI->session->userdata('is_logged_in');
//rest of your old code


text:
Q: File.Copy() to file server with network Credential I am writing console application which will Copy file from my local disk to file server.  This folder is protecting by username and password. File.Copy() method does not work. It gives permission error. I have looked to this code
I have tried it but it does not work. First it was written in VB but I have changed the code to C# but there are have some errors. I don't know what does this error mean.  Maybe you can advise me other way coping  file to protected File Server
with simple File.Copy(bla bla) it gives me "you have not permission"
when i converted VB code to C# it gived me error below: Attempted to read or write protected memory
I have found solution
You can Follow It

A: You could use the little impersonation class I wrote some years ago:
using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
   // code that executes under the new context.
   File.Copy( x, y );
}


text:
Q: Setting up parLapply() for parallel processing I have a very large dataset (17,000 features in 360 samples), for which i need to calculate some diversity indices. This takes extremely long (3-4 days on a single sample), so i want to go parallel. I have about 50 cpus available, so each cpu should do about 7 samples (columns) sequentially.
I can run this:
df <- data.frame(matrix(sample.int(1000, 2000*360, TRUE), 2000, 360))
dflist <- as.list(df)

library(parallel)
cl <- makeCluster(detectCores()-1)

clusterExport(cl, "dflist")
results <- parLapply(cl, df.list, function(x) range(x)) #range as a wild card

, and this yields the desired output, but i dont know if this really works as i think it works.
So, my question is:
Does this command let each process pick up the next free object in dflist, once it has finished its current task?
Or do i have to assign a specific set of objects in dflist to each process?


text:
Q: EventsAdapter() in EventsAdapater cannot be applied i try to make custom listview, then I get errors, and i don't know why.
there was an error at this, R.layout.list_events_item,listEvents
and the error message is:

EventsFragment.java
public class EventsFragment extends Fragment {
    private View paramView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        paramView = inflater.inflate(R.layout.fragment_events,container,false);
        ListView listView = (ListView) paramView.findViewById(R.id.listViewEvents);
        List<Events> listEvents = new ArrayList<Events>();
        Events events = new Events(1,"12:00","A1221",
                "Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
        listEvents.add(events);
        events = new Events(2,"11:20","A1221",
                "Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
        listEvents.add(events);
        listView.setAdapter(new EventsAdapter(this, R.layout.list_events_item,listEvents));

        return paramView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }
}

EventsAdapter.java
public class EventsAdapter extends ArrayAdapter<Events> {
    List<Events> listEvents;
    Context context;
    int layout;
    public EventsAdapter(Context context, int layout, List<Events> listEvents){
        super(context,layout,listEvents);
        this.context=context;
        this.layout=layout;
        this.listEvents=listEvents;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View v = convertView;
        EventsHolder holder;
        if (v == null){
            LayoutInflater vi=((Activity)context).getLayoutInflater();
            holder = new EventsHolder();
            holder.time=(TextView) v.findViewById(R.id.time);
            holder.signature = (TextView) v.findViewById(R.id.signatureId);
            holder.sensor = (TextView) v.findViewById(R.id.sensor);
            holder.attacker = (TextView) v.findViewById(R.id.attacker);
            holder.attacked = (TextView) v.findViewById(R.id.attacked);
            v.setTag(holder);
        }else {
            holder=(EventsHolder) v.getTag();
        }
        Events events = listEvents.get(position);
        holder.time.setText(events.getTime());
        holder.signature.setText(events.getSignature_id());
        holder.sensor.setText(events.getSensor());
        holder.attacker.setText(events.getAttacker_port());
        holder.attacked.setText(events.getAttacked_port());
        return v;
    }
    static class EventsHolder{
        TextView time;
        TextView signature;
        TextView sensor;
        TextView attacker;
        TextView attacked;
    }
}

my Events model
public class Events {
    int id;
    String time;
    String signature_id;
    String alert_message;
    String ip_source;
    String ip_destination;
    String sensor;
    String protocol;
    int attacker_port;
    int attacked_port;

    public Events(int id, String time, String signature_id, String alert_message, String ip_source, String ip_destination, String sensor, String protocol, int attacker_port, int attacked_port) {
        this.id = id;
        this.time = time;
        this.signature_id = signature_id;
        this.alert_message = alert_message;
        this.ip_source = ip_source;
        this.ip_destination = ip_destination;
        this.sensor = sensor;
        this.protocol = protocol;
        this.attacker_port = attacker_port;
        this.attacked_port = attacked_port;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getSignature_id() {
        return signature_id;
    }

    public void setSignature_id(String signature_id) {
        this.signature_id = signature_id;
    }

    public String getAlert_message() {
        return alert_message;
    }

    public void setAlert_message(String alert_message) {
        this.alert_message = alert_message;
    }

    public String getIp_source() {
        return ip_source;
    }

    public void setIp_source(String ip_source) {
        this.ip_source = ip_source;
    }

    public String getIp_destination() {
        return ip_destination;
    }

    public void setIp_destination(String ip_destination) {
        this.ip_destination = ip_destination;
    }

    public String getSensor() {
        return sensor;
    }

    public void setSensor(String sensor) {
        this.sensor = sensor;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public int getAttacker_port() {
        return attacker_port;
    }

    public void setAttacker_port(int attacker_port) {
        this.attacker_port = attacker_port;
    }

    public int getAttacked_port() {
        return attacked_port;
    }

    public void setAttacked_port(int attacked_port) {
        this.attacked_port = attacked_port;
    }
}

A: Try changing this to getActivity()


text:
Q: Cannot open IJulia; it instead starts IPython How can I use IJulia in my browser?
When I start to open it by executing ipython notebook --profile julia on my Terminal, a new window opens on my browse - however, it is IPython notebook, not IJulia notebook.
Why does it show IPython? For your information, I use Python 2.7.5 and iPython 1.1, and 0.2.0 for Julia. Also, when I tried running Pkg.add("IJulia"), INFO: Nothing to be done. was shown on my screen.

A: Probably just a caching issue of the logo. Try executing some code to see if the kernel is actually python or Julia. IJulia notebook is actually an IPython notebook, but which talk to Julia in the back.


text:
Q: Continuous Delivery of NodeJS App using AWS Services Can someone share the thoughts that what could be the best way to do CI/CD of a NodeJS app using only AWS Services.
I have gone through some blogs but I did not find any where complete AWS Services stack has been used.
Suggestions would be appreciated.
Please advise what could be done otherwise if not AWS Services stack completely.
Thanks

A: If you need to use AWS services, then your option is to use AWS Code Pipeline which is tailor made for doing CI/CD on AWS. It integrates with other AWS services such as CodeCommit, CodeDeploy. Code Pipeline can also work with other non-AWS platforms such as Jenkins and GitHub. You can have a look at the aws official documentation for details on how to implement a CI/CD pipeline.


text:
Q: PHP fopen fails - does not have permission to open file in write mode I have an Apache 2.17 server running on a Fedora 13. I want to be able to create a file in a directory.
I cannot do that. Whenever I try to open a file with php for writing fopen(,'w'), it tells me that I don't have permission to do that.
So i checked the httpd.conf file in /etc/httpd/conf/. It says user apache, group apache. So I changed ownership (chown -R apache:apache .*) of my whole /www directory to apache:apache. I also run chmod -R 777 *
Apart from knowing how terribly dangerous this is, it actually still gives me the  same error, even though I even allow public write!

A: Check your error log, it will tell you the problem. I think it will boil down to one of these four things:
- PHP safe_mode is enabled for the domain. The error log will make this clear.
- PHP open_basedir restrictions are in effect. Again, the error log will make this clear.
- You have the wrong document root
- A parent directory has the wrong permissons.
Also, change those permissions as soon as possible. If you're using PHP as an apache module, if your website gets compromised the attacker will be able to write custom PHP scripts and execute them at will via the browser.
If you're using FC13 and have acl enabled, consider using a setfacl instead of chmod -R 777 - it's a little more secure (only specified for given users) and easier to undo:
setfacl -R -m user:apache:rwx /path/to/webroot
setfacl -d -R -m user:apache:rwx /path/to/webroot.


text:
Q: Running Virtual box and Ubuntu 17.04 on a Razer Blade Stealth - time outs I have a Razer Bladed Stealth Laptop, and I have intalled Ubuntu Gnome 17.04 on it.
I have also installed the latest version of Virtualbox.
All works well and I can run

vagrant up

and

vagrant ssh

and I can see my files are mirrored inside the box. Thing is when I go to the URL in the browser and expect it to load the site it times out every time.
I have another laptop next to me running ubuntu 14.04 and I have cross checked all the config files and it should be working.
Variables are:
Ubuntu 14.04 (working) vs Ubuntu 17.04 (not working)
The hardware the newer Razer Blade Stealth is not working
Trying to solve this, I have found some references to issues with Virtualization, and I have turned of "Safe boot".
The linked article also says:

This post also applies if you are running your system with module
  signature verification enabled (CONFIG_MODULE_SIG) even if it's not
  running in Secure Boot.

I can't seem to tell if this is turned on or not for a normal install of Ubuntu Gnome 17.04? If so, I need to recompile the linux kernal in order to turn this off?
Otherwise I'm stumped. My hosts file is the same as on the working laptop, and the box seems to be up since I can ssh into it. The files are there...
...but some how it's not getting from the browser to load the virtual website.
I'm stuck.
Please let me know how I can debug this :)

A: I had the same problem with all vagrant boxes and found the solution to be:
removing the second line in the /etc/hosts file
just uncomment or remove the line containing:
 127.0.1.1 [computer-name]

Installing net-tools:
It seems like ubuntu 17.04 is not installing the package net-tools anymore.
So installing them via
 sudo apt-get install net-tools

and it should work again.


text:
Q: Validating bash script argument by flag name and value I have a bash script that I want invoked using a require -p argument that is of type string/alphanumeric. For example:
sh myscript.sh -p abc123

My best attempt thus far:
#!/usr/bin/bash
mypassword=${p:}
echo $mypassword
if [ -z mypassword ]
then
  echo "error"
fi

Since this is a required argument, I don't have a good meaningful default to apply (hence my attempt with using ${p:} to set mypassword to empty/null, and then attempt the null check conditional right afterwards).
When I run it via sh myscript.sh -p abc123 I get:
myscript.sh: line 46: ${p:}: bad substitution

All I'm trying to accomplish is this:
If -p wasn't specified, or if it was specified, but no value for it was given (e.g. -p abc123), I want to echo "error". In other words, -p must not only be provided, but a value for it must be supplied as well.
Any ideas as to how I could accomplish this?

A: [ -z mypassword ] will always evaluate to false, because the word mypassword has a length greater than zero. You could test with, for instance, [[ -z $mypassword ]].
Also, the term ${p:}  does not make sense. Perhaps you meant ${p:=} ?
UPDATE:
One more note: The way you are invoking your script would not work, even after those fixed, becaues mypassword will always be empty. For your script to work, p must be an environment variable holding the password. You would have to call your script (assuming it is in your working directory) like this:
# To run it as sh-script (POSIX shell)
p=THIS_IS_MY_PASSWORD sh myscript.sh

# To run it as bash-script, if the script is executable
p=THIS_IS_MY_PASSWORD ./myscript.sh

# To run it as bash-script, if the script is not executable
p=THIS_IS_MY_PASSWORD bash myscript.sh


text:
Q: Cleanest Way to Allow Empty Scheme in Django URLField I'm using Django 2.0 and trying to allow users to input a link to their website in a django ModelForm. I would like for my URLField to validate urls even when they have no scheme prefix.
I have read this solution: django urlfield http prefix. I'm wondering if there is a way to achieve this without writing my own custom regex in a RegexValidator. It doesn't seem like a very DRY solution to repeat all of the regex logic that is built into the URLValidator.
I want to do something like the below:
website = models.CharField(max_length=400, blank=True, null=True, validators=[URLValidator(schemes=['', 'http', 'https', 'ftp', 'ftps'])])

This obviously doesn't work because of the way the URLValidator's call method validates against the given schemes.
    def __call__(self, value):
        # Check first if the scheme is valid
        scheme = value.split('://')[0].lower()
        if scheme not in self.schemes:
            raise ValidationError(self.message, code=self.code)

Adding an empty string to the schemes list doesn't work because splitting the url in this way returns the entire URL (as a user typically does not include :// if that user is not including a scheme prefix).
Now, I could subclass URLField and overwrite the entire call method in order to change the way that it handles schemes, but the call method includes all of the regex so this seems to be no more DRY than simply copying the URLField regex into my own RegexValidator.
Is there a cleaner or more "Djangonic" way to achieve this?

A: You could subclass the URLValidator and prefix schemeless values with http:// before calling super(). This avoids any duplication of code from URLValidator.
from django.core.validators import URLValidator

class OptionalSchemeURLValidator(URLValidator):
    def __call__(self, value):
        if '://' not in value:
            # Validate as if it were http://
            value = 'http://' + value
        super(OptionalSchemeURLValidator, self).__call__(value)


text:
Q: Beautiful Soup Tree Backward Navigation Shell screen shot
Hello:
I am a Python neophyte so apologies in advance if this question is too easy. I've been searching like crazy for an answer but cannot seem to find an example that is applicable to my case.
In Python 3 running Beautiful Soup, I am trying set my html tree reference as a specific href and then scrape the 6 preceding numerical values from the url below.
url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm'

My reason for starting from the href tag is that it is the only reference in the html which stays the same and is not repeated again.
In my example, I would like to start at the href tag:
href="./hist/LeafHandler.ashx?n=PET&s=W_EPOOXE_YIR_NUS_MBBLD&f=W"

Then scape the individual contents from the six "td=class" tags preceding that tag:
936, 934, 919,957, 951, 928.

Thanks in advance for any help.

A: First select the anchor using the href, then find the six previous td's:
from bs4 import BeautifulSoup
import requests
url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm'
soup = BeautifulSoup(requests.get(url).content,"html.parser")
anchor = soup.select_one("a[href=./hist/LeafHandler.ashx?n=PET&s=W_EPOOXE_YIR_NUS_MBBLD&f=W]")
data = [td.text for td in anchor.find_all_previous("td","DataB", limit=6)]

If we run the code, you can see we get text from the previous six td's:
In [1]: from bs4 import BeautifulSoup
   ...: import requests
   ...: url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm'
   ...: soup = BeautifulSoup(requests.get(url).content,"html.parser")
   ...: anchor = soup.select_one("a[href=./hist/LeafHandler.ashx?n=PET&s=W_EPOOX
   ...: E_YIR_NUS_MBBLD&f=W]")
   ...: data = [td.text for td in anchor.find_all_previous("td","DataB", limit=6
   ...: )]
   ...:

In [2]: data
Out[2]: ['934', '919', '957', '951', '928', '139']

That does not quite get there as there as there are two different classes for the td's Current2 and DataB sdo we can use the parent of the anchor which will be a td itself:
In [5]: from bs4 import BeautifulSoup
   ...: import requests
   ...: url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm'
   ...: soup = BeautifulSoup(requests.get(url).content,"html.parser")
   ...: anchor_td = soup.find("a", href="./hist/LeafHandler.ashx?n=PET&s=W_EPOOXE_Y
   ...: IR_NUS_MBBLD&f=W").parent
   ...: data = [td.text for td in anchor_td.find_all_previous("td", limit=6)]
   ...:

In [6]: data
Out[6]: ['936', '934', '919', '957', '951', '928']

Now we get exactly what we want.
Lastly we could get the grandparent of the anchor i.e the main td then use a select using the the both the class names in our select:
href = "./hist/LeafHandler.ashx?n=PET&s=W_EPOOXE_YIR_NUS_MBBLD&f=W"
grandparent = soup.find("a", href=href).parent.parent
data = [td.text for td in grandparent.select("td.Current2,td.DataB")]

Again data gives us the same output.

A: The format of the file is a number of tables, the one you are interested in being the second. Since you know the value of the href attribute you want to match on, one way to access the parts you need would be to iterate over the table rows, first of all checking in the href value is the one you want.


text:
Q: Pandas Multi-Index - Can't convert non-uniquely indexed DataFrame to Panel Given a time series data, I'm trying to use panel OLS with fixed effects in Python. I found this way to do it:
Fixed effect in Pandas or Statsmodels
My input data looks like this (I will called it df):
    Name    Permits_13  Score_13    Permits_14  Score_14    Permits_15  Score_15
0   P.S. 015 ROBERTO CLEMENTE   12.0    284 22  279 32  283
1   P.S. 019 ASHER LEVY 18.0    296 51  301 55  308
2   P.S. 020 ANNA SILVER    9.0 294 9   290 10  293
3   P.S. 034 FRANKLIN D. ROOSEVELT  3.0 294 4   292 1   296
4   P.S. 064 ROBERT SIMON   3.0 287 15  288 17  291
5   P.S. 110 FLORENCE NIGHTINGALE   0.0 313 3   306 4   308
6   P.S. 134 HENRIETTA SZOLD    4.0 290 12  292 17  288
7   P.S. 137 JOHN L. BERNSTEIN  4.0 276 12  273 17  274
8   P.S. 140 NATHAN STRAUS  13.0    282 37  284 59  284
9   P.S. 142 AMALIA CASTRO  7.0 290 15  285 25  284
10  P.S. 184M SHUANG WEN    5.0 327 12  327 9   327

So first I have to transform it to Multi-index (_13, _14, _15 represent data from 2013, 2014 and 2015, in that order):
df = df.dropna()
df = df.drop_duplicates()

rng = pandas.date_range(start=pandas.datetime(2013, 1, 1), periods=3, freq='A')
index = pandas.MultiIndex.from_product([rng, df['Name']], names=['date', 'id'])
d1 = numpy.array(df.ix[:, ['Score_13', 'Permits_13']])
d2 = numpy.array(df.ix[:, ['Score_14', 'Permits_14']])
d3 = numpy.array(df.ix[:, ['Score_15', 'Permits_15']])
data = numpy.concatenate((d1, d2, d3), axis=0)
s = pandas.DataFrame(data, index=index, columns=['y', 'x'])
s = s.drop_duplicates()

Which results in something like this:
        y   x
date    id
2013-12-31  P.S. 015 ROBERTO CLEMENTE   284 12
P.S. 019 ASHER LEVY 296 18
P.S. 020 ANNA SILVER    294 9
P.S. 034 FRANKLIN D. ROOSEVELT  294 3
P.S. 064 ROBERT SIMON   287 3
P.S. 110 FLORENCE NIGHTINGALE   313 0
P.S. 134 HENRIETTA SZOLD    290 4
P.S. 137 JOHN L. BERNSTEIN  276 4
P.S. 140 NATHAN STRAUS  282 13
P.S. 142 AMALIA CASTRO  290 7
P.S. 184M SHUANG WEN    327 5
P.S. 188 THE ISLAND SCHOOL  279 4
HENRY STREET SCHOOL FOR INTERNATIONAL STUDIES   255 4
TECHNOLOGY, ARTS, AND SCIENCES STUDIO   282 18
THE EAST VILLAGE COMMUNITY SCHOOL   306 35
UNIVERSITY NEIGHBORHOOD MIDDLE SCHOOL   277 4
THE CHILDREN'S WORKSHOP SCHOOL  302 35
NEIGHBORHOOD SCHOOL 299 15
EARTH SCHOOL    305 3
SCHOOL FOR GLOBAL LEADERS   286 15
TOMPKINS SQUARE MIDDLE SCHOOL   306 3
P.S. 001 ALFRED E. SMITH    303 20
P.S. 002 MEYER LONDON   306 8
P.S. 003 CHARRETTE SCHOOL   325 62
P.S. 006 LILLIE D. BLAKE    333 89
P.S. 011 WILLIAM T. HARRIS  320 30
P.S. 033 CHELSEA PREP   313 5
P.S. 040 AUGUSTUS SAINT-GAUDENS 326 23
P.S. 041 GREENWICH VILLAGE  326 25
P.S. 042 BENJAMIN ALTMAN    314 30
... ... ... ...
2015-12-31  P.S. 054 CHARLES W. LENG    309 2
P.S. 055 HENRY M. BOEHM 311 3
P.S. 56 THE LOUIS DESARIO SCHOOL    323 4
P.S. 057 HUBERT H. HUMPHREY 287 2
SPACE SHUTTLE COLUMBIA SCHOOL   307 0
P.S. 060 ALICE AUSTEN   303 1
I.S. 061 WILLIAM A MORRIS   291 2
MARSH AVENUE SCHOOL FOR EXPEDITIONARY LEARNING  316 0
P.S. 069 DANIEL D. TOMPKINS 307 2
I.S. 072 ROCCO LAURIE   308 1
I.S. 075 FRANK D. PAULO 318 9
THE MICHAEL J. PETRIDES SCHOOL  310 0
STATEN ISLAND SCHOOL OF CIVIC LEADERSHIP    309 0
P.S. 075 MAYDA CORTIELLA    282 19
P.S. 086 THE IRVINGTON  286 38
P.S. 106 EDWARD EVERETT HALE    280 27
P.S. 116 ELIZABETH L FARRELL    291 3
P.S. 123 SUYDAM 287 14
P.S. 145 ANDREW JACKSON 285 4
P.S. 151 LYNDON B. JOHNSON  271 27
J.H.S. 162 THE WILLOUGHBY   283 22
P.S. 274 KOSCIUSKO  282 2
J.H.S. 291 ROLAND HAYES 279 13
P.S. 299 THOMAS WARREN FIELD    288 5
I.S. 347 SCHOOL OF HUMANITIES   284 45
I.S. 349 MATH, SCIENCE & TECH.  285 45
P.S. 376    301 9
P.S. 377 ALEJANDRINA B. DE GAUTIER  277 3
P.S. /I.S. 384 FRANCES E. CARTER    291 4
ALL CITY LEADERSHIP SECONDARY SCHOOL    325 18

However, when I try to call:
reg  = PanelOLS(y=s['y'],x=s[['x']],time_effects=True)

I get an error:

ValueError: Can't convert non-uniquely indexed DataFrame to Panel

That's my first time using Pandas, this may be a simple question but I don't know what's the problem. As far as I got I have a multi-index object as required.
I don't get why I have duplicates (I put a lot of drop_duplicates() try to get rid of any duplicated data -- which I don't think is the answer, though). If I have data for the same school for three years, shouldn't I have duplicate data somehow (looking just at the row Name, for example)?
EDIT
dfis 935 rows × 7 columns, after getting rid of NaNs rows.
So I expected s to be 2805 rows × 2 columns, which is exactly what I have.
If i run this:
s = s.reset_index().groupby(s.index.names).first()
reg  = PanelOLS(y=s['y'],x=s[['x']],time_effects=True)

I get another error:

ValueError: operands could not be broadcast together with shapes (2763,) (3,)

Thank you.

A: Using the provided pickle file, I ran the regression and it worked fine.
-------------------------Summary of Regression Analysis-------------------------

Formula: Y ~ <x>

Number of Observations:         2763
Number of Degrees of Freedom:   4

R-squared:         0.0268
Adj R-squared:     0.0257

Rmse:             16.4732

F-stat (1, 2759):    25.3204, p-value:     0.0000

Degrees of Freedom: model 3, resid 2759

-----------------------Summary of Estimated Coefficients------------------------
      Variable       Coef    Std Err     t-stat    p-value    CI 2.5%   CI 97.5%
--------------------------------------------------------------------------------
             x     0.1666     0.0191       8.72     0.0000     0.1292     0.2041
---------------------------------End of Summary---------------------------------

I ran this in Jupyter Notebook


text:
Q: Command line scaffolding in asp.Net VNext I am trying to create a Web Application in Visual studio 2015 Preview. I am trying to create views using the Command Line Scaffolding.
I used the following command:
k gen controller -name ProductController -m ViewModels.Product -dc ProductContext -f -udl

The ViewModels.Product class is defined in another project and referenced in UI project. I get the following error while running the command:
Finding the generator 'controller'...
Running the generator 'controller'...
Attempting to figure out the EntityFramework metadata for the model and DbContext.
The entity type 'ViewModels.Product' requires a key to be defined.

In the Product class I have added a reference to System.ComponentModel.DataAnnotations and defined a property with the [key] attribute.
It is creating the DataContext class, not views.
Anyone please suggest where I am wrong.

A: This is a known issue with the scaffolding right now, as a work around, you can configure the Key in the generated DbContext's OnModelCreating method like this:
builder.Entity<Product>().Key(p => p.MyKeyName);

and then scaffold again.


text:
Q: UITextView links highlighting, but not clickable when in custom UITableViewCell
I've got these three text views (bottom of the hierarchy) inside a custom tableviewcell.

Here are their settings. They highlight the right things (phone numbers, addresses, etc) but don't allow me to click them.

A: Can you try manual create your textview. The link below be able to click:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString* cellIdentify = @"Cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];

if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
}

UITextView* textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 200, 50)];
textView.text = @"12345678 http://haivl.com";
textView.dataDetectorTypes = UIDataDetectorTypeLink;
textView.editable = NO;
textView.selectable = YES;
[cell addSubview:textView];
return cell;

}

A: If i m correct, you want to make the interaction with text view...
[ textview setUserInteractionEnabled:YES ];
and if you want to make it editable then you can do it by,
textview.editable = Yes;
or bye checking the Editable like this


text:
Q: "For only through assiduous repetition is it possible to redistribute skewed tendencies." | meaning To set the quote into context here's an excerpt from Hard-Boiled Wonderland and the End of the World by H. Murakami.

There was little left to do but lean up against a wall and count the change in my pockets. For someone in my profession, know how to kill time is as important a method of training as gripping rubber balls is for a boxer. Although, in any strict, it's not killing time at all. For only through assiduous repetition is it possible to redistribute skewed tendencies.

I would interpret as it takes lot of effort (assiduous repetition) to replace (redistribute) bad habits (skewed tendencies) but it's does not seem to fit here.

A: When your head is al over the place, doing a simple task that requires your attention is a means to gather your thoughts.
Like Holmes judging something as a three pipe problem; keeping the pipe burning requires just enough attention to distract you from distractions and stimulate a calmness of thought.


text:
Q: To show $\mathrm{ker} f=\{0\}$ for linear mapping $f$. Let $V$ be a vector space over $F$ with basis $\{e_1,e_2,...e_n\}$.
Let $F$ be a linear mapping from $V$ to $V$ such that
$F(e_1) =e_2,...F(e_n)=e_1$.
Show that  $\mathrm{ker} f=\{0\}$. Also find $f^{-1}$.
I just know that $\mathrm{ker} f=\{0\}$ iff $f$ is 1-1.
So is it enough to show that basic definition for 1-1?
The inverse mapping will be defined as $f^{-1}(e_1) =e_n, f^{-1}(e_2)=e_1,...$
Am I right?

A: Using the rank-nullity theorem it is easy to prove that

if $V$ is a finite dimensional vector space and $f\colon V\to V$ is a linear map, then $f$ is injective (or 1-1) if and only if it is surjective

Prove it and verify your map is surjective.
The inverse function is correct.

A: Recall that for finite dimensional vector spaces you have that
$$
\dim V = \dim Im F + \dim \ker F,
$$
an by the definition of $F$ you know that
$$
Im F \in sp\{ e_1, e_2,..., e_n \},
$$
thus $\dim Im F= n$, therefore $\dim \ker F = 0$ so $\ker F = 0_v$.

A: If $x = x_1 e_1 + \cdots x_1 e_n \in \mathsf{ker}(f)$ then
$0 = f(x) = x_1f(e_1) + \cdots +x_{n-1}f(x_{n-1})+ x_nf(e_n) $
$=  x_1e_2 + \cdots + x_{n-1}e_{n} + x_ne_1 $
$= x_ne_1 + x_1 e_2 + \cdots + x_{n-1}e_n$
$\Longrightarrow \quad x_n =x_1 = \cdots =x_{n-1} = 0 \quad
\Longrightarrow \quad x=0$.
Because the domain and codomain of the injective transformation $f$ have equal dimension, $f$ is an isomorphism.
Also, I really like the advice by @Adren:
A function $f:A \to B$ between two sets is injective if and only if it has a left inverse with respect to composition; that is, if and only if there exists a function $g:B \to A$ such that $g \circ f = \mathrm{Id}_A$. Similarly, a function $f:A \to B$ is surjective if and only if has a right inverse, or rather there exists a function $g:B \to A$ such that $f \circ g = \mathrm{Id}_{B}$.
In your example, $A,B = V$, and the left/right inverse $g$ you should look at is $g = f \circ \stackrel{n-1}{\cdots}\circ f$, since
$g \circ f = f \circ g = f \circ \stackrel{n}{\cdots} \circ f = \mathrm{Id}_{V}$
Of course, you should show why the composite of $f$ with itself $n$ times gives you the identity map (think permutation of the basis elements).

A: Hints :

*

*if $f,g:X\to X$ are applications such that $f\circ g$ is injective (which means "one to one"), then $g$ is injective.

*id $E$ is a finite dimensional space and if $f\in\mathcal{L}(E)$ is injective or surjective, then $f$ is a bijection.

*Try to understand what can be said about $F^n$ (which means of course $F\circ\cdots\circ F)$


text:
Q: cpanel email & gmail reply I've created email accounts e.g. user1@domain.com, user2@domain.com in cpanel.  I then logged in to webmail for an account and clicked on 'add forwarder' and typed their Gmail account.
Now here is the problem, i assume i have set it up correctly for them to receive user1@domain.com emails in their Gmail account but how do they reply to emails or send emails through Gmail with user1@domain.com?
e.g.
-reply to an email from Gmail with the address user1@domain.com
-send an email from Gmail with the address user1@domain.com
How do i do this? The simpler the explanation the better as i have to tell this to colleagues who may not be computer savvy.

A: In Gmail if you select Settings/Accounts in the Send mail as section - click "Add another email address you own" and set up the user1@domain.com there.
Also alter the "reply to address" section.
Details here : multiple addresses

*

*This may only work for Google Apps for Business *

A: Since your colleagues aren't computer-savvy, it might be a good idea to point them to a tutorial first so they can create their own email accounts. As for your second question, you can change the "Reply to" address in GMail.


text:
Q: Reiniciar aplicación e C# estoy trabajando con sockets y en la aplicación cliente, cada que intento reiniciar mi aplicación
Application.ExitThread();
Application.Restart();

Me genera un error en esta linea, diciendo que la operación ha sido finalizada por el cliente, anteriormente funcionaba correctamente, lo único que hice fue generar el ejecutable de la aplicación y ahora no encuentro como solucionar :(


text:
Q: Entity Framework error updating iSeries record I am new to iSeries AS/400.  I've downloaded DB2Connect from IBM and I'm trying to get Entity Framework to work with it.
I have been successful in creating my EDMX file from the iSeries and I can read records.  However, whenever I try and save a change, I get the error message
ERROR [55019] [IBM][AS] SQL7008N  REXX variable \"INVENTORY \" contains inconsistent data.

From what I've read, this has to do with the table not being journalled.  I don't have control over whether it is or not.  I assume there is some kind of setting in the connection string that I need to set, but I can't figure out what.
My current EF connection string is (user and password removed)
<add name="LATHAM1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=IBM.Data.DB2;provider connection string="Database=LATHAM1;User ID=xxxx;Password=xxxx;Server=LATHDEV1:446;Persist Security Info=True;"" providerName="System.Data.EntityClient" />

If I attempt to update using just ADO.Net, I can update this just fine.
Any help would be appreciated.

A: I think you add CommitMode=0 as per Connection string keywords - Server properties
.
I usually just add the journaling.


text:
Q: Why does PHP treat classes and functions differently regarding namespaces and autoload? You can't alias a namespaced function to just the function name and you can't autoload functions. It would be nice if you could autoload functions and alias functions as just the function name.
So why is it like that?

A: The jury is still out on that one.
See Feature Request #63263
It's been open since 2012 so don't hold your breath.
It does make mention of a potential work around of defining or including functions on an abstract class declaration and them making it in so referencing
/My/Custom/Namespace/Abstract::LOAD_FUNCTIONS;

and allowing the class autoloader to include the abstract class which either also declare the functions or includes the declaration of the function as a means to include a group of functions. To me this fills hackey but it might work for your use case.


text:
Q: Android global array string
i write simple android application with two method:
i define a simple string array in this line:
public class breakactivity extends Activity {
    String[] id;
    protected void onCreate(Bundle savedInstanceState) {

and into this method:
public void fill(){
         id=new String[30];
         id[0]="x1";
         id[1]="x2";
}

and i want fetch the id array data into android onCreate method for example:
protected void onCreate(Bundle savedInstanceState) {
            string temp=id[0];
}

How can solve that?thanks for all.

A: You created a method called fill() now you have to call it in onCreate()
public class breakactivity extends Activity {
    String[] id;
    protected void onCreate(Bundle savedInstanceState) {
            fill();
            String temp = id[0];
    }
    public void fill(){
         id = new String[30];
         id[0] = "x1";
         id[1] = "x2";
    }
}


text:
Q: Hover over effect pushing image down Here is an image of the media div with the on hover X I have:

Here is an image of when you click on the div and upload a photo. As you can see it fits nicely inside the box.

Finally here is a div when I hover over the image to see the X.

As you can see the image got pushed down. My end result is instead to have it hover over the image and not affect the images placement
Here's my CSS:
.x {
  color:red;
  #width:50px;
  #height:50px;
  display:none;
  #left:50px;
}
.MediaPreview:hover > .x {
  display:block;
}
.MediaPreview {
    position: absolute;
    width: 128px;
    height: 72px;
    background-color: #e0e0e0;
    cursor: default;
}

Here is my HTML:

  Image or video, required

x

A: Try this?
.x {
  color:red;
  #width:50px;
  #height:50px;
  display:none;

  top: 10px;
  left: 10px;
  position: absolute;
  z-index: 1;

}
.MediaPreview:hover > .x {
  display:block;
}
.MediaPreview {
    position: absolute;
    width: 128px;
    height: 72px;
    background-color: #e0e0e0;
    cursor: default;
}

A: You need to apply position:absolute to .x, not .MediaPreview. Try this:
.x {
  color:red;
  display:none;
  position: absolute;
  top: 0;
  left: 0;
}
.MediaPreview:hover > .x {
  display:block;
}
.MediaPreview {
    position: relative;
    width: 128px;
    height: 72px;
    background-color: #e0e0e0;
    cursor: default;
}

A: This is how to get the job done. Using pure css

X

DEMO

A: you can try this:
https://jsfiddle.net/maky/gqn1nrxj/
.x {
  color:red;
  display:none;
  position: absolute;
  top: 0;
  left: 0;
}
.MediaPreview:hover > .x {
  display:block;
}
.MediaPreview {
    position: relative;
    padding:10px;
    width: 200px;
    height: 200px;
    background-color: #e0e0e0;
    cursor: default;
}


text:
Q: Applet: Unable to read image file I have some problems calling ImageIO.read to read a file. This applet is embedded onto a HTML page, and I am using Javascript to return a string ("second"). Before calling ImageIO.read, the string "second" could be displayed. However after calling ImageIO.read, "second" could not be displayed. I want "second" to be returned back to the user after an Image file has been read.
Greatly appreciate any help. Thanks.
HTML
<html>
<body>
    <script language = "JavaScript">
    function bing()
    {
        alert(document.xyz2.Test());
    }
    </script>

    <input type="button" value="Value" onclick="bing()"/>
    <applet name="xyz2" code="xyz2.class" width=100 height=100>
    </applet>
</body>
</html>

Applet Codes
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JApplet;

public class xyz2 extends JApplet {
   public String s="first";
   public BufferedImage bf;
   public void init(){

   }
   public String Test() throws IOException{
       bf = ImageIO.read(new File("c:\\rose.jpg"));
       s = "second";
       return s;

   }

}

A: You are probably getting an exception when reading the image from the file system. The applet needs to be signed to be able to touch those files.
Some choices:

*

*Sign your applet

*Read the image from the webpage you are accessing the applet from

*Embed the image in the applets resources


text:
Q: Plotting multiple xy pairs in Gnuplot from file I have a data series that I'm trying to plot in Gnuplot of the format:
x1, y1, x2, y2 ... xn, yn

Where every two adjacent columns represent an xy pair. I'm looking for a way to plot each of these xy pairs as separate lines using a single (concise-ish) command in Gnuplot, rather than trying a command like this:
plot "file" u 1:2 w l, "file" u 3:4 w l

...and so on.

A: You can use a for loop in (relatively recent) gnuplot:
plot for [i=1:4] "file" u (column(2*i-1)):(column(2*i)) w lp

will plot four curves, each based on one of the first four pairs of each line in the file.


text:
Q: Getting "A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll" when updating with the code My OCCUPIED-column is Boolean and I would like the room status to change, so that it wont appear on the list of free rooms.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    dataFile = "C:\Users\MAI KUDA\Documents\Visual Studio 2008\Projects\HOTEL MANAGMENT\HOTEL MANAGMENT\bin\Debug\MY HOTEL.accdb"
    connString = provider & dataFile
    myConnection.ConnectionString = connString
    myConnection.Open()
    Dim str As String
    str = "update [ROOMS] set [OCCUPIED]=?status, [occupied by]=?name Where [ROOM] = ?room  "
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    cmd.Parameters.AddWithValue("?status", True)
    cmd.Parameters.AddWithValue("?name", Form3.NAMETextBox.Text And Form3.SURNAMETextBox.Text)
    cmd.Parameters.AddWithValue("?room", ROOMTextBox.Text)

    Try
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        myConnection.Close()
        MsgBox("done")
    Catch ex As Exception
        MsgBox("error")
    End Try

    Form3.ROOMTextBox.Text = ROOMTextBox.Text
    Me.Validate()
    Me.ROOMSBindingSource.EndEdit()
    Me.TableAdapterManager.UpdateAll(Me.MY_HOTELDataSet)
    Me.Hide()
    Form3.Show()
End Sub

A: A couple of things.

*

*The Ado.NET OleDB provider, used for ms access, uses ? as parameter place holders. They are not named so drop the name entirely and only use the question mark. Be sure the order of the parameters matches the order they appear in the statement.

*When concatenating strings in vb use & and not the word AND which is for combining booleans. I added a space between the name parts, remove it if this is not your intention.

*Not applicable to the error but I strongly suggest using using blocks to ensure your connections are closed / disposed.

Updated relevant code:
str = "update [ROOMS] set [OCCUPIED] = ?, [occupied by]= ? Where [ROOM] = ?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
' here the name no longer matters so keep it or drop it up to you as long as the order matches the order in the statement.
cmd.Parameters.AddWithValue("?status", True)
cmd.Parameters.AddWithValue("?name", Form3.NAMETextBox.Text  & " " & Form3.SURNAMETextBox.Text)
cmd.Parameters.AddWithValue("?room", ROOMTextBox.Text)


text:
Q: Embedded Python in C++ socket programming Can i not send and receive UDP packets in a single python embedded C++ program in which send and receive scripts run in different threads?
I get an unhandled exception when the exe file is run. When one of the send or receive command is commented out i.e either PyRun_SimpleString(sendPy) or PyRun_SimpleString(recPy) then the program works all fine.
What is the mistake here?
The code is given below:
DWORD WINAPI sendPack(LPVOID iValue)
{

while(1){

   const char* sendPy = "UDPSockSend.sendto('10707',('10.107.35.167',21567))";
   PyRun_SimpleString(sendPy);

    }
return 0;
}

DWORD WINAPI receive(LPVOID iValue){

while(1){

    Py_Initialize();
    recPy = "data,addr = UDPSockRcv.recvfrom(99000)";
    PyRun_SimpleString(recPy);

}

return 0;

}

int threads()
{

    HANDLE sendPackThread, receiveThread;
    DWORD dwGenericThread;

    char lszThreadParam[4];

    receiveThread =
    CreateThread(NULL,0,receive,&lszThreadParam,0,&dwGenericThread);
    if(receiveThread == NULL){
        DWORD dwError = GetLastError();
        return 0;
    }

    sendPackThread =
    CreateThread(NULL,0,sendPack,&lszThreadParam,0,&dwGenericThread);
        if(sendPackThread == NULL){
        DWORD dwError = GetLastError();
        std::cout<<"SCM:Error in Creating send sample thread"<<dwError<<"\n" ;
        return 0;
        }

    return 1;
}

int main(int argc, char* argv[])
{

    using namespace std;
    Py_Initialize();

    const char * initPy = "import socket;
    UDPSockSend = socket.socket(socket.AF_INET,socket.SOCK_DGRAM);
    UDPSockRcv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM);
    listen_addr = ('',2000);UDPSockRcv.bind(listen_addr)";
    PyRun_SimpleString(initPy);

    int thd = threads();

    system("pause");
    return 0;

}

Thanks in advance

A: I think the problem here is, that python is not thread safe. You can't just access the interpreter from two threads and expect that it works. See http://docs.python.org/2/c-api/init.html#non-python-created-threads for more details. Essentially you have to acquire and release the GIL (The global interpreter lock).
This thing is kind of a mutex that ensures, that only one Thread accesses python objects at a time. The GIL is also the reason why python multithread performance is generally bad.