Address coming from Geocoder is in English

Question: I want to do an application which gets the current address; country name, city name and district name. And then I have 3 spinner which are having all country names, city names and district names in Turkish.
When I get the address using GPS and Geocoder, I want to match them with the names in my spinners.
The problem is the address coming from geocoder is in English. And so, it does not match with my countries in my spinner. So I cannot select true country with programatically.
Here is my related code:
//In here I add countries coming from web service into countries array.
for(int i=0;i<responseInfo.size();i++) {
    String name = responseInfo.get(i).getName();
    countries.add(name);
    //If country name is equals to country name coming from gps
    //then I hold it in selectedCountry variable.
    //But "Turkey" != "Türkiye" so this if block does not work
    if(name.equalsIgnoreCase(foundAddress.getCountryName()))
    {
        selectedCountryId = (String)responseInfo.get(i).getId();
        selectedCountry = responseInfo.get(i);

    }
}

//In this method, when I get country name from the item in addresses array
//it returns in English
public List<Address> findAddressFromLatLng(double latitude, double longitude)
{
    Geocoder geocoder;
    List<Address> addresses = null;
    geocoder = new Geocoder(this, Locale.getDefault());
    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);

    } catch (IOException e) {
        e.printStackTrace();
    }

    if ((addresses != null) && (addresses.size() != 0)) {
        return addresses;
    }
    return null;
}

In another device, I have no problem. Country name coming from geocoder is in Turkish (which means Geocoder have Turkish names also). Probably it is because of device language.
I tried to change this line but I can't find Turkish as locale:
geocoder = new Geocoder(this, Locale.getDefault());

Thanks in advance.
Answer: Docs for Geocoder suggest that setting a Locale is exactly what you need. There's no predefined Locale for Turkish, but you can easily define one:
Locale locale = new Locale("tr", "TR");

Comment: Thanks! That is exactly what I need  =)


Cannot find PhotogrammetrySession in scope

Question: Trying to compile the Photogrammetry example from Apple (https://developer.apple.com/documentation/realitykit/creating_a_photogrammetry_command-line_app#overview).
It fails as it does not find the PhotogrammetrySession class. I am on XCode 13 and MacOs 12 Monterey. I have successfully compiled and used the same example with XCode 13 beta and Monterey beta.
Anyone has a clue?
EDIT: adding the part of the code that generates the error (should be obvious but here it is)
import RealityKit

let inputFolderUrl = URL(fileURLWithPath: "/tmp/MyInputImages/")
guard let session = try PhotogrammetrySession(input: inputFolderUrl) else {
    return
    }

The class is part of the os and I cannot debug it, its just not there after I import RealityKit. The resulting compile error is:
Cannot find type 'PhotogrammetrySession' in scope.

Now this comes straight from Apple documentation, so I assume I am doing something stupid or I missed some release notes somewhere. I looked and I did not find anything, so I am asking for help here.
Comment: I've been experiencing the same issue as well. Will post back here if I figure it out
Comment: Found the reason, they removed the MacOS 12 SDK in the XCode 13 release. Update Xcode and it will work again
Comment: Were you able to get it to work? I updated to the xcode beta and macos 12 beta and still same error
Comment: nvm I downloaded the sample app and it successfully built!
Answer: Had the same issue, but realized i wasn't targeting macOS and that fixed it.
If you're not check if this might help, otherwise please share.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Installing libgirepository-1.0-1:i386 leads to strangeness

Question: This apt-get exchange leaves me befuddled (on a 64-bit CPU):
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:        14.04
Codename:       trusty

The follwoing output arise when running the command:
$ sudo apt-get install libgirepository-1.0-1:i386

Following packages have been installed and are no longer necessary:
  app-install-data-partner cdrdao fonts-lao fonts-thai-tlwg fonts-tlwg-garuda
  fonts-tlwg-kinnari fonts-tlwg-loma fonts-tlwg-mono fonts-tlwg-norasi
  fonts-tlwg-purisa fonts-tlwg-sawasdee fonts-tlwg-typewriter
  fonts-tlwg-typist fonts-tlwg-typo fonts-tlwg-umpush fonts-tlwg-waree
  foomatic-db-compressed-ppds gir1.2-dbusmenu-glib-0.4
  gir1.2-javascriptcoregtk-3.0 gnome-icon-theme gnome-icon-theme-symbolic
  gstreamer1.0-clutter humanity-icon-theme indicator-application kdesudo
  kubuntu-notification-helper libao-common libao4 libappindicator1
  libappindicator3-1 libcairo-script-interpreter2 libcairo2-dev
  libclutter-1.0-0 libclutter-1.0-common libclutter-gst-2.0-0
  libclutter-gtk-1.0-0 libcogl-common libcogl-pango15 libcogl15
  libdbusmenu-gtk3-4 libfontconfig1-dev libfreetype6-dev libgmime-2.6-0
  libharfbuzz-dev libharfbuzz-gobject0 libindicator3-7 libindicator7
  libjson-glib-1.0-0 libjson-glib-1.0-common libnautilus-extension1a
  libpeas-common libperl4-corelibs-perl libpixman-1-dev libpng12-dev
  libtotem-plparser18 libxcb-shm0-dev libxcomposite-dev libxft-dev
  libzeitgeist-2.0-0 printer-driver-min12xxw python-defer python3-pykde4
  syslinux-legacy ubuntu-extras-keyring ubuntu-release-upgrader-qt
  x11proto-composite-dev
  ...
Following packages will be REMOVED:
  aptdaemon apturl-kde gir1.2-atk-1.0 gir1.2-dee-1.0 gir1.2-freedesktop
  gir1.2-gdkpixbuf-2.0 gir1.2-glib-2.0 gir1.2-gst-plugins-base-0.10
  gir1.2-gstreamer-0.10 gir1.2-gtk-2.0 gir1.2-gtk-3.0 gir1.2-pango-1.0
  gir1.2-peas-1.0 gir1.2-soup-2.4 gir1.2-totem-1.0 gir1.2-totem-plparser-1.0
  gir1.2-udisks-2.0 gir1.2-unity-5.0 gir1.2-vte-2.90 gir1.2-webkit-3.0
  kubuntu-desktop libatk1.0-dev libgdk-pixbuf2.0-dev libgirepository-1.0-1
  libgtk2.0-dev libgtkglext1-dev libmuonprivate2 libpango1.0-dev
  libpangox-1.0-dev libpeas-1.0-0 libtotem0 muon muon-discover muon-notifier
  muon-updater python-appindicator python-aptdaemon
  python-aptdaemon.gtk3widgets python-gi python-gi-cairo python-gobject
  python-gst0.10 python-indicate python3-aptdaemon
  python3-aptdaemon.gtk3widgets python3-gi software-properties-common
  software-properties-gtk software-properties-kde totem totem-mozilla
  totem-plugins ubuntu-release-upgrader-gtk update-manager update-notifier
  usb-creator-common
Following NEW packages will be installed:
  libgirepository-1.0-1:i386

My questions are two.

Why does apt-get think it should remove so many packages? I didn't
tell it to remove totem at all.
The next time a really strange apt-get situation like the above arises, how can I figure out for myself why apt-get seem to act so weirdly?
Answer: First you should know this is not a weired action, this is totally right and you some how asking for this action!!
So why this happens?
You want to install libgirepository-1.0-1:i386 , but you already have this
libgirepository-1.0-1 64 bit version, so here the system is asking you to replace the 64bit with this 32bit.
This replace has some consequences, if you choose to replace this means the system will delete libgirepository-1.0-1 and install the 32bit instead, so as this lib package will deleted then the system will delete other applications which depend on it, since those applications will be no longer available if this library is removed.
For example why totem will be removed, let's see the totem dependencies
$ apt-cache rdepends totem
totem
Reverse Depends:
  totem:i386
  totem:i386
  libtotem0:i386
  libtotem-dev:i386
  gnome-settings-daemon:i386
  totem-plugins-extra
  ubuntu-desktop
  totem-plugins
  totem-mozilla
  totem-dbg
  totem
 |nautilus
  libtotem0
  libtotem-dev
  gnome-settings-daemon
  totem:i386
  totem:i386
  libtotem0:i386
  libtotem-dev:i386
  gnome-settings-daemon:i386
  ubuntustudio-desktop
  ubuntu-sugar-remix
 |tunapie
  totem-plugins-extra
  totem-plugins-dvb-daemon
  totem-plugin-arte
  totem-plugin-arte
  streamtuner2
  remuco-totem
  gnome-core
  ezgo-multimedia
  bombono-dvd
  ubuntu-desktop
  totem-plugins
  totem-mozilla
  totem-dbg
  totem
 |nautilus
  libtotem0
  libtotem-dev
  gnome-settings-daemon

As you see above totem depends on libtotem0 and many other packages but let's take this package as example, now if you check the dependencies of the libgirepository-1.0-1 will show you also libtotem0 and many others, so to explain the example, if you delete the libgirepository-1.0-1 and want to install the 32 bit then you'll need to remove the libtotem0 to install its 32 bit also to be compatible with libgirepository-1.0-1 32bit and though you are going to remove totem(Even you don't mean it).
Hope things become clear now
Comment: So Ubuntu doesn't support parallel installation of the same libraries for different platforms?  E.g I'm not allowed have *both* the 32bit build of `libglib-2.0.so` and the 64bit one installed at the same time?
Comment: did you add multiarch support ?  if not  run the command `sudo dpkg --add-architecture i386` then try again
Comment: I did and it doesn't help. I think I have had multiarch enabled for a long time. F.e I have both libreadline-dev and libreadline-dev:i386 installed.
Comment: some packages that have same files may not installed together so you should choose one of them
Comment: Read this answer http://askubuntu.com/questions/254754/how-can-i-install-both-32-and-64-bit-versions-of-the-same-dev-package
Comment: I checked http://packages.ubuntu.com/trusty/i386/libgirepository-1.0-1/filelist and http://packages.ubuntu.com/trusty/amd64/libgirepository-1.0-1/filelist and indeed, the packages seem to be sharing file paths.  But libreadline6 also share file paths: http://packages.ubuntu.com/trusty/i386/libreadline6/filelist and http://packages.ubuntu.com/trusty/amd64/libreadline6/filelist


Optimization problem on 2-simplex

Question: I have the following simple formulated optimization problem:
$$
f = \sqrt{ab} + \sqrt{bc} \to \max \\
a + b+ c = 1
$$
In other words I want to maximize $f$ on simplex. How can I evaluate this?
Comment: Lagrange multipliers seem to work nicely.
Comment: Actually, that's not even necessary.  Note that symmetry tells you that $a=c$ at the extreme, so you can get down to a single variable.
Comment: Nothing in the problem distinguishes $a$ from $c$, so we'll have $a=c$ at the extreme.  Should say, if you aren't comfortable reasoning that way (and it can lead one astray at times), use Lagrange.  It's easy and the desired symmetry drops out of that instantly.
Comment: @lulu thank you, but what do you mean by "symmetry tells" ? Do you mean that on the optimum $a = c$
Comment: @lulu thank you again
Answer: By the AM-GM inequality
$$\sqrt{ab}+\sqrt{bc}=\frac{1}{\sqrt{2}}\left(\sqrt{(2a)b}+\sqrt{b(2c)}\right)\leq\frac{1}{\sqrt{2}}\left(\frac{2a+b}{2}+\frac{b+2c}{2}\right)=\frac{1}{\sqrt{2}}.$$
Equality holds when $2a=b=2c$ and then $(a,b,c)=(\frac14,\frac12,\frac14)$.

Optimization problem on 2-simplex


metric induced norm or norm induced metric

Question: I am always confused between whether metric induces norm or norm induces metric. Can someone clarify this relation a bit for me? Was there any intuition on which direction being true?
Comment: Are you familiar with the definition of [_induce_](http://dictionary.reference.com/browse/induce)?
Comment: A induces B if B can be obtained from A. We can obtain a metric from a norm. We usually can't obtain a norm from a metric.
Comment: Also see [this](http://math.stackexchange.com/questions/423508/examples-of-metric-spaces-which-are-not-normed-linear-spaces)
Answer: In a vector space, a norm can induce a metric.  For example, suppose that $u,v\in\mathbb{R}^n$ and let $||\cdot||$ be the Euclidean norm.  Then one can induce a metric $d(u,v):\mathbb{R}^n\times\mathbb{R}^n\rightarrow\mathbb{R}$ given by
$$
d(u,v)=||u-v||.
$$


How does the Soul Siphon perk work?

Question: The rightmost line of perks in the Enchanting constellation terminates with a perk called Soul Siphon, which causes your deathblows on creatures (but NOT people) to trap 5% of the victim. What does this mean? Does this require you to have an unused soul gem in inventory for it to work, and how does it interact with a soul trap weapon?
Comment: I was also wondering about the soul trap enchantment overlap. It would imply that either you catch 105% of the soul, or only get 95% in the gem...
Answer:
What does this mean?

It means, you can take out your completely empty Sword of Flaming Flames, kill a bear with it, and now it's got 5% of the bear's soul for the next fight.  (note: works for partially filled magic items too)

Does this require you to have an unused soul gem in inventory for it to work

Nope.

and how does it interact with a soul trap weapon?

The soul trap weapon casts soul trap on the creature.
The creature dies.
5% of the creature's soul is stored to the weapon.
100% of the creature's soul is stored to an empty gem.

Yes, that is 105% of the soul, which is awesome.
Comment: I think the only disadvantage is that it doesn't increase the enchanting skill
Answer: That description seems off, or at least misleading. The full perk description is:

Death blows to creatures, but not people, trap 5% of the victim's soul, recharging the weapon.

The Soul Siphon perk isn't meant to trap souls in the normal sense (like you would with Soul Trap), it's meant to be an automatic recharge for your enchanted weapon.
Skizzlefrits mentions in the comments how it works:

It would recharge the weapon for 5% of the amount that a soul gem filled with that soul would recharge. So this is a good perk to have at higher levels when you are fighting enemies that would fill grand soul gems.
Comment: that calculation is slightly off... it doesn't recharge 5% of the weapons charge. It would recharge the weapon for 5% of the amount that a soulgem filled with that soul would recharge. so this is a good perk to have at higher levels when you are fighting enemies that would fill grand soul gems
Comment: Realistically: any weapon with 20 or more charges is self sustaining against enemies that provide souls equivalent to the one used to craft the weapon. Which is kind of amazing.
Comment: ...provided that you one-shot them every time. If not, you're using more than one charge to kill them, but only getting one back when they die.
Comment: @Skizzlefrits Ah, interesting: that makes sense. The description could be a lot clearer.

How does the Soul Siphon perk work?


ReactJS: Show a list in a select inside a form

Question: I'm trying to show a list inside a form, but I don't understand why it isn't showed.
useEffect(() => {
    props.getRealms(); // I make call to api
    localStorage.setItem('realm', JSON.stringify(realm));
  }, [realm]);

  const { realmsList, loadingRealms } = props;
  console.log('realmsList.length ', realmsList.length);

  return (

      <AvForm model={{}} onSubmit={saveEntity}>
        {realmsList.length > 0 ? (

            <AvGroup>
              Realm
              <AvInput id="personaInfo-realm" data-cy="realm" type="select" name="realm">
                <option value="" key="0">
                  Choose Realm
                </option>
                {realmsList.map(entity => {
                  console.log('entity ', entity),
                    (
                      <option key={entity.id} value={entity.id}>
                        {entity.name}
                      </option>
                    );
                })}
              </AvInput>
            </AvGroup>
            <Button color="primary" id="save-entity" data-cy="entityCreateSaveButton" type="submit" style={{ marginLeft: 10 }}>
              <FontAwesomeIcon icon="save" /> Save
            </Button>

        ) : (

        )}
      </AvForm>

  );
};

const mapStateToProps = ({ sceRealm }: IRootState) => (
  {
    realmsList: sceRealm.entities,
    loadingRealms: sceRealm.loading,
  }
);

const mapDispatchToProps = {
  getRealms,
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(ScePersonaInfoUpdate);

In my return I wrote this condition: realmsList.length > 0, but the only thing that I can see it the write "Choose Realm" and not the realm list. The console log inside the map, show the entities of the list.
How can I fix it?
Thank you
Answer: You don't have a return inside your map so nothing is actually happening with your map
{realmsList.map(entity => {
    console.log('entity ', entity),
     return (
         <option key={entity.id} value={entity.id}>
            {entity.name}
         </option>
    );
 })}

Answer: You didn't return the options
....
{
  realmsList.map((entity) => {
    console.log("entity ", entity);
    return (
      <option key={entity.id} value={entity.id}>
        {entity.name}
      </option>
    );
  });
}


how to allow only arabic,numeric and special chars in textbox using jquery or javascript?

Question:
Possible Duplicate:
Jquery filter text boxes (Preventing user from inserting certain characters)

I want to allow only arabic ,numeric and special characters to be typed in my web page. i want to apply this thing using jquery or javascript. How can i do? Please help me.Thanks in advance.
Answer: Use the jquery validate plugin.  Build a rule that limits the characters to the one you want (alternately, there may be one already), apply it to a class, and apply that class to all of your input fields.  Note that this won't prevent people who intend you ill from submitting other things - jquery validate sits on top of the form, and it's possible to submit stuff underneath it with a bit of hackery - but it will make sure that everyone who's trying to do the right thing is guided to the proper path.


Checking if button is pressed to segue correct data

Question: Hi this may be a simple question and I apologize if it is on here already, I searched for what I could but couldn't find an answer that tailors to my specific situation.
Here is the issue. I am currently creating a text adventure to practice some iOS development using swift in Xcode 6 and in this case I have a text view in my view controller that can scroll to the bottom of itself and 2 buttons at the bottom of the screen. The point being that if you hit one button it segues you to a different scenario and also alters some general character stats from a class UserCharacter I defined in my project altering some basic data and vice versa for the other button.
Thing is in my segue I need to check which button the user pressed so I know which data to segue but can't quite figure out how to do that.
Here is what I have so far, (I have already passed my data once previously but didn't need to make a choice so it was fairly simple)
<code>class RouteZeroViewController: UIViewController {

var character : UserCharacter?

@IBAction func choiceOneButton(sender: AnyObject) {
    character?.strength += 3
    character?.intelligence -= 2
}
@IBAction func choiceTwoButton(sender: AnyObject) {
    character?.agility += 2
    character?.intelligence += 2
    character?.courage -= 2
}
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    // set initial textView load at the top instead of middle/bottom
    self.textView.scrollRangeToVisible(0)
}

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

// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    // Get the new view controller using [segue destinationViewController].
    // check for button one push ????????
    var thirdSceneA = segue.destinationViewController as RouteOneAViewController
    thirdSceneA.character = character

    // check for button two push ????????
    var thirdSceneB = segue.destinationViewController as RouteOneBViewController
    thirdSceneB.character = character
    }

}
</code>
Any help would be appreciated. Thank You..
Answer: You need to add segue from view controller to viewcontroller refer this link : IOS7, Segue and storyboards - How to create without a button?
set tag property to each button i.e. 1 and 2
on button click pass button
<code>   @IBAction func choiceOneButton(sender: AnyObject)
{
character?.strength += 3
character?.intelligence -= 2
 self.performSegueWithIdentifier("identifer", sender: sender)
}

 @IBAction func choiceTwoButton(sender: AnyObject)
{
character?.agility += 2
character?.intelligence += 2
character?.courage -= 2
self.performSegueWithIdentifier("identifer", sender: sender)
 }
</code>
In prepare segue method check
<code> override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?)
{
   var btn:UIButton=sender as UIButton

        if btn.tag==1
        {
            // First button clicked
        }

        if btn.tag==2
        {
            // Second button clicked
        }

}
</code>
Comment: Ah ok. I think that worked out for me, I'm having a hard time seeing the variables as I'm in debug mode but it seemed to allow me to move on to the next scene.

One question though, why do we have to have the line, self.performSegueWithIdentifier("identifier", sender: sender) if we already specified on the storyboard where each button will take us?


Can my free Android app be upgraded to a paid version via in-app purchase AND paid store version?

Question: I'm looking into monetizing my first app with a free and a paid version. It seems that the simplest approach would be to use an in-app purchase to unlock extra features. However, I'd also like the customer to have the option to purchase the full version outright on the Play Store (more visibility that way). I could publish a "pro key" app as an upgrade key, but then they'd have to install 2 packages and it seems like a hassle. On the other hand, I don't want to have to support two independently complete packages (one free, one paid).
So I'm not sure what approach to take. I want to let users upgrade from within the app because that would be simplest, but I also want a the customer to be able to buy and install the paid version straight from the store. Thoughts?
Comment: I personally have 2 different apps. The free one, and the pro key version with more features. Just make it evident to the person who is buying the pro version that it is the pro version like changing the Icon around a little, that's what I have done and it's working perfectly :)
Comment: @Jack, is it not troublesome to maintain 2 apps? Do they have different workspaces?
Comment: Yes it is, because of this, I would not recommend it.
Comment: This question appears to be off-topic because it is about app store policies, not programming.
Answer: No. Free and paid apps are handled completely differently on the market.
Answer: I see three solutions.

Add In-app purchase
Add new app "Your app name pro unlocker"
Add new pro version of you app

I think that the first one is the most reliable and easy to achieve. It is harder to crack by pirates too. Pirates can upload your app to their sited but when user will download it he will get normal free version. Of course anything can be hacked ;-) but... it is better than 3rd option (see below).
Second one - in you main app you need to check if "pro unlocker" is installed, maybe you will need to check if certificates are the same and run, custom implemented, android service in this to check if use is allowed to use pro version. It is quite ok and beacuse you will use a quite lot of custom coding it should be safe.
Third - using Grandle you can simply create second version of your app, during building Grandle will create pro/free version automatically. However pro versions which are using Google Licensing are easy to crack by pirates so...
To sum up - you have 3 three solutions. I think that the first one is good enough and it is not requiring too much code or time for maintaining. I hope that this will help you ;-)
Cheers
Comment: I think you sum it up pretty well. Yes, the in-app purchase seems like the way to go. It's simple and logical. If I find I really want the extra visibility of having two versions on the store, I'll look into that. I doubt anyone will want to hack my little app, but that's a good point. Thanks!


iOS: Crash after writing socket

Question: In my application, I am sending screenshot of the current view programmatically and sending to a socket server program at every 5 seconds interval.
Socket program is running in Eclipse. I checked the code earlier and able to send screenshot of the image to the socket without any issues.
After that, as per my actual requirement, I added a tab bar controller (5 tabs) and used navigation controller for the first tab selection. As per my code below, the first tab bar item is "MyHomeViewController".
In the "MyHomeViewController" i have a button action called -(IBAction)goAhead:(id)sender. Clicking on this will take to another "HomeViewController".
In this "HomeViewController", I connect socket and if the socket connection is success, under "NSStreamEventHasSpaceAvailable" delegate method, i call a function called "[self coShareScreen];" to take to sending screenshot images of the current view (whatever view controller is present) and sending to that socket server program.
I use a "CobrowseSingletonSocket" class, where i have socket related variables and sending screenshot programmatically are handled in this function "-(void) takeScreenshotSend :(NSString *) endOrCancelString".
My issue is, socket is getting connected successfully now. It should send screenshot of the image programmatically wherever the view I'm currently in.
As expected, Its start sending the screenshot of the view programmatically to socket server successfully at every 5 seconds interval.
But,
As its a navigation controller based view,  If i coming back to the first view manually, which is "MyHomeViewController". It tries to send that screen also, but it crashes after immediately write socket is done.
It is crashing immediately after writing here-> "int num = [self.outputStream write:[data bytes] maxLength:([data length])];"
This is crash is happening only if i come back in navigation controller manually. If i stay in "HomeViewController" itself after socket connection, it keeps sending screenshot programmatically a t every 5 seconds interval to socket server without any issues.
I don't understand what could be the reason here? Please someone advise me, as i'm unable to fix this for long time. Please also let me know if i need to paste any more code here.
<code> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];

    UITabBarController *tabbarCtrler = [[UITabBarController alloc]init];

    MyHomeViewController *myHomeCtrler = [[MyHomeViewController alloc] initWithNibName:@"MyHomeViewController" bundle:NULL];
    [myHomeCtrler.tabBarItem setTitle:@"My Home"];

    ProductsViewController *prodViewCtrler = [[ProductsViewController alloc] initWithNibName:@"ProductsViewController" bundle:NULL];
    [prodViewCtrler.tabBarItem setTitle:@"Products"];

    InboxViewController *inboxViewCtrler = [[InboxViewController alloc] initWithNibName:@"InboxViewController" bundle:NULL];
    [inboxViewCtrler.tabBarItem setTitle:@"Inbox"];

    ContactUSViewController *contactViewCtrler = [[ContactUSViewController alloc] initWithNibName:@"ContactUSViewController" bundle:NULL];
    [contactViewCtrler.tabBarItem setTitle:@"Contact Us"];

    VoiceViewController *voiceViewCtrler = [[VoiceViewController alloc] initWithNibName:@"VoiceViewController" bundle:NULL];
    [voiceViewCtrler.tabBarItem setTitle:@"Voice"];

    UINavigationController *navigationcontroller = [[UINavigationController alloc] initWithRootViewController:myHomeCtrler];
    navigationcontroller.title = @"My News;

    [navigationcontroller.navigationBar setBackgroundImage:[UIImage imageNamed:@"SettingsTitlebar.png"] forBarMetrics:UIBarMetricsDefault];

    [navigationcontroller setNavigationBarHidden:YES];

    //create an array of all view controllers that will represent the tab at the bottom
    NSArray *arrayViewControllers = [[NSArray alloc] initWithObjects:
                                     navigationcontroller, prodViewCtrler, inboxViewCtrler, contactViewCtrler, voiceViewCtrler, nil];

    [tabbarCtrler setViewControllers:arrayViewControllers];

    [self.window makeKeyAndVisible];

    [self.window setRootViewController:tabbarCtrler];

    return YES;
}
</code>
and
<code>#import "MyHomeViewController.h"
#import "SettingsViewController.h"

@interface MyHomeViewController ()

@end

@implementation MyHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)goAhead:(id)sender
{
    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [self.navigationController pushViewController:setttingsViewController animated:YES];
}
</code>
and
<code>//  HomeViewController.m
//
//

#import "HomeViewController.h"
#import "AppDelegate.h"
#import "CobrowseSingletonSocket.h"

#import <QuartzCore/QuartzCore.h>
#import <notify.h>

@interface HomeViewController ()

@end

@implementation HomeViewController
@synthesize authTexField;
@synthesize sessionID;
@synthesize sentPing;
@synthesize bScreenOff;
@synthesize responseAlertView;
@synthesize portFld;
@synthesize ipFld;
@synthesize shareScreenTimer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
    authTexField.delegate = self;
    responseAlertView.delegate = self;
    ipFld.delegate = self;
    portFld.delegate = self;
    bScreenOff = NO;
    cobrowseSingletonIns = [CobrowseSingletonSocket sharedCobrowseSocketInstance];
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)connectShare:(id)sender
{
    // Connect socket freshly here

    [self initSocketConnection];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

- (IBAction)backAction:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark Socket Connection

- (void)initSocketConnection
{
    NSString * ipAddrStr = ipFld.text;
    NSString * portStr = portFld.text;

        NSLog(@"IPAddress: %@ ; Port: %@", ipAddrStr, portStr);

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;

        NSString *ipaddress = ipAddrStr;

        ipaddress = [ipaddress stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

        NSLog(@"Retrieved socket ip: %@", cobrowseSingletonIns.socketIPAddress);

        CFStreamCreatePairWithSocketToHost(NULL, (__bridge  CFStringRef)ipaddress, 8081, &readStream, &writeStream);

        cobrowseSingletonIns.inputStream = (__bridge_transfer NSInputStream *)readStream;
        cobrowseSingletonIns.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [cobrowseSingletonIns.inputStream setDelegate:self];
        [cobrowseSingletonIns.outputStream setDelegate:self];

        [cobrowseSingletonIns.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [cobrowseSingletonIns.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [cobrowseSingletonIns.inputStream open];
        [cobrowseSingletonIns.outputStream open];

}

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    NSString *io;

    if (theStream == cobrowseSingletonIns.inputStream) io = @">>";
    else io = @"<<";

    NSLog(@"Stream space : %d",[cobrowseSingletonIns.outputStream hasSpaceAvailable]);

    NSString *event;
    switch (streamEvent)
    {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            //statusText.text =  @"Can not connect to the host!";
            NSLog(@"NSStreamEventNone - Can not connect to the host");
            break;

        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            //pingButton.hidden = NO;
            //statusText.text = @"Connected";
            NSLog(@"Connected");
            break;

        case NSStreamEventHasBytesAvailable:

            event = @"NSStreamEventHasBytesAvailable";
            NSLog(@"NSStreamEventHasBytesAvailable called");

            if (theStream == cobrowseSingletonIns.inputStream)
            {
                //read data
                //uint8_t buffer[1024];
                uint8_t buffer[2];
                NSMutableData *data=[[NSMutableData alloc] init];

                int len;
                while ([cobrowseSingletonIns.inputStream hasBytesAvailable])
                {
                    len = [cobrowseSingletonIns.inputStream read:buffer maxLength:sizeof(buffer)];

                    if(len)
                    {
                        [data appendBytes:&buffer length:len];
                    }
                    else
                    {
                        NSLog(@"no buffer!");
                    }

                }
                NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                responseStr = [responseStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

                //do something with data
                NSLog(@"Server said this-> %@", responseStr);
                NSString *successResponse;
                responseAlertView = [[UIAlertView alloc] init];
                if ( [responseStr isEqualToString:@"SUCCESS"])
                {
                    successResponse = @"Successfully connected! Click OK to starts screen sharing!";
                    responseAlertView.tag = 3;
                    [responseAlertView addButtonWithTitle:@"OK"];
                    [responseAlertView addButtonWithTitle:@"CANCEL"];
                }
                else
                {
                    successResponse = @"There seems to be problem in connecting..Try connecting it again with proper Random Auth ID!";
                    responseAlertView.tag = 4;
                    [responseAlertView addButtonWithTitle:@"OK"];
                }
                responseAlertView.delegate = self;
                [responseAlertView setTitle:@"Cobrowsing"];
                [responseAlertView setMessage:successResponse];

                [responseAlertView show];

            }
            break;

        case NSStreamEventHasSpaceAvailable:
        {
            event = @"NSStreamEventHasSpaceAvailable";

            NSLog(@"space : %d", [cobrowseSingletonIns.outputStream hasSpaceAvailable]);

            if ( !cobrowseSingletonIns.bConnectionEstablished )
            {
                NSLog(@"NSStreamEventHasSpaceAvailable - Connection established, sharing is going to be established!");

                if ( theStream == cobrowseSingletonIns.outputStream && !self.sentPing )
                {
                    if ( [sessionID length]<=0 )
                        sessionID = @"EMPTY";

                    NSLog(@"sessionID : %@", sessionID);
                    NSData* data = [sessionID dataUsingEncoding:NSUTF8StringEncoding];

                    int num = [cobrowseSingletonIns.outputStream write:[data bytes] maxLength:([data length])];
                    if (-1 == num) {
                        NSLog(@"Error writing to stream %@: %@", cobrowseSingletonIns.outputStream, [cobrowseSingletonIns.outputStream streamError]);
                    }else{
                        NSLog(@"Wrote %i bytes to stream %@.", num, cobrowseSingletonIns.outputStream);
                    }
                    sentPing = YES;
                }

            }
            else
            {
                NSLog(@"NSStreamEventHasSpaceAvailable - Connection already established");

                if ( [cobrowseSingletonIns.outputStream hasSpaceAvailable] )
                {
                    [self coShareScreen];
                }
            }
        }
            break;

        case NSStreamEventErrorOccurred:
        {
            event = @"NSStreamEventErrorOccurred";
            NSLog(@"NSStreamEventErrorOccurred - Can not connect to the host");
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Co-browsing" message:@"Connection error, Cannot connect to the host!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            alertView.tag = 5;
            [alertView show];

        }
            break;

        case NSStreamEventEndEncountered:
            event = @"NSStreamEventEndEncountered";
            NSLog(@"NSStreamEventEndEncountered - Connection closed by the server");
            break;

        default:
            event = @"** Unknown";
    }

    NSLog(@"%@ : %@", io, event);
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int tag = alertView.tag;

    NSLog(@"buttonIndex: %d ; alertView.tag: %d", buttonIndex, tag);

    if ( alertView.tag==3 )
    {
        if ( buttonIndex==0 ) // for OK button
        {
            sentPing = NO;

            cobrowseSingletonIns.bConnectionEstablished = YES;
            [cobrowseSingletonIns shareScreen]; // call just once here, then 5 mins thread caller will be called in hasspaceavailable delegate method.
        }
        else if ( buttonIndex==1 ) // for Cancel button
        {
            NSLog(@"User selected Cancel, just stop the socket connection");
            [cobrowseSingletonIns.outputStream close];
            [cobrowseSingletonIns.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        }

    }
    else if (alertView.tag==4)
    {
        NSLog(@"Problem connecting with socket, just stop the socket connection");
        sentPing = NO;
        [cobrowseSingletonIns.outputStream close];
        [cobrowseSingletonIns.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }
    else if (alertView.tag==5) // Socket connection closed Abruptly, one of the reasons, user manually locked of the phone. In this case, logout and love to login
    {
        NSLog(@"Socket connection closed Abruptly due to unknown reasons");
    }
}

//-(void) shareScreen :(NSTimer *) timerInfo
-(void) coShareScreen
{
    NSLog(@"coShareScreen called");

    [cobrowseSingletonIns shareScreen];
}

@end
</code>
and
<code>//
//  CobrowseSingletonSocket.m
//

#import "CobrowseSingletonSocket.h"
#import "AppDelegate.h"
#import "MyUSAAViewController.h"
#import "USAASettingsViewController.h"
#import "ProductsViewController.h"
#import "InboxViewController.h"
#import "ContactUSViewController.h"
#import "VoiceViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation CobrowseSingletonSocket

static CobrowseSingletonSocket *sharedCobrowseSocketInstance = nil;

@synthesize loginViewController;
@synthesize outputStream;
@synthesize inputStream;
@synthesize bConnectionEstablished;
@synthesize socketIPAddress;
@synthesize servletIPAddress;
@synthesize servletPort;

+(CobrowseSingletonSocket *) sharedCobrowseSocketInstance
{
    @synchronized ([CobrowseSingletonSocket class])
    {
        if ( !sharedCobrowseSocketInstance )
        {
            sharedCobrowseSocketInstance = [[super allocWithZone:NULL] init];
        }
    }
    return sharedCobrowseSocketInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [self sharedCobrowseSocketInstance];
}

-(void) takeScreenshotSend :(NSString *) endOrCancelString
{
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    UIGraphicsBeginImageContext(appDelegate.window.bounds.size);
    [appDelegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSMutableData *data = [NSMutableData data];
    data = (NSMutableData *) UIImagePNGRepresentation(image);
    //[data writeToFile:@"screenshot.png" atomically:YES];

    NSLog(@"shareScreen [data length] %i: ", [data length]);

    NSData *newData = [endOrCancelString dataUsingEncoding:NSUTF16StringEncoding];
    [data appendData:newData];
    NSLog(@"shareScreen [data length] %i: ", [data length]);

    //sentPing = YES;

    int num = [self.outputStream write:[data bytes] maxLength:([data length])];
    if (-1 == num) {
        NSLog(@"Error writing to stream %@: %@", self.outputStream, [self.outputStream streamError]);

    }else{
        NSLog(@"Wrote %i bytes to stream %@.", num, self.outputStream);
        //[self.outputStream close];
    }

}

-(void) shareScreenAtInterval
{
    NSLog(@"Screen sharing going to happen!");
    [self takeScreenshotSend:@"END"]; // appending END, to detect the same on the server side and get out of reading data loop there.

}

-(void) shareScreen
{
    NSLog(@"shareScreen called!");
    [self performSelector:@selector(shareScreenAtInterval) withObject:nil afterDelay:5.0];
}

-(void) disconnectSocket
{
    NSLog(@"Close the socket connection by user");

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(shareScreenAtInterval) object: nil];
    //[NSObject cancelPreviousPerformRequestsWithTarget:self];

    // Send Cancel message to socket
    [self takeScreenshotSend:@"CANCEL"]; // appending CANCEL, to detect the same on the server side and get out of reading data loop there.

    [self.outputStream close];
    [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    self.outputStream = nil;

    self.bConnectionEstablished = NO;

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Co-browsing" message:@"Screen sharing disconnected!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];

     AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate.window.rootViewController dismissModalViewControllerAnimated:YES];

}

@end
</code>
Crash error in Xcode
Comment: At a guess, something that is in the removed view controller is still being referenced.  What is the detail of the exception message?  Have you set an exception breakpoint?
Comment: Hi, How do i check exception message? please advise
Comment: You should get a stack trace and enter the debugger when the exception is thrown.  Also go to the breakpoint navigator and press the + at the bottom of the screen - add an exception breakpoint
Comment: I have attached a screenshot of xcode in OP. Could you help please?
Comment: It shows that you referenced a released object.  Do you have an exception breakpoint enabled?  Run with zombies enabled - http://stackoverflow.com/questions/5386160/how-to-enable-nszombie-in-xcode and watch the log for warnings about messages sent to zombie objects
Comment: As You suggested, I enabled breakpoint, zombie log. I could able to get the crash point now..I updated in the screenshot of OP. Please find the screenshot in OP.
Comment: It says like "[HomeViewController respondsToSelector:]: message sent to deallocated instance 0x200629b0", I am not sure where I'm calling a function, which can't be accessible.
Comment: Thank you very much Mr. Paul. I fixed it. The issue was, from LoginViewController i am pushing to HomeViewController. At this time, I used HomeViewController local object, not global, so this obj gets removed by the time when i come back. Now, I moved HomeViewController instance object created in AppDelegate and used in LoginViewController during when pushing it. So, it worked fine.
Answer: Your problem is here -
<code> [cobrowseSingletonIns.inputStream setDelegate:self];
 [cobrowseSingletonIns.outputStream setDelegate:self]
</code>
Your <code>HomeViewController</code> sets itself as the delegate for the socket, but once it has been removed from view it will be deallocated, because the delegate property on the streams will be a <code>weak</code> reference.
You need to make sure the socket writing is completed and cleaned up when the view controller is removed.  Try setting the delegates to nil in <code>viewWillDisappear</code>.

iOS: Crash after writing socket


How to chain a promise that calls another promise in node js

Question: I'm new to node js, I'm trying to create a rest method that returns a list of objects, all was fine until I wanted to send the response, the logic does something like this:

find objects
init the objects
push the object into a list
send the list with the objects

what happens is that the point 3 is happening after the point 4 and I got an empty list, after research I found that is due to the async nature of node, I tried to rewrite the code using promises but I could not find an example of a promise that calls another promise
first version
app.get('/initDevices', (req, res) => {
    console.log('init devices.');
    cameras = [];
    onvif.startProbe().then((device_info_list) => {
        let requests = device_info_list.map((info) => {
            processDevice(info)
        });
        Promise.all(requests).then(() => {
            console.log('all done ');
            res.json(cameras);
        });
    }).catch((error) => {
        res.json('nothing');
    });
});

function processDevice(info) {
    return new Promise((resolve, reject) => {
        console.log("step 1");
        let device = new onvif.OnvifDevice();
        console.log("step 2");
        device.init().then((devinfo) => {
            console.log("step 3");
            cameras.push(devinfo);
            console.log("cameras: " + cameras.length);
            resolve("done");
        }).catch((error) => {
            reject("It broke");
        });
    });
}

output
 init devices.
 step 1
 step 2
 //response goes to the user with empty array []
 step 3 //push happens

second try (with promises)
function processDevice(info) {
    return new Promise((resolve) => {
        console.log("step 1");
        let device = new onvif.OnvifDevice();
        console.log("step 2");
        resolve(device);
    }).then((device) => {
       console.log("step 3");
        return device.init();
    }).then((device) => {
       console.log("step 4");
        return cameras.push(device);
    });
}

output
init devices.
step 1
step 2
step 3
//response goes to the user with empty array []
step 4 //push happens

I think this line return device.init(); makes the promise to finish but I do not know why.
Can someone help me to understand why the chain doesn't work as expected?
what did I do wrong?
by the way, the examples that I followed are here but the operations are just some additions that do not invoke other promises
Edit: I found a better way to achieve this
function processDevice(info) {
    let device = new onvif.OnvifDevice();
    return device.init().then(() => {
        console.log("init done");
        cameras.push(camObj);
    });
}

since a promise was already being used, it was not necessary to wrap it around another
Comment: your map version doesn't return the promise in map callback... `requests` will be array of undefineds
Comment: Avoid the [Promise construction anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) in `processDevice`
Comment: `let requests = device_info_list.map((info) => {
            return processDevice(info)
        });` or `let requests = device_info_list.map((info) => processDevice(info));`
Comment: Return processDevice(info) where you are mapping the requests.
Answer: Your requests variable is undefined - you have to return the processDevice(info) inside the map like this:
let requests = device_info_list.map((info) => {
            return processDevice(info)
        });

Comment: it works, thank you and thank you to Jaromanda X for the help too


Start hostapd service on boot

Question: How to start hostsapd service every time my compute starts
I have Ubuntu Server 13.10 and kernel 3.11
When I tried sudo update-rc.d hostapd defaults I got the following
System start/stop links for /etc/init.d/hostapd already exist.

and sudo service hostapd status shows that the service is not running
Comment: possible duplicate of [How can I configure a service to run at startup](http://askubuntu.com/questions/9382/how-can-i-configure-a-service-to-run-at-startup)
Comment: Does hostsapd need other services in up status to successfully complete its startup?
Comment: @Parto Already tried that, doesn't work
Comment: Is there anything useful in `/var/log/syslog` after "Starting advanced IEEE 802.11 management" if you try `sudo service hostapd start` manually?
Comment: `sudo service hostapd start` works perfectly, my only issue is starting the service automatically @Jos
Comment: Try this: edit the file `/etc/init.d/hostapd`, remove the `--quiet` option in the `start)` section, and reboot. This should give you more informational messages in `/var/log/syslog`.
Comment: @Letizia I have no idea, how to check that?
Comment: @Jos a message there says that the channel chosen is not supported, but when the computer is on I can use the same configuration file to run the service and it works.
Comment: That sounds like a bug. Perhaps report this on Launchpad?
Comment: Run level init process starts ad static-network-up event. The event will not be emitted unless every interface configured as 'auto' in /etc/network/interfaces is up (see this [link](http://askubuntu.com/questions/220377/why-doesnt-network-manager-start-at-boot). Did hostapd need other kind of network up in order to complete its startup? Other point: verify in your /etc/rc2.d the number assigned to Sxxhostapd and which other services has upper value (they start after hostapd). Does this service necessary to hostapd startup? Sorry, but I don't know this service.
Answer: Sounds like you might have gotten past this, as the daemon reports it is running when querying status.
My /etc/default/hostapd file did not define where to find the hostapd.conf file (as  provided by Ubuntu 14.04.1 LTS).  And so, I received no output when running sudo service hostapd start or sudo service hostapd status.
Once I directed the out-of-the-box init script to a configuration file, the service was able to start, and show status.
Maybe this was done on purpose to force you to think about configuration before the wireless services start.

Start hostapd service on boot


Detecting an empty hand (1.9)

Question: So I'm making a map for version 1.9 and one of its core mechanics, is that if someone is holding an object in hand, they get a certain effect (speed, jump boost etc.) and I'd like the effect to come off as soon as they switch to an empty slot or another item. With the second one the job is simple, but I've been wondering and can't find the solution for a seemingly simple question.
Is it possible to detect if a player isn't holding anything in their hand?
Comment: Can't you just copy your NBT check and use `nbt=!{…}` for the reverse check? That way you don't need to individually check for holding another item and for holding nothing, it's just one check for both.
Answer: Maybe this is what you want:
/give PlayerNameHere minecraft:iron_boots 1 0 {AttributeModifiers:[{AttributeName:"generic.movementSpeed",Name:"generic.movementSpeed",Amount:20,Operation:1,UUIDLeast:425245,UUIDMost:849726,Slot:"feet"}],display:{Name:"runners shoes"}}
This gives a specific player a pair of iron boots called runners shoes, with which he can run faster, if he has it on his feet.

Detecting an empty hand (1.9)


Why is this program not entering my ElseIf statement -- System.DBNull

Question: I imported an Excel file into an ASP.NET DataTable.  Some of the values are blank, specifically at indexes 2 and 3, and I would like to set those blank fields to 0.
When debugging, the values for row.item(2) and row.item(3) are both System.DBNull.  Interestingly enough, the program enters the If statement and sets row.item(2) value to 0, but it never enters the ElseIf statement. What is going on?  Here's my code:
If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
    dt.Rows.Item(i).SetField(2, 0)

ElseIf row.Item(3) Is Nothing OrElse row.Item(3).ToString = "" OrElse IsDBNull(row.Item(3)) Then
    dt.Rows.Item(i).SetField(3, 0)
End If

EDIT:
Per Tim's suggestion, I revised my code as follows:
If Not row.Field(Of Int32?)(2).HasValue Then
    dt.Rows.Item(i).SetField(2, 0)
End If

If Not row.Field(Of Int32?)(3).HasValue Then
    dt.Rows.Item(i).SetField(3, 0)
End If

However, this is throwing an error--Object cannot be cast from DBNull to other types
When debugging, in the first loop:
row.Item(2) = 17
row.Item(3) = 1
Theoretically, it should skip this iteration and proceed to the next.  However, my program immediately catches the exception with the above error.
Answer: Since your if is executing, your else if will not execute.
If you want your else if logic to execute even if your if executes, just make it it's own if block:
If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
    dt.Rows.Item(i).SetField(2, 0)
End If

If row.Item(3) Is Nothing OrElse row.Item(3).ToString = "" OrElse IsDBNull(row.Item(3)) Then
    dt.Rows.Item(i).SetField(3, 0)
End If

Comment: Side-note: It's better to use the strongly typed `Field`-extension method which also supports nullable types. For example: `If Not row.Field(Of Int32?)(2).HasValue row.SetField(2, 2) End If`.
Comment: Wow. That's like programming 101 and I failed at it.  Thanks!
Comment: @user1496816: will hve a look tomorrow, don't have time now :)
Comment: @TimSchmelter Thanks for the tip.  Unfortunately, the strongly typed `Field` extension is not working for me.  See the main post edit for details.
Comment: @TimSchmelter Just finished typing it.
Answer: You don't provide sample data so we just have to guess.  But my guess is that you want two If statements.. not an ElseIf.  ElseIf will only evaluate if the If statement returns false.


Related to angles in tetrahedron

Question: Let $OABC$ be a tetrahedron such that $|OA|=|OB|=|OC|$. Denote by $D$ and $E$ the midpoints of segments $AB$ and $AC$ respectively. If $\alpha=\angle(DOE)$ and $\beta=\angle(BOC)$ what is the ratio $\beta/\alpha$?
It is obvious that $|BC|=2|DE|$ since triangles $\Delta(ABC)$ and $\Delta(ADE)$ are similar and $D, E$ are midpoints by assumption. I would expect that $\beta/\alpha\geqslant 2$ but I haven't been able to confirm this. I tried to use the cosine law for the segments $|BC|$ and $|DE|$ but without success.
Comment: To test your expectation that $\beta/\alpha\geq 2$, consider an degenerate case where $\triangle ABC$ is equilateral and $O$ is its center (so the tetrahedron is *flat*). In this situation, both $\angle BOC$ and $\angle DOE$ are obviously equal (at $120^\circ$). Lifting $O$ ever-so-slightly above the plane of $\triangle ABC$ un-flattens the tetrahedron, but those angles will remain very-nearly equal; therefore, you should not expect one angle to always be at least twice the size of the other.
Answer: The ratio $\beta/\alpha$ does not take a single value. This answer does not attempt to find a formula for the ratio.
I imagine this becomes finding the distance of two mid-points of a spherical triangle.
Construct a sphere centred at $O$ with radius $r=OA$.
Extend $OD$ and $OE$ to meet the sphere at $D'$ and $E'$ respectively; $D'$ and $E'$ will be the mid-points of arcs $\overset{\frown}{AB}$ and $\overset{\frown}{AC}$ respectively.
Then the required angles $\angle BOC$ and $\angle D'OE'$ are proportional to the lengths of arcs $\overset{\frown}{BC}$ and $\overset{\frown}{D'E'}$ respectively:
$$\frac\beta\alpha = \frac{\angle BOC}{\angle D'OE'} = \frac{\overset{\frown}{BC}}{\overset{\frown}{D'E'}}$$
Now consider four special / extreme cases:
Case 1: When $A$, $B$ and $C$ are near relative to the size of the sphere, Euclidean geometry becomes applicable, and arcs and respective chords are approximately equal in length. By mid-point theorem,
$$\overset{\frown}{BC} \approx 2\overset{\frown}{D'E'},\quad \frac\beta\alpha \approx 2$$
Case 2: When $A$ is the north pole of the sphere, and $B$ and $C$ on the equator. $D'$ and $E'$ are on the $45^\circ N$ latitude. Comparing the arc lengths of $\overset{\frown}{BC}$ and $\overset{\frown}{D'E'}$,
$$\overset{\frown}{BC} >\overset{\frown}{D'E'},\quad \frac\beta\alpha > 1$$
Case 3: When $A$ is the north pole, and $B$ and $C$ are on the $30^\circ S$ latitude. $D'$ and $E'$ are on the $30^\circ N$ latitude, with the same longitude as $B$ and $C$ respectively. Then $\overset{\frown}{D'E'}$ and $\overset{\frown}{BC}$ are symmetric, reflected by the equatorial plane,
$$\overset{\frown}{BC} = \overset{\frown}{D'E'},\quad \frac\beta\alpha = 1$$
Case 4: When $A$ is the north pole, and $B$ and $C$ are close to the south pole. The spherical triangle of $ABC$ is almost like a spherical lune. $D'$ and $E'$ are just north of the equator.
Arc $\overset{\frown}{BC}$ can be arbitrarily short, while $\overset{\frown}{D'E'}$ depends on the longitudes of $B$ and $C$ and tends to $r$ times the difference in longitudes.
$$\overset{\frown}{BC} \ll \overset{\frown}{D'E'},\quad \frac\beta\alpha \approx 0$$
Answer: This answer attempts to find a formula for the ratio.
I imagine this becomes finding the distance of two mid-points of a spherical triangle.
Construct a sphere centred at $O$ with radius $r=OA$.
Extend $OD$ and $OE$ to meet the sphere at $D'$ and $E'$ respectively; $D'$ and $E'$ will be the mid-points of arcs $\overset{\frown}{AB}$ and $\overset{\frown}{AC}$ respectively.
Following this convention of spherical trigonometry, consider the spherical triangle $ABC$, denote
$$\begin{align*}
a &= \angle BOC = \beta\\
b &= \angle AOC\\
c &= \angle AOB
\end{align*}$$
According to the spherical laws of cosine, if $A$ is the spherical angle made by arcs $\overset{\frown}{AB}$ and $\overset{\frown}{AC}$, consider spherical triangle $ABC$,
$$\begin{align*}
\cos A &= \frac{\cos a -\cos b \cos c}{\sin b \sin c}\\
&= \frac{\cos \beta -\cos b \cos c}{\sqrt{(1+\cos b)(1-\cos b)(1+\cos c)(1-\cos c)}}\tag 1\\
\end{align*}$$
And consider spherical triangle $AD'E'$,
$$\begin{align*}
\cos A  &= \frac{\cos \angle D'OE' -\cos \frac b2 \cos \frac c2}{\sin\frac b2 \sin\frac c2}\\
&= \frac{\cos \alpha -\sqrt{\frac{1+\cos b}2} \sqrt{\frac{1+\cos c}2}}{\sqrt{\frac{1-\cos b}2}\sqrt{\frac{1-\cos c}2}}\\
&= \frac{2\cos \alpha - \sqrt{(1+\cos b)(1+\cos c)}}{\sqrt{(1-\cos b)(1-\cos c)}}\tag 2
\end{align*}$$
Equating $\cos A$ in $(1)$ and $(2)$,
$$\begin{align*}
\frac{\cos \beta -\cos b \cos c}{\sqrt{(1+\cos b)(1+\cos c)}} &= 2\cos \alpha - \sqrt{(1+\cos b)(1+\cos c)}\\
\cos \beta -\cos b \cos c &= 2\cos \alpha\sqrt{(1+\cos b)(1+\cos c)} - (1+\cos b)(1+\cos c)\\
\cos \beta &= 2\cos \alpha\sqrt{(1+\cos b)(1+\cos c)} - 1 - \cos b - \cos c\\
\cos \alpha &= \frac{1 + \cos b + \cos c + \cos \beta}{2\sqrt{(1+\cos b)(1+\cos c)}}\\
&= \frac{1 + \cos b + \cos c + \cos \beta}{4\cos\frac b2 \cos \frac c2}\\
\frac \beta\alpha &= \frac{\beta}{\arccos \cfrac{1 + \cos b + \cos c + \cos \beta}{4\cos\frac b2 \cos \frac c2}}
\end{align*}$$

Related to angles in tetrahedron


Should I keep a bathroom door open or closed to keep it from expanding?

Question: Should I keep the bathroom door open or shut after a shower to keep it from expanding?  What if the fan is on as well?
Comment: Whether it is open or closed has no bearing on it expanding due to excessive moisture. Though if the room isn't properly vented with an exhaust fan, leaving it open may reduce the overall moisture in that one area.
Comment: How humid is the rest of the interior, especially right outside the bathroom door?
Comment: When the door was painted. were all six (6) surfaces painted in the same way?  Warping is more problematic than simple expansion...
Comment: Does the door swing in or out?  Is the door so tight, that if it expands it sticks? Why are you trying to prevent the expansion?
Answer: Leave the door open to reduce humidity, better yet: knock out the hinge pins, pull the door  and lay the door flat on some sawhorses and give it a good glossy paint job paying special attention to the top and bottom edges.


Scrapy crawling speed is slow

Question: I had been crawling a ecommerce website using Scrapy and the crawling speed I am getting is 50~60 pages/minute.
I am using 8 core linode server with 24 GB Ram, so I don't think network or server could be the reason.
I am aware of the fact the some websites give download latency if we crawl them too often, but this is a large website and I am using proxymesh proxies too, so this also could not be possibly the reason.
I think I am missing something in settings.py file -
<code>BOT_NAME = 'scraper'

SPIDER_MODULES = ['com.crawler.scraper.spiders']
NEWSPIDER_MODULE = 'com.crawler.scraper.spiders'

ITEM_PIPELINES = {
    'com.crawler.scraper.pipelines.generic_pipeline.Pipeline': 300
}
RANDOMIZE_DOWNLOAD_DELAY = False
COOKIES_ENABLED = False
CONCURRENT_ITEMS = 200
CONCURRENT_REQUESTS=50
DOWNLOAD_DELAY= 0
CONCURRENT_REQUESTS_PER_DOMAIN=50
LOG_LEVEL = 'ERROR'
RETRY_TIMES = 2
CONNECTION_TIMEOUT = 30
USER_AGENT_LIST = 'user_agents.txt'

DOWNLOADER_MIDDLEWARES = {
    'random_useragent.RandomUserAgentMiddleware': 400,
    'com.crawler.scraper.middlewares.proxy_middleware.ProxyMiddleware': 410,
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
}
</code>
I started from DOWNLOAD_DELAY 5 and now even I have kept it as 0 but still I couldn't see any significant change in the number of requests per minute.
So, my questions are ->
1) What should I do to increase the speed to at least 200 requests/minute?
2) What should be the ideal value for CONCURRENT_ITEMS?
Comment: What is the average response time for a single page? 50-60rpm is already significant load for a single client.
Comment: But if I am using dynamic proxies, the website couldn't identify that the requests are coming from the same client, and the website is amazon, and I had seen others crawling at a much higher speed, @jordanm
Comment: Is the [AutoThrottle extension](https://docs.scrapy.org/en/latest/topics/autothrottle.html) on or off? You can disable it and check if it makes any difference.
Comment: @paultrmbrth I think it is disabled by default
Comment: If you created your project with `scrapy startproject`, the `settings.py` contains `AUTOTHROTTLE_ENABLED=True`. You can check that in the logs when the crawl starts, where the middlewares are listed.
Answer: CONCURRENT_ITEMS is definitely not the solution as this setting has only impact on the processing time used on the server and given your server specs that shouldn't make a difference at all.
Besides that your settings look ok, your scraper should go as fast as the site responds. (even when upping DOWNLOAD_DELAY to 1, the scraper would have the potential to do 50 x 60 = 3000 requests a minute)
Oh and RANDOMIZE_DOWNLOAD_DELAY should also be set to True, just to be sure.
Depending on the number of proxies you use, it is very likely that the target site is throttling your scraper.
At the current speed, if using ProxyMesh's smallest 20 IP plan, you would be hitting the site every 20 seconds from the same IP. If using their 100 IP plan you'd be still sending a request from each IP every 100-120 seconds.
Doing this over an extended period of time is fast enough to get your ProxyMesh IPs throttled. Also I would speculate your scraper was faster when starting out and then got throttled because of this.
Ways to check my theory: either add more IPs and the speed should increase accordingly or wait 24 hours until ProxyMesh assigned you new IPs and then run the scraper again and watch if it starts much faster and then gets throttled down.
Comment: just to clarify the things more, I am using proxymesh world proxy, which gives a very large amount of IP's(not sure of the number).
Comment: As far as I understand the price structure of proxymesh, they limit your number of IPs per day and rotate them out after 24 hours. So only a fraction of the full 15k IPs of the proxymesh world proxy will be available to you on a single day (unless you have signed up for some unofficial plan they don't list on their site)

Scrapy crawling speed is slow


Why is my oven unable to achieve baking temperatures?

Question: Some time ago, the bottom heating element of the oven burnt. I replaced it. From there, the temperature can not rise to the assigned target (350° F). It stalls at around 200 and it is very slow to reach it. I thought that the element was the culprit but the vendor rejected the return and told me that the electronic board could have burnt too and that I should check that I get 240V at the element connectors. So I borrowed a multimeter and tried various things:
The continuity test around the element is ok.
I get 0V when starting the Bake function. However, the temperature slowly rises, which puzzles me since I get 0V.
If I test the top element I correctly get 240V when starting the Broil function.
Can I safely consider that the electronic board is the culprit and purchase a new one?
Why is the temperature still rising slowly while I read 0V around the element?
The oven is a Whirlpool model YWFE745H0FS1.
Thanks helping me understand what happens.
Answer:
Why is the temperature still rising slowly while I read 0V around the element?

Most likely, your oven preheats with both elements. Usually they alternate so you should hear the "click" sound of a relay as this happens, perhaps every 15 seconds or so. If the bottom one is not working, you'll still get some heat from the top one but not as much, hence the slow warmup. It should be easy for you to confirm this is what is happening.
Once the oven considers warmup done, it will switch to bottom element only and no longer heat at all. Again, easy enough to check if you let it run for an hour or so.

Can I safely consider that the electronic board is the culprit and purchase a new one?

Safely? No. Nothing is certain when troubleshooting. But it's a reasonable guess and the next most likely culprit. But because of the cost of these, you should first check the wiring between the element and the control board, or simply check the voltage at the exit of the control board. Make sure there are no fuses there which might have blown. It's not fun to buy a $150 part and then find out it was a $1 part you really needed.
Comment: One of the great disappointments (for me) of contemporary life is that fixing things is often more expensive than buying a new item.  I bought a bunch of replacement parts for a charcoal kettle grill and once I had it fixed, I realized I spent more than what a new one costs.  So deflating.
Comment: @Nelson economy of scale is only a part of it. I dare say not the most important one. In many areas, replacement parts that are made by 3rd party are much cheaper than the originals, and of the same quality. If scale was the deciding factor for price, that wouldn't be the case.
Comment: You're right. I was able to see that it preheats with the top element also. So as you suggested, I checked the voltage at the control board exit. It's 0V. I also checked the only fuse there is, a thermostat security, and its continuity is fine. So I guess the board is the one that is faulty... And unfortunately, it doesn't cost 150$. It costs ~400 CA$!
Comment: @NicolasCadilhac that's an even bigger ripoff than I expected. It might be worth trying to fix it yourself. Or finding someone locally to make the attempt if you don't have the tools and skill. As broil is still working, you probably just have a dead relay in there.
Comment: @JimmyJames It is economy of scale. Making and shipping 100 parts in bulk to a manufacturer is way cheaper logistically than creating a way for you to purchase individual parts across multiple countries. You then have to deal with defects, damage, fraud, etc.
The alternative is you DIY as many of the parts as possible, but that is quite a bit more advanced, and there's definitely risks involved.


Need to populate textbox via value of selectbox, multiple textboxes and selectlists

Question: Hey guys I have a table that has a main row, a row with a textbox and row with a selectlist that has values of premade comments that when double clicked on need to be populated into the textbox just above it. I am able to get the value of the selected list item into a variable but I can't seem to find the textbox I am looking for. This is all ran by our DB so I am using classes instead of ids and need to find the previous item with the class name. Heres my code, any help would be great.
NOTE: I am not including the document.ready wrapper but it is in my code.
   $(".mfValues").dblclick(function () {
            var val = $(this).attr("value")
           // alert(val);
            $(this).prev(".mfTextComments").val(val);
        });

<textarea class="mfTextComments" runat="server" cols="20" rows="2" ></textarea>
";

<select runat=\"server\" style=\"height:20px;\" title=\"Please select a comment from this list by double clicking the comment or create your own in the text area above.\" size=\"4\">
    <option class="mfValues" value="Value1"\">Value1</option>
    <option class="mfValues" value="Value2"\">Value1</option>
    <option class="mfValues" value="Value3"\">Value1</option>
    </select>

Answer: You were almost there, just need to get out of the
 :
$(".mfValues").dblclick(function() {
    var $this = $(this),
        val = $this.val();
    $this.closest('tr').prev().find(".mfTextComments").val(val);
});

Comment: Thanks that did teh trick! I'm still learning how to group functions together, and this helped a lot.
Comment: No problem, sorry for the multiple edits - I kept typo'ing :)
Comment: NP. One thing tho you have an extra unneeded line for the variable the way I have it set to one line works perfectly.
Comment: Yea but it's always good to cache your selectors if you plan to use it more than once. By caching $(this) it's saved in memory vs having to go out and select it again. Just a performance enhancement.
Comment: ahh I see, I don't need it held in memory, once it is in the textarea the user can add to the comment line or just hit submit then it is sent to the server and everything is handled there. Its just a way of giving our employees a faster way of commenting what they are working on.


Jasmine test, not catching " is not a function" error

Question: In my Angular 7 component, ngOnInit is calling a method (getRecurrence) on a service.  For testing, I am mocking the service, but the mock is missing the method.  (So, the component code is correct, but the test mocks are wrong)
Component source snippet:
async ngOnInit() {
  try {
    var results = await Promise.all([
      this.lookupService.getRecurrence(),
      ...
    }
  }

When I run the test, I get the expected error message TypeError: this.lookupService.getRecurrence is not a function in the log file, but Jasmine and Karma report that the test passes.
Edited: The Jasmine test is mostly the standard one created from ng g c ....
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [MyComponent],
    imports: [ReactiveFormsModule, BrowserAnimationsModule, FormsModule],
    providers: [
      { provide: LookupService, useClass: MockLookupService }
    ]
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () => {
  expect(component).toBeTruthy();
});

Since ngOnInit is async, I tried adding either async() or fakeAsync() to the beforeEach that creates the component and the test case that verifies it was created, to no avail.
Any suggestions on how to get Jasmine and Karma to catch the error and report failure?
Edited: I implemented Bill Cheng's suggestions, still no luck.  I added console log message to the tests (and replaced the await Promise.all() with await this.lookupService.getRecurrence()), and this is what I get.
ngOnInit source snippet:
async ngOnInit() {
  console.log('ngOnInit')
  try {
    console.log('Before getRecurrence')
    this.recurrences = await this.lookupService.getRecurrence();
    console.log('After getRecurrence')
    ...
  }
}

Test code:
it('should create', async() => {
  fixture.detectChanges();
  console.log('should create before whenStable')
  await fixture.whenStable();
  console.log('should create after whenStable')
  expect(component).toBeTruthy();
});

Console log results:
ngOnInit
context.js:245 Before getRecurrence
context.js:245 TypeError: this.lookupService.getRecurrence is not a function
    [stack trace deleted]
context.js:245 should create before whenStable
context.js:245 should create after whenStable

It looks to me like someplace the TypeError is being handled and eaten, so as far as Jasmine is concerned there was no exception...
Comment: Can you update your question to include the relevant code? What does the test look like?
Comment: 1. Try to move `fixture.detectChanges();` to it(...)   2. remove the async in beforeEach   3. use `await fixture.whenStable();` after detectChanges... this should solve your problem
Comment: @BillCheng No joy, still not catching the error.
Answer: The answer was staring me in the face, I just needed to post a little more of the code.
async ngOnInit() {
  try {
    ...
  }
  catch (err) {
    console.log(err);
  }
}

I'm eating the error so that the unit test doesn't see it.  /.\
Comment: not a good idea to catch and swallow an error to pass a test. Does you user know you have and error?


Using Foundation Orbit Alongside Interchange - Reflow issues

Question: I am not able to get orbit to trigger its natural behaviour as a slider, when interchange has done its job.
JS:
    $(document).foundation('interchange', {
        named_queries : {
            small_range : 'only screen and (min-width:0px) and (max-width: 768px)',
            medium_range : 'only screen and (min-width:769px) and (max-width: 1024px)',
            large_range : 'only screen and (min-width:1025px) and (max-width: 1200px)',
            xlarge_range : 'only screen and (min-width:1201px)',
        }
    });

I have interchange running on another part of site and all works fine there. I need to add obit reflow to the code above with breaking the current interchange html Orbit settings use the data attr).
I have tried:
$(document).foundation('interchange', 'orbit', 'reflow', {

But to no avail. To clarify Interchange works fine across the site, however when the DOM gets changed the slider behaviour is not triggered..
Answer: I actually fixed my issue. I was using interchange insert an html file with an orbit slider for medium and large screens, but a different file without a slider for small screens. The orbit slider would not work at all after the interchange since the foundation js already fired after the slider was loaded. I fixed it by including this IN the html file i was including that had the orbit slider in order to re-call the js for the slider.


apache htaccess codeigniter query string to path

Question: i'm trying to make a codeigniter based website be able to convert index.php?option=test&controller=con1 to /test/con1 using .htaccess i tried multiple examples i found and none seem to work, it goes straight to the home page. any ideas?
i've tried things like
RewriteCond %{QUERY_STRING} ^(\w+)=(\w+)$
RewriteRule ^\/(.+?)\/(.+?)\/?   /index.php/$1/$2 [L]

but doesn't throw any errors or anything.
 my current htacces is
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|img|js|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Answer: try put this .htaccess in same directory with your index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Comment: moving one of the rewritecond to a different spot?
Comment: just try to replace your current htaccess with i provided above
Comment: OK I did and see no difference, still ignoring the GET parameters.


correct mssql connection string in php

Question: Perhaps this is the connection string to connect to an sql server
<?php
$myServer = "localhost";
$myUser = "your_name";
$myPass = "your_password";
$myDB = "examples";
?>

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

but i do not know what to input in the $myServer, $myUser and $myPass
if I wanna use windows authentication
This is my Server details kindly help me please
Microsoft SQL Enterprise Manager
Microsoft Corporation
Version: 8.0
Comment: check manual http://php.net/manual/en/function.mssql-connect.php
Answer: If you have PHP 5.3 or later, you can no longer use the ms_sql extension, according to the PHP documentation page. I'm not sure of the extent of that, but you may want to consider using PDO instead. It allows for a generic way to access various database types, including MSSQL. To connect to a MSSQL database using PDO, you first need SQLSRV, the driver, which you can download from Microsoft here. To connect, you would use the following:
$handle = new PDO("sqlsrv:Server=$server;Database=$database", $username, $password);

Above, and to answer the main part of your question, $server is probably localhost, and your username and password can be accessed and changed from within the Microsoft SQL Server access panel. I believe you can use "sa" for $username and "" for $password. For $database, just put in the name of the database you want to connect to.
To query:
$queryRef = $handle->query($query);

To read results, declaring $results as a two-dimensional associative array, the first being the result number, the second being the column name:
$results = $queryRef->fetchAll(PDO::FETCH_ASSOC);

So $results[3]['id'] would be the value of the column 'id' of the third result.
You can find more examples on the PHP documentation page for PDO here. Much of this was taken from my previous answer here.
Answer: Your server is usually localhost, and your username and password could be changed and viewed by following this tutorial:
http://blog.sqlauthority.com/2007/12/29/sql-server-change-password-of-sa-login-using-management-studio/

correct mssql connection string in php


Unable to update button display data

Question: I am learning Kotlin and TornadoFX to program a very simple task: two buttons, one with Int 1 and other with Int 200.  When I click the button one, I would like to update and display button one  with Int 2 and the other with Int 201.  The following program will allowed me to check the update data and all seemed to be correct.  My question is why the display on the buttons would not be updated according.
Please help.
class MainView : View("Hello TornadoFX") {
    val controllera: ControllerA by inject()
    val i: Int? = 1
    val j: Int? = 2
    override val root = hbox {

        button(controllera.s1.toString()) {
            setOnAction {
                setId(i.toString())
                println("  in view button 1 s1: { ${controllera.s1.toString()} }")
                controllera.temp(i)
            }
        }
        button(controllera.s2.toString()) {
            setOnAction {
                setId(j.toString())
                println("  in view button 2 s2:  { ${controllera.s2.toString()} }")
                controllera.temp(j)
            }
        }
        label(title) {
            addClass(Styles.heading)
        }
    }
  }

class ControllerA :Controller(){
     var s1: Int =1
     var s2: Int = 200
    fun temp(k: Int?) {
        when( k) {
            1 -> {println("botton ID  " +k)
                println(" current value of s1:   $s1 ")
                s1 = s1+1
                println(" new value of s1 to update:   $s1 ")
                s2 = s2 +1
                println(" new value of s2 to update:   $s2 ")}
            2 -> {
                println("botton ID  " + k)
                println("current value of  s2:   $s2 ")}
            else -> println("default")
        }
    }
}

test output  at various location:
  in view button 1 s1: { 1 }    //In MainView
botton ID  1        //in ControllerA
 s1:   1
 new value of s1 to update:   2
 new value of s2 to update:   201
  in view button 2 s2:  { 201 } //in MainView
botton ID  2            //in ControllerA
current value of  s2:   201
Note: those updated data will not be display on button text.

Answer: You need to use observable properties and bindings. Just starting writing code without reading about the framework is not a good approach. I suggest you read the guide as a starting point. Here is your code rewritten so that each button will display and increase the corresponding number on click:
class MainView : View("Hello TornadoFX") {
    val controllera: ControllerA by inject()
    val myModel: MyModel by inject()

    override val root = hbox {

        button(myModel.s1.asString()) {
            action {
                controllera.inc(myModel.s1)
            }
        }
        button(myModel.s2.asString()) {
            action {
                controllera.inc(myModel.s2)
            }
        }
        label(title)
    }
}

class MyModel : ViewModel() {
    val s1 = SimpleIntegerProperty(1)
    val s2 = SimpleIntegerProperty(200)
}

class ControllerA : Controller() {
    fun inc(v: IntegerProperty) {
        v.value = v.value + 1
    }
}

Comment: Mr. Edvin Syse:  The program you suggested works!   Yet having reading your TornadoFX Guide several times before and gleaned over observable and observer properties over web.  I hardly could comprehend how all these were tied in TornadoFX.  Your examples of "Why tornadoFX?" and ViewModel were presented beautifully and convincing for such complicated yet really difficult examples.  I did not see how to relate observable and binding in kotlin and tornadoFX. Now I do. I really appreciated your contribution to development of Kolin and TornadoFX projects and educate us.
Daniel

Unable to update button display data


Vue2 Date-Picker Date Time Format Empty Problem

Question: I'm using vue2-datepicker to represent starting and ending time of meeting in a company. In our backend we store the dates in "YYYY-MM-DD HH:mm" format but when we get the data, we convert it on the mounted() hook in "DD-MM-YYYY HH:mm" because in our country this is the correct way to represent the date.
I'm using the same method for all the datepickers but this one bothers me with HH:mm.
When the data comes from API, I use a function called "responseDateTimeFormatter" which slices the YYYY-MM-DD HH:mm formatted date and converts into the one I mentioned earlier.
When I post the data, I also use requestDateTimeFormatter to convert it again as YYYY-MM-DD HH:mm to be stored on database.
Here is the problem, after I convert the data into the format that I want, the <date-picker>s are all empty. Even though their format attribute is set to same one with my date's.
Here are my codes:
DatePicker:
              <date-picker ref="startDatepicker" id="startDate" name="startDate" v-model="meeting.startDate" :first-day-of-week="1" type="datetime" format="DD-MM-YYYY HH:mm" @change="startDateClick" :disabled-date="disableStartDate" :time-picker-options="timePickerOptions"></date-picker>

After I convert the data the v-model looks as follows
meetingStartDate = 30-07-2022 09:30

As I explained earlier, it is in YYYY-MM-DD HH:mm format when it came from response.
I convert it with responseFormatter function below;
  responseTimeFormatter(dateTime) {
    var day = dateTime.slice(8, 10);
    var month = dateTime.slice(5, 7);
    var year = dateTime.slice(0, 4);
    var time = dateTime.slice(11, 16);

    return day + "-" + month + "-" + year + " " + time;
  },

Here is my then() block;
  .then((response) => {
    this.meeting = response
    console.log("MEETING", this.meeting)
    this.meeting.startDate = this.responseTimeFormatter(response.startDate)
    console.log("Start Date", this.meeting.startDate)

    this.meeting.endDate = this.responseTimeFormatter(response.endDate)
    console.log("End Date", this.meeting.endDate)
  })

So after all these, meeting.startDate is in the right format. The v-model of the DatePicker above is in the right format (same with the format attribute of the date picker) but still I am not seeing the date in my date-picker. It is empty.
There is no problem when I use it without HH:mm but in datetime format it gives me this problem. Is there anyone have experienced this problem? What is the solution? Thanks in advance.
Answer: I checked out the vue2-datepicker package and when I pass string date as input it shows me an empty field so I think it does not accept string type as a date you must pass a date object
actually, you don't need that responseTimeFormatter function pass your DateTime string to the Date object, and done :)
modify your then block like this:
 .then((response) => {
    this.meeting = response

    this.meeting.startDate = new Date(response.startDate)
    this.meeting.endDate = new Date(response.endDate)
  })

To convert that long string that comes from the Date object to your backend format, you can use this way
define these two functions in your methods object:
  methods: {
    padTo2Digits(num) {
      return num.toString().padStart(2, "0");
    },
    formatDate(date) {
      return (
        [
          date.getFullYear(),
          this.padTo2Digits(date.getMonth() + 1),
          this.padTo2Digits(date.getDate()),
        ].join("-") +
        " " +
        [
          this.padTo2Digits(date.getHours()),
          this.padTo2Digits(date.getMinutes()),
          this.padTo2Digits(date.getSeconds()),
        ].join(":")
      );
    },
  },

and when you call your API to send data to your backend use this:
// some code here for API call
this.formatDate(this.meeting.startDate)

References:
Format a Date as YYYY-MM-DD hh:mm:ss in JavaScript
Date Object JavaScript


Jenkins remote ERROR: Error cloning remote repo 'origin'

Question: I don't know what that means, could someone explain what the problem is, and what the solution would be.
I've been stuck here a couple of days.
I want to run the tests on a virtual machine on Azure.
I have updated all the Jenkins plugins.
I use Putty for the ssh tunnel
This is the console output I get when I want to run the build:
Started by user admin
Building remotely on testadminjenkinsazure277db0 (ubuntu) in workspace /home/Jenkinsadmin/workspace/DemoProject5
Cloning the remote Git repository
Cloning repository https://github.com/jankojanko123/my-app.git
 > C:\Program Files\Git\cmd\git.exe init /home/Jenkinsadmin/workspace/DemoProject5 # timeout=10
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Could not init /home/Jenkinsadmin/workspace/DemoProject5
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$5.execute(CliGitAPIImpl.java:787)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:579)
    at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:153)
    at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:146)
    at hudson.remoting.UserRequest.perform(UserRequest.java:212)
    at hudson.remoting.UserRequest.perform(UserRequest.java:54)
    at hudson.remoting.Request$2.run(Request.java:369)
    at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    Suppressed: hudson.remoting.Channel$CallSiteStackTrace: Remote call to testadminjenkinsazure277db0
        at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1741)
        at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:357)
        at hudson.remoting.Channel.call(Channel.java:955)
        at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.execute(RemoteGitImpl.java:146)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.invoke(RemoteGitImpl.java:132)
        at com.sun.proxy.$Proxy222.execute(Unknown Source)
        at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1146)
        at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1186)
        at hudson.scm.SCM.checkout(SCM.java:504)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1208)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:574)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:499)
        at hudson.model.Run.execute(Run.java:1810)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:97)
        at hudson.model.Executor.run(Executor.java:429)
Caused by: hudson.plugins.git.GitException: Error performing command: C:\Program Files\Git\cmd\git.exe init /home/Jenkinsadmin/workspace/DemoProject5
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2023)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1984)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1980)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:1612)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$5.execute(CliGitAPIImpl.java:785)
    ... 11 more
Caused by: java.io.IOException: Cannot run program "C:\Program Files\Git\cmd\git.exe" (in directory "/home/Jenkinsadmin/workspace/DemoProject5"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at hudson.Proc$LocalProc.<init>(Proc.java:249)
    at hudson.Proc$LocalProc.<init>(Proc.java:218)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:936)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2012)
    ... 15 more
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 20 more
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE

Answer: Seems to be that you're building your Jenkins job on remote Ubuntu agent (in /home/Jenkinsadmin/workspace/DemoProject5 workspace), but path to Git you have defined as a Windows folder (C:\Program Files\Git\cmd\git.exe). So, you need to install Git on Ubuntu and set correct path to it (linux-style).
Answer: the error says: Cannot run program "C:\Program Files\Git\cmd\git.exe". this means you dont have git installed (or at least, not in this path). You need to install it.
Comment: I've installed git and I've set the path (C:\Program Files\Git\bin\git.exe). it still doesn't work properly
Comment: how many agents you have? maybe you configured the wrong one?
Comment: I have one agent
Answer: In the Global  Tool Configuration provide the complete path including the git.exe.....  In my case it is C:\Program Files\Git\bin\git.exe    I got the same error when leaving the program name : C:\Program Files\Git\bin\


Pivot Query into combinations of columns

Question: In Sql Server 2008 how can I go from here:
Owner  Animal   Age  Height   Weight
-----  ------   ---  ------   ------
Steve  Dog        8     22      60
Steve  Cat        5     11      14
Steve  Gerbil     2     1.5     0.3

To here:
Owner  Dog_Age  Dog_Height  Dog_Weight  Cat_Age  Cat_Height  ...
-----  -------  ----------  ----------  -------  ----------  ...
Steve       8           22          60        5          11  ...

So I am pivoting the Animal column,  but want to generate columns for all possible combinations of animals and certain columns.  No aggregate function is actually being performed.  Since for my table the total number of possible combinations will be fairly large, I'd like a solution that avoids me having to explicity type out every resulting column name, but I'll do it if I must.
I have looked at several examples of the PIVOT command, but I have not run across any that create columns from combinations like above, so I'm not sure this is possible.  SQL Server is not my area of expertise.
Comment: Always useful to specify and/or tag with the version of SQL Server. Different versions have different capabilities.
Comment: Just updated my question - it's 2008 R2.
Answer: If you don't care about order of columns in the final output:
DECLARE @sql NVARCHAR(MAX);

SELECT @sql = N'';

SELECT
    @sql = @sql + ',' + Animal + '_$c$ = MAX(CASE WHEN Animal = '''
          + Animal + ''' THEN $c$ END)'
FROM dbo.PetStuff
GROUP BY Animal;

SELECT @sql = 'SELECT Owner '
 + REPLACE(@sql, '$c$', 'Age')
 + REPLACE(@sql, '$c$', 'Height')
 + REPLACE(@sql, '$c$', 'Weight')
 + ' FROM dbo.PetStuff
 GROUP BY Owner;';

PRINT @sql;
-- EXEC sp_executesql @sql;

If column order matters (order by animal name then age/height/weight alphabetically), then you can put the columns in a table instead and generate the SQL with slightly more work:
DECLARE @cols TABLE(col SYSNAME);
INSERT @cols SELECT 'Age' UNION ALL SELECT 'Weight' UNION ALL SELECT 'Height';

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = N'';

SELECT @sql = @sql + ',' + p.Animal + '_' + col
  + ' = MAX(CASE WHEN Animal = '''
  + p.Animal + ''' THEN ' + c.col + ' END)'
FROM dbo.PetStuff AS p
CROSS APPLY @cols AS c
GROUP BY p.Animal, c.col
ORDER BY p.Animal, c.col;

SELECT @sql = 'SELECT Owner ' + @sql
 + ' FROM dbo.PetStuff
 GROUP BY Owner;';

PRINT @sql;
-- EXEC sp_executesql @sql;

Can't really think of any way to do this without dynamic SQL.


Certificate Chain incomplete using Let's Encrypt and Certes (Azure webrole)

Question: I am trying to create a new Let's Encrypt SAN certificate using the Certes Library and hosting on a Azure WebRole. Everything has worked previously (many times) but now I am getting a cert error on Android and ssllabs.com shows a certificate chain incomplete error.
The certificate is created without error and I have explicitly set FullChain = true on the PfxBuilder but I am unsure how to check if the full chain is recorded in the certificate correctly without uploading the certificate together with a new deployment (I am not a cert expert).
On the Azure Web role both the created certificate and the required Let's Encrypt Cert (Let's Encrypt Authority X3) are listed in the webrole certificates. I only uploaded the created certificate Azure adds the Let's Encrypt Authority X3 cert itself.
I am unsure whether it is a problem with the certificate not recording the full chain or some configuration setting on the WebRole. When I go to Certificates in the Azure Management console I see the Let's Encrypt Cert but when I rdp into the role and look in the IIS Manager I cannot see the Let's Encrypt Cert under Server Certificates. I also cannot find it when I open the Certificates Management Console (certlm).
I am starting to think it is a problem with the WebRole but I am at a loss on what to check next.
Answer: You need to add additional <Certificate> element in your ServiceDefinition and ServiceConfiguration to specify the intermediate certs. See https://blogs.msdn.microsoft.com/azuredevsupport/2010/02/24/how-to-install-a-chained-ssl-certificate/
Edit due to broken link
View your certificate. For each of the intermediate certificate between the root cert and your certificate, export the certificate file.
Upload these certificate to Azure
Add the <Certificate> element. You can get the thumbprint from the Azure portal.
Comment: Link is broken.