Q: Nav Bar not showing after camera image capture I have been updating an app that I had some else build for me. In the updating, I am instituting storyboard segues, among other things, and have got the app almost complete. One little niggling issue is when I take an picture with the camera and the image is presented in the TakenImageView, the NavBar is not visible. Yet, if I go from the gallery to the TakenImageView, the NavBar shows! Ugh.
The image picker is presented from the HomeView, then moves to TakenImage after the user chooses camera or gallery.
I have tried to change to a prepare and perform Segue, but the segue doesn't fire from the gallery when selecting an image or from the camera's UsePhoto. The only way I can get the image to the TakenImageView is to manually segue via instantiating the view in code. See below...
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    TakenImageVC *takenVC = [storyboard instantiateViewControllerWithIdentifier:@"TakenImageVC"];
    takenVC.takenimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker pushViewController:takenVC animated:YES];
    //_pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    //[self performSegueWithIdentifier:@"TakenSegue" sender:self];
}

The prepare for segue has only these three. The top two are modal and are linking from the buttons. The TakenSegue is linking from the controller. Of course, I have the destinationController commented out, as the segue doesn't fire when using perform as noted earlier.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"InfoSegue"])
    {
        NSLog(@"Info Modal view");
    }
    if ([segue.identifier isEqualToString:@"HelpSegue"])
    {
        NSLog(@"Help Modal view");
    }
    if ([segue.identifier isEqualToString:@"TakenSegue"])
    {
        NSLog(@"Taken Segue");
        //TakenImageVC *takenVC = segue.destinationViewController;
        //takenVC.takenimage = _pickerImage;
    }
}

In trying different methods, I have added a NavigationController between the HomeView and TakenImageView and have changed the class to UIImagePickerController in the attributes.
Still, the NavBar doesn't show... but only after taking a photo with the camera!
And, yes, I have the navigation bar set to not hide... in both the HomeView and TakenView. This is in the viewWillAppear of both controllers.
Target is iOS7.1 and up. Running Xcode 7.
I'd appreciate some help from anyone with a hint as to what is causing the nav bar to not show from the camera and, of course, a way to fix it! Thanks!

A: I was unable to get the next view to show with a nav bar after the camera, even after trying numerous scenarios.
So, after seeing a hint in a different post, I removed the nav controller between the home and taken view, changed the attributes to none for Simulated Metrics/Top Bar and inserted a toolbar in it's place in the TakenView and two following views. Yes, it required more work in Storyboard and I had to add a label where the title should go, but it is all functioning. And, I didn't have to add any more code, except for changing the back or cancel buttons into unwindSegues.


Q: Parsing Soap XML I have a XML like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <SampleResponse xmlns="http://tempuri.org/">
            <SampleResult>
                <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
                                 xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
                    <NewDataSet xmlns="">
                        <Table diffgr:id="Table1" msdata:rowOrder="0">
                            <tag1>tag1 text</tag1>
                            <tag2>tag2 text</tag2>
                        </Table>
                        <Table diffgr:id="Table2" msdata:rowOrder="1">
                            <tag1>tag1 text</tag1>
                            <tag2>tag2 text</tag2>
                        </Table>
                    </NewDataSet>
                </diffgr:diffgram>
            </SampleResult>
        </SampleResponse>
    </soap:Body>
</soap:Envelope>

So i parsed above XML using Below Code:
string XMLresponse = e.response;
var XResult = XElement.Parse(XMLresponse);

var result = XResult.Descendants("Table")
    .Select(t => new
    {
        tag1 = t.Descendants("tag1").First().Value,
        tag2 = t.Descendants("tag2").First().Value,
    });

foreach (var res in result)
{
   string str = res.tag1; // here i am able get the response
}

listbox.ItemsSource = result;

But i am not able bind it to ListBox. i have a ListBox like below:
<ListBox x:Name="listbox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock Text="Sample" ></TextBlock>
                <TextBlock Text="{Binding tag1}" ></TextBlock>
                <TextBlock Text="{Binding tag2}" ></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

In the ListBox i have added a TextBlock, which is repeated twice. But the dynamical text blocks are not binding with data.

A: The two dynamic values are represented as fields, not properties. And since you can only bind to properties in XAML, you'll need to create a strong-typed data structure with your two properties, and select the values into that.
Something like:
class V
{
    public string tag1 { get; set; }
    public string tag2 { get; set; }
}

var result = XResult.Descendants("Table").Select(t => new V
             {
                 tag1 = t.Descendants("tag1").First().Value,
                 tag2 = t.Descendants("tag2").First().Value,
             });


Q: jQuery : XMLHttp Requests : Is this use of synchronous ajax bad? I know that in general the goal should be to avoid async: false.  However, in this situation, I want to understand whether it's worth tying things together to make it work, or if it is okay:
On my site's registration page, I have a JS/jQuery validation function on submission.  It has two AJAX queries, one for the username (to make sure it hasn't already been taken), and one for the email (to make sure they didn't submit an email already claimed by another user). In the validation function, I check each of these, along with lots of other things (passwords matching, check not blank, etc.), and when either of these pop up, a warning message states the issue.
Both of these ajax queries use async: false in order to ensure that the form doesn't submit before they are checked.
My question is,
how bad is this?  And if it's bad bad, then why?  I could put the work in to make a single function that checks both and has 4 return values for each of the different options, but that seems like a lot...  I know this may not be a solid coding question, but I'm new to coding and want to make sure I understand what the difference here means.
Thanks so much in advance.

A: Synchronous HTTP requests halt execution of subsequent code while they are en route. While browsers may no longer block the UI during this time, we're relying on the user's available bandwidth, network reliability, and the server's current load for the performance of our code. This is generally not good practice.
as i have found from this link may this will help you please look at this
https://softwareengineering.stackexchange.com/questions/112551/should-we-still-consider-a-synced-xmlhttprequest-bad-practice
you should also reffer to https://webtide.com/xmlhttprequest-bad-messaging-good/


Q: Crystal Reports Record Selection and Summary Field conflict I am really new to Crystal Reports and I am looking for any suggestions on how to approach the following issue:
I currently have a report that uses a record selection to limit the results by date. I would like to include in this same report a summary a total count of all the records (ignoring the record restriction). Unfortunately (although somewhat expected), the summary calculates the total after the record restriction is applied. Is there any way to get around this? In case my question is a bit unclear I've included a generic example below:

*

*I have a report that pulls info from a database with a total of 10 records.

*I select a specific date range, and it only returns 3 records

*I would like to include in the report footer that 3/10 records are getting returned.

A: This is bit tricky to perform in crystal reports as record selection is compulsory applied. However you can overcome this by using sub report.
Calculate the report footer using report.
This will surely work


Q: Logical constraints in CPLEX I am a beginner at using CPLEX and I have come across a problem with creating logical constraints (if ... then ...). I use IBM ILOG CPLEX Optimization Studio version 12.7. According to the the manual, it should be able to handle logical constraints by using "=>" (e.g., "if x>0 then y>=2" should become x>0 => y>=2).
The problem consists of assigning a start and end of a shift to employees (or a 0 if they are not working today). I am trying to create a variable that functions like an indicator for whether they are working in order to use it for assigning costs later.
I have boiled my code down to the following:
using CP;

tuple TimeSlot {
    key int day;
    key int slotNo;
}
{TimeSlot} TimeSlots = ...;
{int} mondays = {t.slotNo|t in TimeSlots:t.day==1};
int monMax = max(t in mondays) t;
range monRange = 0..monMax;

range allEmployees = 1..10;

dvar int monStart[allEmployees] in monRange;    //Start of monday shift
dvar int monEnd[allEmployees] in monRange;      //End of monday shift
dvar int monAtWork[allEmployees] in 0..1;       //Binary

//minimize ...

subject to{
    forall(t in allEmployees)
        {monStart[t] > 0 && monEnd[t]>0} => monAtWork[t] = 1; //Get error here
}

The error I get is syntax error, unexpected =. I have tried both splitting and flipping the constraint (e.g., monStart[t] == 0 => monAtWork[t] = 0;) to no avail. Am I missing something?

A: Looking at the provided OPL examples (e.g. BasketballScheduling\acc.mod) I think that the 'then' part defining the constraint should have '==' rather than '='. It is not an assignment, but declaring that the two must be equal.

A:  using CP;

tuple TimeSlot {
    key int day;
    key int slotNo;
}
{TimeSlot} TimeSlots = {<1,1>,<2,2>};;
{int} mondays = {t.slotNo|t in TimeSlots:t.day==1};
int monMax = max(t in mondays) t;
range monRange = 0..monMax;

range allEmployees = 1..10;

dvar int monStart[allEmployees] in monRange;    //Start of monday shift
dvar int monEnd[allEmployees] in monRange;      //End of monday shift
dvar int monAtWork[allEmployees] in 0..1;       //Binary

//minimize ...

subject to{
    forall(t in allEmployees)
        (monStart[t] > 0 && monEnd[t]>0) => monAtWork[t] == 1; //Get error here
}

works fine


Q: How to create a Flash Movieclip via a web interface? Forgive me if this is not the correct place to ask such a question.
Basically, I am looking for a way to allow someone to easily (at least, easier then diving into Flash) create a basic Flash animation (movieclip) with some placed image assets and text, all via a web interface.
I was thinking along the lines of using jQuery to allow drag and drop assets, of which you'd "record" the co-ordinates and relay that to Flash somehow to create the SWF file.
Or would it be better to create a tool in Flash (surely making operations easier) and then have some kind of "save" button to render out the SWF?
I'm totally open to suggestions.
Thank you

A: If you really need to produce a stand-alone SWF file (and not just a config file for you own "player"), I would probably do it like this;
1) Create your editor in whatever system you feel like (flash, jquery etc).
2) Build a config file in the client. This is used, together with all the resources the user added, to play back the animation.
3) Upload said assets and config file to your web server.
4) Use the flex compiler (on the server) to produce the resulting SWF, combining your player with generated AS3 which embeds the uploaded resources as needed, to make it available to the player.
5) Give the user a download link for the newly generated SWF file.

A: I don't think there is any swf compiler available for Flash (actionescript). You may create a swf that allows users to create an animation, save it as a home-made vector format, and then replay it. But I don't believe you can create and independant swf file with only the created animation in it.
Just think about a player in Flash, and a format that the player will read (xml, json, name it...). You can either generate the input with jQuery or Flash, and then feed it into your player to display it. You will eventually need two files.

A: Apparently this library allows you to compile SWFs at runtime. I haven't used it myself (yet) and don't know how stable or flexible it is, but it appears to be what you're looking for. I'd recommend giving it a spin and seeing if it's sufficient.
I'm not exactly sure how it saves the file, so you might run into security problems since it's a web application. Hopefully it should be OK though.


Q: FCM messages are not delivered when the device is started and it has a password On android, the messages do not arrive after I restart my device and have a password, if he has no password he receives the message
I would like to understand this situation, whether it is for security or really is a sdk failure


Q: need to add a col conditionally I have one table which I want to join with another. I would create a commmand in Crystal reports to get this output and change the names in the formulas easily.
I need something like this: only I need the sum from the second tbl.
Select
    *
from
    rapklib.shpfrt a
    left outer join ralib.shpfrtc b

where idord# a = idord# b

the first is created as
CREATE VIEW
    Ralib.shpfrt
AS
    SELECT
        T01.IDORD#,
        T01.IDDOCD,
        T01.IDPRT#,
        T01.IDSFX#,
        T01.IDSHP#,
        T01.IDNTU$,
        T01.IDENT# ,
        ( T01.IDNTU$ * T01.IDSHP# ) AS LINTOT ,
        T02.IARCC3,
        T02.IAPRLC ,
        T01.IDORDT,
        T01.IDHCD3
 FROM
    STDTA.OEINDLID  T01
    INNER JOIN STDTA.ICPRTMIA T02 ON T01.IDPRT# = T02.IAPRT#

WHERE t01.iddocd > 20131231

the second is the same as the first but only will contain rows when there is a value in idprt# = 'FRTCRDM' then the sum we get there means there was a credit given for shipping charge (freight).
So I want to join them for use in a crystal report that will give me all the rows of the first but bring in the FRTCRDM amounts as well. Currently I am joining them when order# are = and thus only getting orders which have a FRTCRDM.


Q: Disqus Comment System [Wordpress] - Change the word "Comment" i have installed Disqus comment system on one of my wordpress blogs, but i want the comment numbers to show as 0 instead of 0 Comments or 12 instead of 12 Comments. Previously there used to be an Appearance section in Disqus admin that used to have an option to change this output as was suggested in answer to this question. But seems like the Appearance section has been taken off by Disqus. Is there any other way to achieve this (without messing with the plugin code, ofcourse.) ??
UPDATE:
Well, looked into the plugin source as well but no use, seems like they are updating it using javascript. After enabling Reactions now it returns 0 comments and 0 Reactions.
UPDATE#2:
okie so i at last found where it is coming from ... the plugin basically includes a count.js files from yoursite.disqus.com\count.js?some wierd parameters, and the js file looks something like this:
var DISQUSWIDGETS;

if (typeof DISQUSWIDGETS != 'undefined') {
    DISQUSWIDGETS.displayCount({"showReactions": true, "text": {"and": "and", "reactions": {"zero": "0 Reactions", "multiple": "{num} Reactions", "one": "1 Reaction"}, "comments": {"zero": "0 Comments", "multiple": "{num} Comments", "one": "1 Comment"}}, "counts": [{"reactions": 0, "uid": 1, "comments": 0}, {"reactions": 0, "uid": 0, "comments": 0}, {"reactions": 0, "uid": 3, "comments": 0}, {"reactions": 0, "uid": 2, "comments": 0}, {"reactions": 0, "uid": 4, "comments": 0}]});
}

the worst part is we can't even change the code in the js file as it is hosted on disqus itself.

A: Alternatively you can "hack" the code of Disqus. I'll try to explain what I did step-by-step:

*

*Get the newest file of the main disqus function. It should be something similar to this:
http://disqus.com/forums/(your-site-id)/count.js

*Copy that script somewhere, you can "beautify it" to make it more readable. Than find and change the displayCount function to whatever you want to like this:
c.displayCount = function (a)
{
  for (var b, c, e, g, f = 0; f < a.counts.length; f++)
  if (b = a.counts[f], c = h[b.uid]) e = b.comments === 0 ? "0 drivels" : b.comments == 1 ? "1 drivel" : "{num} drivels",
  g = e.replace("{num}", b.comments),
  a.showReactions && (e = b.reactions === 0 ? a.text.reactions.zero : b.reactions == 1 ? a.text.reactions.one : a.text.reactions.multiple, e !== "" && (g += " " + a.text.and + " " + e.replace("{num}", b.reactions))),
  c.element.innerHTML = g
};

(note the drivels ;)

*Save (upload) the whole file somewhere on your server and remember the path

*Use Wordpress administration to edit the Disqus plugin - file disqus-comment-system/disqus.php and find line that contains concatenated url withthe word count.js. It is in about 3/4 of the file. As of now the line looks like this but it might change in the future:
s.src = '//' + '<?php echo DISQUS_DOMAIN; ?>/forums/' + disqus_shortname + '/count.js';

*Make this link point to your newly-uploaded file like this (I used relative URL):
s.src = '/wp-include/custom/disqus-count.js';

*Save it and profit! It took me more than an hour to figure this out so I hope this actually helps someone (I needed to translate these messages into my native language). A great benefit of this approach is the fact that if your language uses different word forms for different numbers (other than 0, 1 and more), you can script it in.

A: You should be able to hide it via JavaScript.
Something along these lines:
node = document.getElementsByClassName("dsq-comment-count")[0].childNodes[0]
node.nodeValue = node.nodeValue.replace("Comments", "")

A: The official answer is here: http://help.disqus.com/customer/portal/articles/565624#customizing-link-text

*

*Go to http://YOUR-SITE.disqus.com/admin/settings/?p=general

*Edit Comment Count Link section as you need.

*That's all!


Q: Trouble with for loops in Python 3: getting the index in string2 of an element from string1 I am trying to write a program that will take a file and encode it using the Viginère cipher.  I've run into a little bump with indices.  I've defined my strings text and alphabet like this:
import string

alphabet = string.ascii_lowercase
ciphertext = open("black_hole.txt","r")
ciphertext = ciphertext.read()
text = ""

for i in range(len(ciphertext)):
    if ciphertext[i].isalpha() == True:
        text = text + ciphertext[i]

My trouble starts when I try to write this for loop:
for i in range(len(text)):
    print(alphabet.index(text[i]))

I get the ValueError "substring not found".  I find this strange since text[i] is always a letter as well as a string.
Please let me know if I haven't posed this question clearly enough!

A: for i in range(len(text)):
    print(alphabet.index(text.lower()[i]))

just add lower() and it will work

A: As stated by Kevin in comments, you are probably missing uppercase.
You can use alphabet[ord(text[i].lower()) - ord('a')] instead of index.


Q: Count by ratio and then group by MSQL I have a table like
ID Name

1 ABC
1 DEF
1 VVV
1 BBB
1 BCD
2 ZZZ
2 BAA
3 AAA
3 BBB
3 BBC

I want to get the ratio of all the names that start with A to All the names that start with B group by ID.
So the output should be
ID Ratio

1  0.5
2  0
3  0.33

.
SELECT (ID, (SELECT COUNT(*) FROM `table` WHERE name LIKE 'A%') /
            (SELECT COUNT(*) FROM `table` WHERE name LIKE 'B%')) AS `ratio` from table Group by ID

does not give me the right answer. It takes the total ratio of A/B across all ID's into account and writes that number for all the ID's.

A: I'd try:
SELECT ID, CASE WHEN B = 0 THEN 0 ELSE A/B END AS Ratio FROM
    ( SELECT ID,
         SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END) AS A,
         SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END) AS B
      FROM my_table GROUP BY ID ) AS grouped;

The inner SELECT gets the group IDs, and for every ID, the number of items beginning with A and those beginning with B.
The outer SELECT (you can omit it if you're sure that there'll always be at least one B-row) checks that the ratio makes sense before attempting to calculate it.
Or else:
SELECT ID, COALESCE(SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END)
        /  SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END), 0)
FROM my_table GROUP BY ID;

This takes advantage of the fact that, if the number of B-rows is zero, the division will yield NULL. The COALESCE transforms that NULL in a 0.

A: This will do it:
SELECT
    id,
    SUM(IF(name LIKE 'A%',1,0))/SUM(IF(name like 'B%',1,0))
FROM `table`
GROUP BY ID


Q: Drawer is not opening in react-native I am using drawer navigation in material top navigation.
This is my drawer navigation code
import { createDrawerNavigator, createStackNavigator } from "react-navigation";
import { UserProfileComponent } from "../components/standalone/userProfile/userProfile.component";
import { RecordMeetingComponent } from "../components/standalone/recordMeeting/recordMeeting.component";
import { ChatBotComponent } from "../components/standalone/chatBot/chatBot.component";
import DrawerScreen from "../components/shared/drawerToggler/drawerToggle.component";
import userDashBoardTabsStack from "./userDashBoardTabs";

const userDrawerNavigator = createDrawerNavigator({
    Home:{
        screen: userDashBoardTabsStack,
        navigationOptions:{
            drawerLabel: "Home"
        }
    },
    Record: {
        screen: RecordMeetingComponent,
        navigationOptions:{
            drawerLabel: "Record"
        }
    },
    Profile: {
        screen: UserProfileComponent,
        navigationOptions: {
            drawerLabel: "My Profile"
        }
    },
    ChatBot: {
        screen: ChatBotComponent,
        navigationOptions: {
            drawerLabel: "Chat Bot"
        }
    },
    },{
        initialRouteName: "Record",
        contentComponent: DrawerScreen,
        drawerWidth: 300
    }
)
export default userDrawerNavigator;

This is my tab navigation
import { createMaterialTopTabNavigator } from "react-navigation";
import { UserDashboardTodayTab } from "../components/standalone/usersTabs/today/today.component";
import { UserDashboardWeekTab } from "../components/standalone/usersTabs/week/week.component";
import { UserDashboardMonthTab } from "../components/standalone/usersTabs/month/month.component";

const userDashBoardTabsStack = createMaterialTopTabNavigator({
        today:{
            screen: UserDashboardTodayTab,
            navigationOptions: (navigation)=>({
                title: "TODAY"
            }),
        },
        week: {
            screen: UserDashboardWeekTab,
            navigationOptions: (navigation)=>({
                title: "WEEK"
            }),
        },
        month:{
            screen: UserDashboardMonthTab,
            navigationOptions: (navigation)=>({
                title: "MONTH",
                headerTitle: "#000000"
            })
        }
    },{
        order: ["today", "week", "month"],
        tabBarOptions : {
            activeTintColor: "#000000",
            inactiveTintColor: "#ADB2BF",
            pressColor: "#25B7AF",
            indicatorStyle: {
                backgroundColor: "#25B7AF",
            },
            activeBackgroundColor: "#25B7AF",
            style: {
                fontFamily: "nunito_regular",
                backgroundColor: "#ffffff"
            }
        },
    swipeEnabled: true,
    animationEnabled: true,
    lazy: true,
    backBehavior: "initialRoute"
})

export default userDashBoardTabsStack;

I am calling these two in a createStacknavigator
import { createStackNavigator } from "react-navigation";
import userDrawerNavigator from "./userDrawer";
import React from "react";
import { TouchableOpacity } from "react-native";
import Icon from "react-native-vector-icons/Feather";

const OnboardingStack = createStackNavigator({

    userDrawerNavigator: {
            screen: userDrawerNavigator
        },
    },{
        navigationOptions: ({ navigation }) => ({
            title: 'ReactNavigation',  // Title to appear in status bar
            headerLeft:
            <TouchableOpacity  onPress={ () => { navigation.dispatch(DrawerActions.toggleDrawer())} }>
                <MenuImage navigation={ navigation }/>
            </TouchableOpacity>,
            headerStyle: {
                backgroundColor: '#333',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
              fontWeight: 'bold',
            },
        })
    },
    {
        initialRouteName: "userDrawerNavigator",
        headerLayoutPreset: "center",
    }
)

const MenuImage = ({navigation}) => {
    if(!navigation.state.isDrawerOpen){
        return <Icon name="menu" color="#000000"/>
    }else{
        return <Icon name="arrow-left" color="#000000"/>
    }
}

export default OnboardingStack;

And iterating these components in a switch navigator
import { createSwitchNavigator, createAppContainer } from "react-navigation";
import { SplashComponent } from "../components/standalone/splash/splash.component";
import AuthStack from "./loggedOut";
import UserStack from "./loggedIn";
import OnboardingStack from "./freshInstall";

export const AppStack = createAppContainer(createSwitchNavigator(
    {
        Splash: SplashComponent,
        LoggedIn: UserStack,
        LoggedOut: AuthStack,
        Onboarding: OnboardingStack
    },
    {
        initialRouteName: "Splash"
    }
))

This is my custom component for drawer
class DrawerScreen extends React.Component {

  navigateToScreen = (route) => () => {
    const navigateAction = NavigationActions.navigate({
      routeName: route
    });
    this.props.navigation.dispatch(navigateAction);
    this.props.navigation.dispatch(DrawerActions.closeDrawer())
  }

  render () {
    return (
      <View>
        <ScrollView>
          <View>
            <View >
              <Text onPress={this.navigateToScreen('RecordMeetingComponent')}>
                Record
              </Text>
            </View>
            <View>
              <Text onPress={this.navigateToScreen('UserProfileComponent')}>
               My Profile
              </Text>
            </View>
            <View >
              <Text onPress={this.navigateToScreen('ChatBotComponent')}>
              Chat Bot
              </Text>
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }
}

DrawerScreen.propTypes = {
  navigation: PropTypes.object
};

export default DrawerScreen;

But the drawer navigation is not appearing in the screen. What am I doing wrong here?


Q: Launch PowerShell as administrator in current directory New to PowerShell.
I need to launch PowerShell as Administrator in the current directory.
From what I have heard about the amazing abilities of PowerShell, I expect I should be able to do this without a registry hack?


Q: Glide for Android: How to include GIFs from Google Drive? I am trying to include GIFs in my android application. My GIFs are shared as a document on Google Drive with public access enabled. Currently, I'm trying to use Glide to include the GIFs.
 Glide.with(parent.getContext())
            .asGif()
            .load("https://drive.google.com/uc?id=1-QKgZ76K3EZQlbXyY3wI57FA8k31JmrA")
            .into(imageView);

However, although there is no error, the GIF does not display on my phone, even after a long time(internet issues shouldn't be the problem).
It appears that this is only a problem for GIFs on google drive. Trying to show an internet GIF such as this one works on my Android phone.
How can I show GIF files on Google Drive with Glide on my Android device?

A: It should work. Because Glide trying to fetch image which type you specified. I just tried it and its work. it loads too late. If you wait a bit, you will see that it can be loaded. You can test it more easily if you upload a lower resolution gif file to Drive.


Q: Hadoop Name node recovery in CDH3 cluster I am using CDH3 Cloudera Pseudo distributed mode cluster.It was working fine before. but currently i am   not able to do any hadoop commands,hive queries,pig scripts.
Looks like the  namenode gets corrupted.
I tried sudo jps and found that namenode daemon is not running.
It only shows
    DataNode
Jps
RunJar
HMaster
SecondaryNamenode

What is the root cause here? How do i recover my name node?


Q: Recover simulated affine transformation for matched asift features (Morel's implementation) Has anyone tried to recover the simulated affine transformation for the ASIFT feature detector? (From the author's implementation). In the original paper the simulated affine is clearly recovered by the equation 2.2 but I cannot seem to find a clear point where this is performed. Has anyone tried before? The function compensate_affine_coor1 in compute_asift_keypoints.cpp seems to be what I'm looking for but the scale seems to be normalized plus, the center of coordinates to perform the transformation is not clear to me.

A: It is performed in function you mentioned. Center coordinates are shifted because when you rotate image, top-left corner(origin) is moved, so they have to compensate it. And scale doesn`t change at all.


Q: Best way to endian swap many structures in C++ I have a lot of C++ struct that look kind of like this:
typedef struct {
    UINT32 foo    : 5;
    UINT32 spare0 : 27;
    double bar;
}  data;

or this
typedef struct {
    double foo;
    double bar;
} data2;

I'm currently endian swapping all structures by each field individually in a single function call, but I was wondering if there was some more efficient way of doing this without manually swapping each individual field for each struct.
Would the only way to do this is to create a function that requires the size for each field so the function would know how many bits to swap? Other methods are welcome as well.
Thank you!


Q: Mysql: Counting occurences in a table, return as a single row I have a table listing some organizations, and some details, as the country they are in.
I need to count the number of organizations in each country, and I managed that with this query:
SELECT COUNTRY, COUNT(*) AS ORGANIZATIONS FROM ORGANIZATION GROUP BY COUNTRY

This gives me a result set like this:
COUNTRY | ORGANIZATION
--------+-------------
UK      | 12
FR      | 7
NL      | 9

This is good, but a better result I'm looking for is a single row result, like this:
UK | FR | NL
---+----+---
12 | 7  | 9

Any ideas on how to do that in MySQL alone?

A: This can't really be done with a single SQL statement as it would require an unknown number of columns.
I would be inclined to say that this is just formatting of the returned data, and hence probably better places in the calling script.
However it is easy to do if you have a fixed number of countries that you are interested in. But with several sub queries it is not likely to be that efficient.
What can be done is to dynamically build up the SQL, but that is messy.
Alternative would to GROUP_CONCAT the countries details into a single row:-
SELECT GROUP_CONCAT(CONCAT_WS('##', COUNTRY, ORGANIZATIONS ))
FROM
(
    SELECT COUNTRY, COUNT(*) AS ORGANIZATIONS
    FROM ORGANIZATION
    GROUP BY COUNTRY
) sub0


Q: Deleting file from internal storage in Android I was saving file to internal storage now I want to delete it. The problem is, I don't remember the name of that file so I can't use this myContext.deleteFile(fileName); approach. How to get the name of that file and delete it?

A: When you use file methods from Context, Android saves that file into app's directory (and encrypt it, compared to File.()) method). So, you can just clear app data and that file will be removed


Q: Python 3 not rendering html on browser If I run this script on terminal, it outputs the html template. But on browser after serving it using python3 -m http.server 8000, it just display the exact script (not rendering). I've installed packages on requirements.txt and interpreter set to Python 3.x, am I missing something here?
home.py
#!/usr/bin/env python3

import os
import sys
from jinja2 import Environment, FileSystemLoader

# Get current url
try:
    url = os.environ['SCRIPT_NAME']
except KeyError:
    url = ''

print('Content-type: text/html\n')
env = Environment(loader=FileSystemLoader('templates'))

template = env.get_template('home.html')
print(template.render(url=url))

A: Your script could work as a CGI script, since it outputs a HTTP header, followed by the HTML content.
python -m http.server, by default, does not run CGI scripts for security, but if you add the --cgi switch, it will, provided that the scripts are in the cgi-bin directory relative to the directory you start it from.
In other words:

*

*create a cgi-bin directory

*move home.py to cgi-bin/home.py

*run python3 -m http.server --cgi 8000

*navigate to http://127.0.0.1:8000/cgi-bin/home.py
When working with CGI scripts, you might want to enable the (soon-to-be-deprecated) cgitb handler too.
Anything more intricate than that, and I would recommend looking at the Flask application framework instead, though.


Q: Register to GCM in background what I'm trying to do is run some scripts let say "in background" and display external page.
I have my activity
public class MyApp extends DroidGap
{
   @Override
   public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("http://external.com/");
    }
}

I'm able now only to load my internal page where scripts are included or load external url.
What I want to do is
public class MyApp extends DroidGap
{
   @Override
   public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // run my gcm script to register
        super.loadUrl("http://external.com/"); //load prepared page
    }
}

but I don't know if script should/can be run from java code. Or maybe this is wrong solution and I should load my external page from js? I'm using cordova 2.5

A: If you planning to support IOS (APNS) and Android (GCM), you can use PushPlugin https://github.com/bobeast/PushPlugin
It is easy to setup, where you can register for GCM using javascript and having the same interface for Android and IOS.


Q: Cannot import python package installed with apt-get On ubuntu (specifically the python:3.7.3-stretch base dockerimage), I run:
$ pip install pandas
$ python -c 'import pandas'
$

And that works fine.
Then, I try to install the package pygrib (which isn't installable with pip), via apt-get, python3-grib. I try:
$ apt-get update
$ apt-get install python3-grib
$ python -c 'import pygrib'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'pygrib'

(Omitting the output of the installs for brevity).
Why can't I import pygrib? I am not inside a virtual environment.

A: The first thing I would try, would be to double check that the python you're calling is the same that you've installed pygrib into

*

*$ which python

*$ python -c "help("modules")"

*$ python -c "help("modules pygrip")"
(to inspect which python you're calling, and which packages are installed there).
If that's not working, then there's something off with the ubuntu package - so I'd then try installing from source instead;
From https://github.com/jswhit/pygrib
Clone the github repository, or download a source release from https://pypi.python.org/pypi/pygrib.

Copy setup.cfg.template to setup.cfg, open in text editor, follow instructions in comments for editing. If you are using the old grib_api library instead of the new eccodes library, be sure to uncomment the last line setup.cfg.

Run 'python setup.py build'

Run 'python setup.py install' (with sudo if necessary)

Run 'python test.py' to test your pygrib installation.


Q: Delete contents of textbox and automatically deleting another I have 2 input box fields, one linked to an autocomplete and the other is hidden
I have an action on select that takes the id of the selected item into the hidden field.
code:
    $('#id_emp_name').autocomplete({
    source: '/mycompany/employees.json',
    minLength: 1,
    dataType: 'json',
    max: 12,
    select: function(event, ui) {
        $('#id_emp_id').val(ui.item.id);

    }
});

I want to change it so that whenever I delete contents (even a single character) on the autcomplete textbox it would set the hidden textbox's to ''

A: Would this work for you?
$('#id_emp_name').autocomplete({
    source: '/mycompany/employees.json',
    minLength: 1,
    dataType: 'json',
    max: 12,
    select: function(event, ui) {
        $('#id_emp_id').val(ui.item.id);

    }
}).keyup(function(){
    $('#id_emp_id').val('');
});

You may need to put some conditions on it of course.


Q: How to load configurations at Vue JS app start I want to load some configuration from an API call before any page load happens. For this I added my api call function in main.js but it returns promise and page get loaded before my global api completes. I want to load the global configuration first as my backend services URLs will keep on changing.
my main.js

import globalConfigLogic from '../appStarter/globalConfig-logic';
import globalConfigDetails from '../appStarter/app-starter.js';

// API Wrapper - Global Mixin
Vue.mixin(apiWrapper)
Vue.use(VeeValidate);
Vue.config.productionTip = false;

 globalConfigLogic.getGlobalConfiguration(
   globalConfigDetails.globalConfigHost,
   globalConfigDetails.globalConfigHostPort,
   globalConfigDetails.globalConfigKeys
 );
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

The functions is just making an API call and converting the result in hashmap and giving it back.

A: If loading your configuration returns a promise, simply put the creation of the Vue instance in the .then() {} code.


Q: How can I set up gulp to run identically in Visual Studio 2017 and msbuild without having to change my build scripts? I'm struggling to get set up with gulp in Visual Studio 2017. I'm not sure where I'm going wrong but there are a few things I'm confused about and I can't really find any online resources that are of any use.
The build system I'm using is CruiseControl.NET and I would like gulp to work with it.
This is what I've done so far:

*

*Installed Visual Studio 2017 with .NET Core cross-platform development and Node.js development selected (amongst other options).

*Created a new project

*Added a gulpfile.js file to the project

*Right-click on the file and choose Task Runner Explorer
In the Task Runner Explorer I get the error Failed to load. See output window (Ctl+Alt+O) for more information..
Then if I do the following:

*

*Open the Node.js Interactive Window

*Run the command .npm install --global gulp-cli

*Close Visual Studio and open it back up again
In the Task Runner Explorer, I then get the message (No tasks found).
First off, is this the correct way to set up Gulp in Visual Studio 2017?
The reason I'm asking this is because I'm not sure why I need to prefix commands with a period character (ie .npm as opposed to npm).
I'm also not sure where gulp was installed because I can't find it in the path C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Web\External\node_modules.
Because of this I can't really set up CruiseControl.NET.

A: The way I'm handling this is to first use the Web Essentials 2017 extension. This installs the Bundler & Minifier tool, which then adds a bundleconfig.json file to your project. Right-click on this file, go to the Bundler & Minifier menu item and you will see an option in there to Convert To Gulp.
Selecting convert to gulp will create the necessary gulpfile.js and also install the npm packages required for using Gulp. Wait for all of the npm packages to install and you can then right click on gulpfile.js, select Task Runner Explorer and you should be ready to set up Gulp-based tasks. If you see gulpfile.js failed to load message, npm packages may still be installing (check the progress bar on the VS 2017 status bar). Hit the Refresh icon in Task Runner Explorer when all packages are installed and the error should vanish.
There's probably a more manual way to add Gulp support but I find this more automated method ensures all the tooling is wired up to work properly and I don't miss anything.
I gleaned all this information from the awesome Microsoft Docs site, specifically this page on Bundling & Minification. There's also a Using Gulp section in there that may provide additional details for your situation.
https://learn.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification

A: Microsoft have now added documentation on how to get gulp running:
https://learn.microsoft.com/en-us/aspnet/core/client-side/using-gulp
Make sure you update Visual Studio 2017 to the latest version as it now comes shipped with Node.js, NPM and Gulp (you don't need to pick "Node.js support" when installing Visual Studio for this to work).
Create an npm Configuration File (package.json) in your project folder and edit it to reference gulp:
{
  "version": "1.0.0",
  "name": "example",
  "private": true,
  "devDependencies": {
    "gulp": "3.9.1"
  },
  "scripts": {
    "gulp": "gulp"
  }
}

In the project folder, create a Gulp Configuration File (gulpfile.js) to define the automated process.
Add the following to the post-build event command line for each project requiring gulp support:
cd $(ProjectDir)
call dotnet restore
npm run gulp

To run the tasks in Visual Studio 2017, open the Task Runner Explorer (View > Other Windows > Task Runner Explorer).
Then on the build server just install Node.js and ensure the path to node is added to the environmental path variable then when the build server builds the project gulp will run too!

A: I found the solution here. More information on that part of VS from Mads himself.
You have to force Visual Studio run with your Node.js version:
Go to Tools > Options in Visual Studio 2017
Go to Projects and Solutions > External Web Tools
Add the following path: C:\Program Files\nodejs


Q: Clean up Array of words I have a function that strips html and places the words in an array and then uses array_count_values. Im trying to report the number of occurences of each word. The array outputed is very messy. I tried to clean it up, and I'm getting nowhere. I want to remove telephone numbers, and for some reason phrases are pushed together. Also the first array seems to be null, but isset() or empty() doesn't seem to unset it.
$body = $this->get_response($domain);
                $body = preg_replace('//i', '', $body);
                $body = preg_replace('##i', '', $body);

                $openTag = '';
                $start = strpos($body, $openTag);
                $start += strlen($openTag);

                $closeTag = '';
                $end = strpos($body, $closeTag);

                // Return if cannot cut-out the body
                if ($end <= $start || $start === false || $end === false) {
                    $this->setValue('');
                    return;
                }

                $body = substr($body, $start, $end - $start);
                $body = preg_replace(array(
                       '@@si',    // Strip out javascript
                       '@@siU',     // Strip style tags properly
                       '@<![\s\S]*?--[ \t\n\r]*>@',         // Strip multi-line comments including CDATA
                       '/style=([\"\']??)([^\">]*?)\\1/siU',// Strip inline style attribute
                       ), '', $body);

                $body = strip_tags($body);
                $body = array_filter(explode(' ', $body), create_function('$str', 'return strlen($str) > 2;'));
                $body = array_map('trim', $body);
                $words = $body;

                $i = 0;

                $words = array_count_values($words);

                foreach($words as $word){

                    if (empty($word)) unset($words[$i]);
                    $i++;

                }

                echo "
";
                    print_r($words);
                    echo "
";

outputs
Array
(
    [] => 28
    [333.444.5555] => 1
    [facebook] => 2
    [twitter] => 2
    [linkedin] => 2
    [youtube

                googleplus] => 1
    [About

    History
    Our] => 1
    [Mission
    Who] => 1
    [This
     That
     Other] => 1
    [Us

English

    FA
    Football] => 1
    [Media
    Pay] => 2
    [Per] => 4
    [Think
    Fast] => 2
    [Marketing
    Design] => 1
    [Consulting

Case] => 2

A: I'm afraid explode(' ', $body) is not enough because space is not the only white space character. Try preg_split instead.
$body = array_filter(preg_split('/\s+/', $body),
            create_function('$str', 'return strlen($str) > 2;'));


Q: Is there any form designer available for Google Android I am a new comer in Android development, I have downloaded and installed the Android SDK, but not find any GUI or Form designer, can any one know about some Form designer in for Android, Thanks in advance.

A: As d. correctly mentioned the built-in designer does not truly represent your view.
And if we keep in mind that even after 4 years of trying, Microsoft's equivalent for their XAML code still doesn't reach minimum usefulness level, I would strongly recommend to go manual. It's faster, much more difficult but equally rewarding. Once you get a hang of editing the XML files manually the development becomes much easier and WAY faster in my humble opinion.
Regards

A: This answer is very late to the game but each new release of the Eclipse Android plugin improves the layout GUI editor. The one released yesterday (9.0.0) is light years ahead of the original tools which were awful.

A: The form designer is part of the Android Development Tools (ADT) Plugin for Eclipse which comes with the Android SDK.

A: Google has not announced any plans for a wysiwyg designer for Android app development. However, there is a tool available for this. Check out this link http://www.designerandroid.com/?p=165


Q: Python Calling Current Directrory I am using fasitai library and when ı tried the loading model ı want to take model from current directory.
learn = load_learner('This arg. have to my current directory','model.pkl')

I tried os.get_cwd() and ' ./ ' but they aren't worked. Thanks

A: I found the solution
learn = load_learner('','model.pkl')

the first arg. had to be space '' .


Q: RoR NameError - Ruby on Rails MySQL NameError in GenresController#index
uninitialized constant GenresController
RAILS_ROOT: C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki
I've created a table called Genres and when I try to connect to it via local host I get the above error.
Any ideas?

A: With all the questions you're asking I believe you're an absolute beginner regarding ROR. Perhaps you should visit some tutorials to learn rails.
I don't know what your genre model describes, but I think it will have a name.
Basic steps for a basic genre model:

*

*Delete the table for your genres if created manually (with SQL code)
DROP TABLE genres;

*generate a complete scaffolding for genres:
$ ruby script/generate genre name:string
$ rake db:migrate

*Now you have a complete controller for all CRUD actions for a simple genre model
If I were you I would read some tutorial about RoR, because you make the impression that you don't understand RoR or the MVC principle behind it. A good start would be: http://storecrowd.com/blog/top-50-ruby-on-rails-tutorials/

A: You need to generate a controller to handle the index action when your browse your application on localhost
ruby script/generate controller genres index

run that from your console within your application and it will generate the GenresController with the action index (it will be an empty action but you shouldn't see an error when browsing http://localhost:3000/genres/)

A: file
C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki/app/controllers/genres_controller.rb

must be present


Q: How to intercept exe files launch from windows explorer? i want to be notified when when user trys to open a file from the explorer.
How could this be done?
I tired hooking some winapi in the explorer.exe with no hope.
I also want to intercept this call and cancel it.

A: You might want to have a look at a similar question: Intercept windows open file
Also for the people asking why someone would want to do this or immediately jump to malware conclusions. There are a number of legitimate uses for this. Especially if you are creating a B2B product that deals with automation or control over a customer's PC environment.


Q: React Typescript ESLint "extends" parsing error I have a react typescript code that looks like the following in Button.tsx:
   import * as React from 'react';

   type ButtonOwnProps<E extends React.ElementType = React.ElementType> = {
     children?: React.ReactNode;
     variant?: 'contained' | 'outlined';
     as?: E;
   };

I am getting the following eslint error:
Parsing error: Unexpected token, expected ","

  1 | import * as React from 'react';
  2 |
> 3 | type ButtonOwnProps<E extends React.ElementType = React.ElementType> = {
    |                       ^
  4 |   children?: React.ReactNode; eslint

Can anyone help me understand where I did wrong?


Q: How to filter a RecyclerView using Kotlin? I just started to use kotlin and room database, in my fragment i have a RecyclerView and an EditText which i would use as search for the RecyclerView. The RecyclerView's adapter is inside my ViewModel observable and i've actually set a TextWatcher to my EditText but as the data of the RecyclerView comes from my room DataBase how should i set that filtering?
When the EditText is empty i should return items from the LiveData observable..
Here is my Fragment code:
private lateinit var recyclerView: RecyclerView
private lateinit var txtSearch: EditText
private val articoliViewModel: ArticoliViewModel
    get() = (activity as MainActivity).articoliViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.recyclerView)
    txtSearch = view.findViewById(R.id.txtSearch)

    val adapter = ArticoliListAdapter()
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(activity)

    articoliViewModel.articoli.observe(viewLifecycleOwner) { articoli ->
        // Update the cached copy of the words in the adapter.
        articoli.let { adapter.submitList(it) }
    }

    txtSearch.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })

}


Q: Injecting javascript into page via url I'm trying to run a javascript code via url to change values of the form in the page.
Here is the content of the HTML page.

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>

Now, I enter the following value in the URL section of chrome:
javascript:document.getElementById('name').value = 'string1';

What happens is my whole page will go blank and only the value "string1" will be displayed in the page.
However, running the following code works properly:
javascript:document.getElementById('name').value = 1;

It will change the value of the name field to 1.
I'm wondering what is causing this problem.
Note: The purpose of this work is to inject code into webview in android.
Any advice is appreciated.

A: Try this.
javascript:document.getElementById('name').value = 'string1'; undefined;

Tack on a 'undefined;' to any script that returns a string.

A: That is because you are using single quotes after the attribute value
value=''

and you changing it's value in javascript using
document.getElementById('name').value='string1';

so the html becomes
<input type='text' id='name' value=''string1''

you can fix it using
value=""

or using
document.getElementById('name').value="string1";

A: well i tried the following code

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>
<button onclick="change()">Click me</button>

and it works just fine the problem is in your script
do you created a function to change the value or just putted the code in a script tag like this


Q: What is the advantage of dynamic memory control? For example, I want to make a stack. I can do it in that way, using the dynymic memory control, with new and delete opereations:
#include <iostream>

using namespace std;

struct List
{
    int x;
    List *Next,*Head;
};

void Add(int x, List *&MyList)
{
    List *temp=new List;
    temp->x=x;
    temp->Next=MyList->Head;
    MyList->Head=temp;
}

void Show(List *MyList)
{
    List *temp=MyList->Head;

    while (temp!=NULL)
    {
    cout<<temp->x<<" ";
    temp=temp->Next;
    }
}

void ClearList(List *MyList)
    {
    while (MyList->Head!=NULL)
    {
    List *temp=MyList->Head->Next;
    delete MyList->Head;
    MyList->Head=temp;
}
}

int main()
{

    List *MyList=new List;

    MyList->Head=NULL;

    for (int i=0;i<10;i++) Add(i,MyList);
    Show(MyList);

    ClearList(MyList);
    delete MyList->Head;
    delete MyList;
}

And also I can just make a stack in that way and do anything with it:
std::stack<int> MyStack;

So, which one is better? What is the advantage of a stack with dynamic memory allocation? In what cases should I use first/second variants?

A: The both stacks use dynamically allocated memory for their nodes (though for std::stack it depends on underlying container).
Of course it is better to use standard class. It was already tested and written by qualified programmers and it is flexible enough: you can use several standard containers to implement the stack because standard stack is a container adapter.
In fact you can write your own underlying container for std::stack as for example a wrapper around an array and in this case the whole stack will be placed in the stack memory though its size of course will be fixed.:)
Nevertheless the standard stack also has many drawbacks. For example you can  not use std::forward_list as the underlying container. I made a proposal to specialize standard class std::stack for std::forward_list.

A: which one is better depends surely on the use case. But generally I would advise you to use the STL implementation of the stack, because it is heavily used and therefore tested perfectly.
Furthermore, you'll get a perfect abstraction of a stack with the STL implementation.
Second, the STL implementation is also using dynamic memory allocation, so from this point of view there is no difference to your implementation.

A: Using dynamic memory gives the advantage of adding possible memory leaks and/or segmentation faults to your program.
I only use dynamic memory when forced to. Forcing example: working with a library that uses c-strings for parameters and return values.


Q: Cannot open new project or old project in Visual Studio 2012
Recently I have installed VS 2012 and SQL Server Management Studio. When I try to open the New Project, I'm getting this error:

Web application projects are currently configured to use IIS Express. To switch back to using the Visual Studio Development server, change the development server option under the Projects and Solutions/Web Projects category of the Tools/Options menu. Configuring IIS Express failed with the following error:
  Filename: redirection.config
  Error: Cannot read configuration file

I was Search about that issue. But  the given solution doesn't fix my problem.
I have tried

*

*Control Panel -> Programs and Features -> Turn Windows Features on or off... inside that, we had to select Internet Information Services -> Web Management Tools -> IIS 6 Management Compatibility -> IIS Metabse and IIS 6 configuration compatibility."

*true replace it with the string True.

Could someone please help?


Q: How to use for loop to calculate moving average with a window size of 10 using 5th column I have a data.csv file containing 5 columns. now I want to use for loop to calculate moving average with a window size of 10 using 5th column in R.
for(i in 1: length[ , 5]-9) {
 data$Mean [i] <- mean (data[i,5]:data[(i+9),5])
}

This means to calculate the mean of 10 consecutive rows and store them in the same data frame by creating a new column
It is calculating wrong and I am getting the error as follows.....

Error in data[i, 5]:data[(i + 9), 5] : NA/NaN argument

A: You have made a couple of mistakes in the line that calculates the mean. The most significant one is that when you try to calculate the mean for the last 9 rows of your dataframe, you go out of bounds. ie, if your dataframe has 100 rows, by row 92 your are trying to get the mean of rows 92:101; of course, there is no row 101.
It should be something like this:
for(i in 1: length(data[ , 5]-9)) {
    data$Mean [i] <- mean(data[i:min(i+9, nrow(data)),5])
}

Also, it's generally a bad idea to use data as a variable name, since there already is a data() function in base R. Simply choose a similar name, like "mydata"
A reproducible example follows, that will get the mean of the next ten rows, OR the mean of the n next rows for the last 9 rows.
mydata <- data.frame(col_1 = rnorm(100),
                     col_2 = rnorm(100),
                     col_3 = rnorm(100),
                     col_4 = rnorm(100),
                     col_5 = rnorm(100))

for(i in 1: length(mydata[ , 5]-9)) {
    mydata$Mean [i] <- mean(mydata[i:min(i+9, nrow(mydata)),5])
}

head(mydata)

If you dont' want to get the mean for the last ten rows, do this instead:
for(i in 1: length(mydata[ , 5]-9)) {
    mydata$Mean [i] <- ifelse( i + 9 <= nrow(mydata),
                               mean(mydata[i:min(i+9, nrow(mydata)),5]),
                               NA)
}


Q: Bluetooth Low Energy Android - Search in Background I would like to know whether it is possible to check in the background if someone enters or leaves the a beacon Region?
In iOS for example you can use the methods didEnterRegion or didExitRegion to send notifications from the background.
Is there any native possibility or has someone a workaround?

A: Android doesn't have any "native" iBeacon capability at all, but you can see iBeacons using my company's open source Android iBeacon Library, which has APIs similar to those native to iOS 7.
In the case of iOS, the CLLocationManagerDelegate gives you access to the didEnterRegion and didExitRegion callbacks that you describe.  In the Android iBeacon Library, the equivalent is the MonitorNotifier interface that gives you the same callback methods.
Making these callbacks successfully fire for apps that aren't in the foreground is a little tricky on both iOS and Android.  On Android, you need to start a service of your own that runs when the Android device starts up, and bind to the IBeaconManager in that service.
Setting this up isn't super easy, so we developed a Pro Android iBeacon Library that does all this automatically.  Examples are here.
EDIT: Both libraries above have been discontinued in favor of the free and open source  Android Beacon Library which has all the feature of the pro library described above.


Q: Data Clensing in SQL Server I've got a table in the following format:
Name    Address1    Address2    Address3
Joe     NULL        1 A Road    London
Bob     2 A Lane    NULL        London

I'd like to run an update to move all the values left where there are nulls so that I end up with:
Name    Address1    Address2    Address3
Joe     1 A Road    London      NULL
Bob     2 A Lane    London      NULL

Please help!
Thanks,
Josh

A: BEGIN TRANSACTION
update person set Address1 = Address2, Address2 = null
  where Address1 is null and Address2 is not null;
update person set Address2 = Address3, Address3 = null
  where Address2 is null and Address3 is not null;
update person set Address1 = Address2, Address2 = null
  where Address1 is null and Address2 is not null;
select top 100 * from person
ROLLBACK TRANSACTION

This would get very ugly if you had lots of address fields, but for 3 is acceptable. Remember to test any script copy and pasted from the interwebs in a transaction that you rollback so you don't get your database wiped :)
EDIT:
With further info (6 address fields):
You could do like above only repeat 5 times to move so in worst case you where still done
Declare StoredProcedure OneRound
BEGIN
  update person set Address1 = Address2, Address2 = null
    where Address1 is null and Address2 is not null;
  update person set Address2 = Address3, Address3 = null
    where Address2 is null and Address3 is not null;
  update person set Address3 = Address4, Address4 = null
    where Address3 is null and Address4 is not null;
  update person set Address4 = Address5, Address5 = null
    where Address4 is null and Address5 is not null;
  update person set Address5 = Address6, Address6 = null
    where Address5 is null and Address6 is not null;
END

Declare StoredProc FixAllAddresses
BEGIN
  call OneRound
  call OneRound
  call OneRound
  call OneRound
  call OneRound
END

You could also use a cusor (warning psydo code) I have not looked up the syntax for T-SQL cursors and it has been a while so I will get the details wrong, check the syntax in the online help.
Declare cursor @personCursor for select ID,Address1,Address2,... from person;
OPEN @personCursor
FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
while(@@FETCH_STATUS)
BEGIN
  IF @addr1 is null
  BEGIN
    IF @addr2 is not null
    BEGIN
      @addr1 = @addr2
      @addr2 = null
    END
    ELSE IF @addr3 is not null
      @addr1 = @addr3
      @addr3 = null
    BEGIN
    -- Boaring, ugly code goes here for addr4,addr5,addr6
    END
  END

  IF @addr2 is null
    IF @addr3 is not null
    BEGIN
      @addr2 = @addr3
      @addr3 = null
    END
    ELSE IF @addr4 is not null
      @addr2 = @addr4
      @addr4 = null
    BEGIN
    -- Boaring, ugly code goes here for addr5, addr6
    END
  BEGIN

  -- repeat for addr3, addr4,

  if @addr5 is null
  BEGIN
    IF addr6 is not null
    BEGIN
      @addr5 = @addr6
      @addr6 = null
    END
  END

  END
  update person set address1 = @addr1, address2 = @addr2, ...
    where PersonId = @personId
  FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...)
END

The Stored proc begin called 5 times makes for less code and may be less error prone, the cursor only iterates through your people once, but does not filter. I suspect the stored proc solution below will be faster but it will depend on your data.

A: David's solution is the most efficient. One that might be more easily extend-able for greater numbers of columns is.
;WITH cte
     AS (SELECT *,
                 MAX(CASE WHEN RN=1 THEN value END) OVER (PARTITION BY ContactId) AS new_Address1,
                 MAX(CASE WHEN RN=2 THEN value END) OVER (PARTITION BY ContactId) AS new_Address2,
                 MAX(CASE WHEN RN=3 THEN value END) OVER (PARTITION BY ContactId) AS new_Address3
         FROM   #Addresses
                OUTER APPLY (SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN value IS NULL THEN 1 ELSE 0 END, idx) AS
                                   RN, idx, value
                             FROM   (VALUES(1,Address1),
                                           (2,Address2),
                                           (3,Address3)) t (idx, value)) d)
UPDATE cte
SET    Address1 = new_Address1,
       Address2 = new_Address2,
       Address3 = new_Address3


Q: How to filter out different classes into an array How will I take product with same category into a string or an array?

What I want exactly is to filter them and append them into a new div to create a filterable animation using GSAP. This is actually a WordPress WooCommerce product page.
Last time I created a popup using GSAP, and in that I used something called split() function:
triggers.each(function(){
    let listClassName = $(this).attr('class').split(' ');
    let revealClassName = String(listClassName[listClassName.indexOf(listClassName.find(element => element === 'dasrgsap__reveal-trigger')) + 1]);
    const sectionReveal = $('.dasrgsap__reveal-content.' + revealClassName);
    const colReveal = $('.dasrgsap__reveal-content.' + revealClassName + ' .et_pb_column');
});

The trigger was (dasrgsap__reveal-trigger sandra) and the popup content container was (dasrgsap__reveal-container sandra). Both were given two separate classes, which made it easier to split and access them.
In this case, WooCommerce product list items are given too many classes, so the only class I can play with to get a specific category is the product_cat-'product-category'.
I want to get a string or array of the same product category, and I want to split product_cat- and category-1 and get an array of that category, but I'm not able to do it.
Is this even possible?

A: This is only a guess but is this what you were after

$("li").each(function() {
  var category = $.makeArray(
    $(this)
    .attr("class")
    .slice(
      $(this).attr("class").indexOf("-") + 1,
      $(this).attr("class").length
    )
  );
  // console.log(category);

  var product = $.makeArray($(this)
    .attr("class")
    .slice(0, $(this).attr("class").indexOf("-")))
  // console.log(category);

  var completeList = $.merge(product, category);
  console.log(completeList)

});

https://jsfiddle.net/7xcpjr59/
I hope it helps


Q: NLog structuring logging masking Suppose we are writing the following structured log message
logger.Info("User's Password is {Password}", "1234567890");

I would like to mask a password property because it is a sensitive data. I found this issue but I think it is a very difficult way.
For example, I have found the extension that resolves a similar task for serilog. It is very simple to use. But I didn't find any useful information for Nlog.
How to achieve it with nlog library?
I will appreciate any suggestions.

A: You could use RegisterObjectTransformation, introduced in NLog 4.7.
For example:
LogManager.Setup().SetupSerialization(s =>
    s.RegisterObjectTransformation<object>(o =>
    {
        var props = o.GetType().GetProperties();
        var propsDict = props.ToDictionary(p => p.Name, p => p.GetValue(o));

        propsDict.Remove("password");

        return propsDict;
   }));

Please note, in terms of performance you maybe need something like a reflection cache and smart optimizations.

A: I suggest that you wrap the secret password in an object like this:
public class SecretWrapper : IFormatable
{
    private readonly string _secret;

    public SecretWrapper(string secret)
    {
        _secret  = secret;
    }

    public string GetSecret() => _secret; // Not a property to avoid basic reflection

    public override string ToString() => "******"

    public string ToString (string format, IFormatProvider formatProvider) => ToString();
}

NLog will never output the secret-value:
logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));


Q: Wix installer creating registry entry based on user input So, basically what I have is Wix installer, which is modified and I am currently stuck at a problem with registry entry. During install the Installer has a custom dialogue, where user has to choose/insert second path. Which will be stored in the Registry. But instead of inserting what user entered, it inserts "[INSTALLFOLDER]", although it should look something like "C:\Program Files...". I did some research but, didn't find anything that could help me.
All of the code are in the same file.
Main parts of the code are here, first there's this property. Which later should be written into registry.
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" />

Later on there's the custom window.
<!-- NetWork path -->
  <Dialog Id="CustomNETDirDlg" Width="370" Height="270" Title="Custom Folder">
    <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)" />
    <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" />
    <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)">
      <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish>
    </Control>
    <Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes" Text="Choose Network Path" />
    <Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="NetWork Path" />
    <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" />
    <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
    <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
    <Control Id="FolderLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" Text="Choose / Enter Path" />
    <Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/>
    <Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />
  </Dialog>
  <!-- / NetWork path -->

Little bit below that is this publish part...
  <Publish Dialog="CustomNETDirDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[CUSTOMPATH]" Order="1">1</Publish>
  <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish>

And this works for me.
I replaced guid for "reasons". Registry path and everything else seems to be fine, just one thing which is not working,adding  [CUSTOMPATH] property as registry value.I also tried without [] brackets, and so on... Even tried it with  [Manufacturer], worked perfectly fine, inserted Manufacturer into registry. But this here is not working.
<DirectoryRef Id="TARGETDIR">
    <Component Id="RegistryEntries" Guid="{my guid}">
      <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value='[CUSTOMPATH]' KeyPath='yes' />
    </Component>
</DirectoryRef>

A: Correct
This is correct because you specify that the content of CUSTOMPATH is actually a reference a different Property (or Directory because a certain point Directory elements become available to be used like Property elements):
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" />
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/>

The above will visualize the content of INSTALLFOLDER so that's ok.
However, the actual value of CUSTOMPATH will never change. It should always remain a reference to another property because you use it with Indirect=Yes.
Possible root cause of your problem
In the next part you assign a value to CUSTOMPATH and that's where I think something goes wrong. I tried the following and it gave me the requested result ("C:\Program Files..." in the registry value).
<Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[INSTALLFOLDER]" Order="1">1</Publish>
<RegistryValue Root='HKLM' Key='Software\Test\TestRegEntry1' Type='string' Value='[INSTALLFOLDER]' KeyPath='yes'/>

If this doesn't work, could you provide me with the logfile?
zzz.msi /lvoicewarmupx debug.log

A: So basically what I did to fix this issue was that I created right beside INSTALLFOLDER another directory. Since I didn't add any files into it, that folder will not be created, but value as such remains.
<Directory Id="INSTALLFOLDER2" Name="!(bind.property.ProductName)"></Directory>
<Directory Id="INSTALLFOLDER" Name="!(bind.property.ProductName)">
    <!-- Here are files I wanted to include -->
</Directory>

Registry entry now looks like this:
<DirectoryRef Id="TARGETDIR">
    <Component Id="RegistryEntries" Guid="here comes your guid">
        <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value="[INSTALLFOLDER2]" KeyPath='yes' />
    </Component>
</DirectoryRef>

And Property like this:
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER2" Secure="yes" />

Folder selector controls look like this, so both typing and button (folder selector) work. Dialog that uses them is exactly like InstallDirDlg, but with a different name.
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes" />
<Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />


Q: Javascript - .length gives me 0 length Array is initialized
var Collect = [];

So I have a promise arguments so that I'll have a asynchronous in execution since retrieving data from firebase which then push in the array Collect takes a bit of time. Here's my code:
function loadTables(){
    var promise = getDataFirebase();
    promise.then(function(){
        console.log("firsst");
        return ProcessOfData();
    }).then(function(){
        console.log(Collect);            //when printed, it shows the elements collected from firebase so the array is not 0.
         console.log(Collect.length);   // but when printeed here. it gives me 0. why?
        return EndProcessLog();
    }).then(function(){

    });
}

Codes when retrieving data from firebase:
function getDataFirebase(){
    return new Promise (function(resolve,reject){
        refReview.on("value", function(snap){
            var data = snap.val();
            for(var key in data){              //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
                Collect.push({
                    "RevieweeName": data[key].revieweeID.firstname.concat(" ",data[key].revieweeID.lastname),
                    "ReviewerName": data[key].reviewerID.firstname.concat(" ",data[key].reviewerID.lastname),
                    rating:data[key].rating,
                    content: data[key].content
                })
            }//end of for loop

        }); //end of snap
        resolve();
    });
}

A: Why does it not work? Because you are resolving the promise before the asynchronous method runs. The reason why the object shows the value is the console lazy loading the object.
What do you do? Move the resolve line after the for loop inside the callback.
refReview.on("value", function(snap) {
  var data = snap.val();
  for (var key in data) { //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
    Collect.push({
      "RevieweeName": data[key].revieweeID.firstname.concat(" ", data[key].revieweeID.lastname),
      "ReviewerName": data[key].reviewerID.firstname.concat(" ", data[key].reviewerID.lastname),
      rating: data[key].rating,
      content: data[key].content
    })
  } //end of for loop
  resolve(); < --RIGHT

}); //end of snap
// resolve(); <-- WRONG

Ideally with a promise you do not use global variables, you pass the value through the resolve.

var myPromise = new Promise(function(resolve, reject) {
  var str = "Hello!";
  resolve(str);
});

myPromise.then(function(value) {
  console.log(value);
});


Q: How to select specific substring length based on a filter I have multiple CSV files with different names, containing today's date, customer number, and then the extension. For example:
2019-01-23 XYZF-105.csv
2019-01-23 ABCD-205.csv
2019-01-23 Different nonstandard name.csv
2019-01-23 ##ABCD-305(Trial).csv

I would like to get the part of the name where it contains the customer number only, like ABCD-305.
Tried using a substring to select 8 characters right from the dot, but that doesn't work for those that have suffix like (Trial).
Neither it work 11 characters from the beginning, as it will include the ##.
Also, it has to avoid the nonstandard names.
I used
$allitems = Get-ChildItem -Path 'C:\Downloads\Customers\*.csv'
$res = @()
foreach ($item in $allitems){
    $item = $item.Name.substring($item.Name.Length - 12,8)
    $res += $Item
}

This way, for the proper names I get good results, but only if the name of the CSV is like 2019-01-23 ABCD-205.csv.
What should be the way to skip the date, skip the .csv extension and get only results with 8 characters, that have a dash after the 4th character?
Thanks in advance

A: Try the following (PSv3+ syntax):
$res = (Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name |
         Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' |
           ForEach-Object { $_.Matches[0].Value }

*

*(Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name outputs the file names of all CSV files in dir. C:\Downloads\Customers

*Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' uses case-sensitive regex (regular-expression) matching to only select file names that contain 4 ({4}) uppercase chars. [A-Z], followed by -, followed by 3 digits (\d), on word boundaries (\b)

*The ForEach-Object script block then outputs the part of each matching file name that matched the regex ($_.Matches[0].Value), so that only the relevant portions of matching file names are collected in $res, as an array.

A: This would be a good time to use regex.
See https://regex101.com/r/AH00n6/1
and understand the following regex:
.*\s[#]*([A-Z]{4}-[0-9]{3}).*.csv

This is a little extra to capture just the names, but gives more insight into how to control the regex.


Q: Why pl sql assignment operator throws error while reading from sql query? set serveroutput on;
 declare

      v_emp_first_name  US_EMPLOYEES.FIRST_NAME%TYPE;

      BEGIN

       select us_employees.first_name into v_emp_first_name  from us_employees where email = 'jbutt@gmail.com';

       dbms_output.put_line('v_emp_first_name  --> ' || v_emp_first_name);

       v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

       dbms_output.put_line('v_emp_first_name  --> ' || v_emp_first_name);

      END;

When I compile above code the below statement throws error
    v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

Is it not possible to read a column value via a sql query and map that value using  assignment operator ?
If i have the below code alone then it compile and works fine
    select us_employees.first_name into v_emp_first_name  from us_employees where email = 'jbutt@gmail.com';

A: You have issue with this code:
v_emp_first_name := select first_name from us_employees where email = 'kris@gmail.com';

You can not use the assignment operator against the query as you have used.
Replace this assignment := with INTO as follows:
select first_name INTO v_emp_first_name from us_employees where email = 'kris@gmail.com';

A: The short answer is NO. You can't assign the output of a scalar query to a variable. The proper syntax for your "assignment" is the one you are already aware of.
I am sure that you will then ask WHY. Why did Oracle choose that "weird" syntax for assignment, and not the simpler one you tried?
The answer is that in more general cases a select statement may return multiple columns, not just one; and the values from multiple columns can be "assigned" to multiple variables (local to the PL/SQL block) simultaneously. Which, by the way, is the more common usage - people extract one "record" at a time, rather than a single value. So, how would you re-write the "select into" operation as an "assignment" (or multiple "assignments")? There is no natural way to do that.
You may ask why Oracle doesn't allow "your" assignment syntax, in the case of a single column selected, in addition to the select into syntax (which is needed for multi-column rows anyway). The answer is that would be wasteful. We already have a syntax - that we need for more general cases anyway; we don't need one more.
You might say that we could put all the receiving local variables into a record type, and do a single assignment (to a record) even for general "rows" returned by a select. Alas, SQL statements return rows, not records; rows are a SQL concept, and specifically they are not a data type. Perhaps Oracle could do further development along those lines (to add functionality that doesn't exist today), but why bother - they already have a perfectly fine syntax for what you need, and you already know what that syntax is - without needing to define a record type to hold all your local variables, then define a "record type" for rows coming from a SQL select statement, then .....


Q: Can't run code in Android studio due to VT-x disabled When i try to run my code in android studio i got an error"Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.  Enable VT-x in your BIOS security settings (refer to documentation for your computer)." . I did every thing i could but i couldn't fix it . Can anybody tell me in detail how

A: First make sure your processor supports virtualization technology
Intel processors from i3 supports it.
If your processor is above i3, then Go to BIOS and look for an option named VTx or virtualization and Enable it...save changes and exit
Now open your web browser and search for HAxm drivers and install the latest one.
You should be good
P.S: if your processor is below i3, you cannot run avd

A: If your computer does not support Virtualization, there are emulators that don't require it. I know one that many people use is Genymotion.
Alternatively, of course, you can test on a physical device.


Q: Web Scraping w/Mechanize and/or BeautifulSoup4 on ASP pages Hello I am a programming n00b and am desperately trying to get some code to work.
I can't really find any good tutorials on ASP scraping/filling in fields and submitting then working with the content.
Here is my code so far:
import mechanize
import re

url = 'http://www.cic.gc.ca/english/work/iec/index.asp'
br = mechanize.Browser(factory=mechanize.RobustFactory())
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open(url)
response = br.response().read()

What I am trying to do:

*

*Load that URL

*Fill out the 2 form fields

*Submit

*Print the div id stats into python

*Run a loop on a 15 minute timer

*Play a loud sound if anything in div stats changes when it loops

Please advise me the best/fastest way of doing this with minimal programming experience.

A: It's not that difficult once you understand why the second form isn't shown when page is loaded. There's nothing to do with ASP itself, it's rather due to CSS style set to "display: none;" and will only be active once the first Option Select has been filled.
Here is a full sample of what you're after, implemented in Selenium, it's similar to machanize I believe.
The basic flow should be:

*

*load the web browser and load the page

*find the first Option Select and fill it in

*trigger a change event (I chose to send a TAB key) and the second Option Select is shown

*fill in the second Select and find the submit button and click it

*assign a name to the content you get from the div id=stats text

*compared if the text has changed from last fetch
a) if YES, do your BEEP and close the driver page etc.
b) if NO, set a scheduler (I use Python's Event's Scheduler, and run the crawling function again...
That's it! Easy, ok code time -- I used United Kingdom + Working Holiday pair for test:
import selenium.webdriver
from selenium.webdriver.common.keys import Keys
import sched, time

driver = selenium.webdriver.Firefox()
url = 'http://www.cic.gc.ca/english/work/iec/index.asp'
driver.get(url)

html_content = ''
# construct a scheduler
s = sched.scheduler(time.time, time.sleep)

def crawl_me():
    global html_content
    driver.refresh()
    time.sleep(5) # wait 5s for page to be loaded

    country_name = driver.find_element_by_name('country-name')
    country_name.send_keys('United Kingdom')
    # trick's here to send a TAB key to trigger the change event
    country_name.send_keys(Keys.TAB)

    # make sure the second Option Select is active (none not in style)
    assert "none" not in driver.find_element_by_id('category_dropdown').get_attribute('style')

    cateogory_name = driver.find_element_by_name('category-name')
    cateogory_name.send_keys('Working Holiday')

    btn_go = driver.find_element_by_id('submit')
    btn_go.send_keys(Keys.RETURN)

    # again, check if the content has been loaded
    assert "United Kingdom - Working Holiday" not in driver.page_source

    compared_content = driver.find_element_by_id('stats').text
    # here we will end this script if content has changed already
    if html_content != '' and html_content != compared_content:
        # do whatever you want to play the beep sound
        # at the end exit the loop
        driver.close()
        exit(-1)
    # if no changes are found, trigger the schedule_crawl() function, like recursively
    html_content = compared_content
    print html_content
    return schedule_crawl()

def schedule_crawl():
    # set your time interval here, 15*60 = 15 minutes
    s.enter(15*60, 1, crawl_me, ())
    s.run() # and run it of course

crawl_me()

To be honest, this is quite easy and straight forward however it does require you fully understand how html/css/javascript (not javascript in this case, but you do need to know the basic) and all their elements how they work together.
You do need to learn from the basic read => digest => code => experience => do it in cycles, Programming doesn't have a shortcut or the fastest way.
Hope this helps (and I really hope you do not just copy & paste mine, but learn and implement your own in mechanize by the way).
Good Luck!


Q: What is the specific requirement to use Dagger2 in any android application? What are the actual benefits of using dagger2 in an android application? I read the dagger 2 documentation but still not able to find that in what condition I should use dagger2 in my application and what are the benefits of its implementation?

A: 1.) to use Dagger2, you need to include it as a dependency in your project.
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
compile 'com.google.dagger:dagger:2.9'
provided 'org.glassfish:javax.annotation:10.0-b28'

Then you can use Dagger2.

2.) Whenever you have a class which is the dependency of another class.
So if you have something like this:
public int getNewRandomNumber() {
    return new Random().nextInt(5000);
}

Then you have an implicit dependency on Random and it is not mockable.
So you might want to provide this as a dependency to the method instead:
public int getNewRandomNumber(Random random) {
   return random.nextInt(5000);
}

But you might be using Random in a bunch of places, so you might want to provide it to the class itself:
public class RandomGenerator {
    private final Random random;

    public RandomGenerator(Random random) {
        this.random = random;
    }
}

After which the question surfaces: if you need an instance of RandomGenerator, where are you getting Random from?
Surely this is stupid:
RandomGenerator gen = new RandomGenerator(new Random());

Wouldn't it be nicer to do either this:
RandomGenerator randomGenerator = component.randomGenerator();

or
@Inject
RandomGenerator randomGenerator;

Well apparently with Dagger it's pretty easy
@Module
public class RandomModule {
    @Provides
    @Singleton
    Random random() {
        return new Random();
    }
}

@Singleton
@Component(modules={RandomModule.class})
public interface SingletonComponent {
    Random random();
    RandomGenerator randomGenerator();
}

then
@Singleton
public class RandomGenerator {
    private final Random random;

    @Inject
    public RandomGenerator(Random random) {
        this.random = random;
    }
}

or
@Singleton
public class RandomGenerator {
    @Inject
    Random random;

    @Inject
    public RandomGenerator() {
    }
}

You can read more about dependency injection here


Q: Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools? Yesterday I observed some really strange behaviour and wrote a looooong question on it. As @tacoshy correctly pointed out, the question lacked focus. I will therefore, in this post, focus on one single question:

Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools?

Preface
The <head>-element contain the following viewport meta-tag
<meta name="viewport" content="width=device-width, initial-scale=1" />

Before any video shown below, the following have both been performed in Chrome-devtools
Settings > Preferences > Reset defaults and reload
and
The kebab-icon in the responsive view > Reset to defaults
The application.
The code can be found here. It's deployed and can be inspected here.
A React-application with a state (windowWidth) that is updated to window.innerWidth when the resize-event triggers. I also have a container div with min-width set to windowWidth. In short, the container should always have the same min-width as window.innerWidth. The container contains a div with min-width statically set to 400px.
The behaviour
When I only open chrome developer tools and resize the visible window by changing the width of the developer tools, this is the observed behaviour:

*

*window.innerWidth corresponds to the size of the window.

*The scale (from window.visualViewport.scale) remains at 1.

Now we try in Chrome developer tools responsive mode:

*

*The width remains static (781px)

*The entire scale of the viewport goes down.

Further investigations

*

*window.visualViewport.width will produce nearly identical behaviour

*

*(apart from width sometime shifting to a decimal-point value)

*window.screen.width will produce a different but also erroneous behaviour:

*

*The layout doesn't break until the screen becomes smaller than the cyan-coloured element (in the header with min-width: 400px). Then the container seem to shrink quicker and at this point we can also see how the scale starts to go down.

*Setting windowWidth statically to 100vw produces exactly the same behaviour as above.

Solution to the weird behaviour
All of the examples above on the layout breaking have one thing in common: The scale starts to go down instead of the actual width of the viewport. So one could imagine that updating the viewport meta-tag to include minimum-scale=1 would solve the problem, and it does! Using
<meta
  name="viewport"
  content="width=device-width, initial-scale=1, minimum-scale=1"
/>

Produces the following behaviour:

As you can see, the Scale remains at 1 and the layout doesn't break. In fact, adding minimum-scale=1 makes innerWidth, visualViewport.width and screen.width all produce the same expected behaviour in the responsive view of chrome developer tools.
Unfortunately solving that was not the question, the question is and remains:

Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools?

Edit
This strange scaling-behaviour is not mirrored when viewing the page in the Firefox developer tools responsive view.

Edit2
Similar questions
Does Mobile View in Chrome-Dev-Tools force scaling?
Exactly the same problem, solved by adding the meta-tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Which apparently did solve the problem in January 2020, but does not solve the problem today (as we cab see here).

Resize Chrome responsive mode window without changing scale
Also solved by adding:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

which is already present this time around.

Why is Chrome shrinking the view in responsive mode?
Exactly the same behaviour as this mine but the selected solution was a jQuery-hack. The poser also mentioned a similar scaling-problem when tilting your phone and then tilting it back again which I too have experienced (it goes away when adding minimum-width=1 to the viewport metatag).
Summary
It looks like this issue used to be solved by adding
<meta name="viewport" content="width=device-width, initial-scale=1.0">

but now requires
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">

my question in that case remains

*

*Why have they changed this?

*What use is there for the developer to change the scale of the page when resizing the responsive window?

*Is this a feature or a bug?

Edit3
Edge on the other hand does seem to mirror this behaviour.


Q: "Lock on the Kernel Object" on windows can make the entire system unresponsive? There's this WIN32 process, which someone says:

The servide takes a lock on the kernel
  object and does not release. After a
  while the machine becomes irresponsive
  and has to restarted. Restanting only
  the service won't fix the issue.

According to my knowledge applications were not supposed to be able to crash the entire system in windows. Does anyone know if such an indecent behavior (taking a lock on the kernel object and not releasing it) can indeed crash the OS? If so why don't we see this more in malicious software?
Some clarifications:
This is not a device driver.
Any amiguity left in the reponse is also ambiguous to me. Please elaborate on the cases you can think of.

A: This doesn't mean anything. There is no "kernel object" in NT, and any lock you could possibly take would be released if the service were restarted.

A: This depends on what type of application it is.  Some applications install and use kernel drivers as part of their usage.  A kernel driver has the most low level access possible in the system and is capable of crashing or hanging the system.  If the process uses a kernel driver, and the description alludes to this, then yes it can crash / hang the system.
I believe Windows Vista started limiting the amount of damage a kernel driver can accidentally do (graphics drivers especially).  But intentionally, you can still cause lots of problems.

A: Depending on which precise kernel object they mean, and which service, this may very well be true. See for instance Raymond Chen on Loader Lock, a kernel lock which applications can monopolize. Restarting the service will then become a problem because the very unload of that service will require the loader lock, too.


Q: Using Parsec with restrictions on parsed result I'm trying to come up with a clever way of parsing assembly code. For example, if the registers are numbered from 0 to 31, I want to accept $31 but not $32.
I would like to do these while I parse the source code, because 1) I want to use the position information. 2) I like it simple.
My best idea is to use a special parser to indicate failure.
For example I could write
import Text.Parsec hiding (label)
import Text.Parsec.Token
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String
import Text.Parsec.Expr
import Text.Parsec.Perm

data Register = Register Integer
  deriving (Eq, Ord, Show)

register :: Parser Register
register = do char '$'
              n <- onlyWhen "Register number must be between 0 and 31"
                            (\n -> n >= 0 && n <= 31) (decimal p)
              return $ Register n

onlyWhen :: String -> (a -> Bool) -> Parser a -> Parser a
onlyWhen mess pred pars
  = do r <- pars
       if pred r then return r
                 else fail mess

p = makeTokenParser emptyDef

It works, but the error message contains traces of the parsing state, which is unfortunate.
What would be the best way to do it? Is there some additional library for doing this kind of things?

A: Try to extract Error messages
getErrorMessage (ParseError p xs) = show p ++ concat $ map messageString xs


Q: Using a list of conditions to filter a DataFrame in Pandas I wish to have a function which takes a list of conditions, of any length, and places an ampersand between all the conditions. Example code below.
df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'],
         data=[
               ['HG_12_34', 200, 35, 0.4],
               ['HG_12_34_2', 50, 45, 0.9],
               ['KD_89_9', 76, 67, 0.7],
               ['KD_98_9_2', 4, 78, 0.02],
               ['LG_3_45', 90, 3, 0.8],
               ['LG_3_45_2', 15, 12, 0.9]
               ])

def some_func(df, cond_list):

    # wrap ampersand between multiple conditions
    all_conds = ?

    return df[all_conds]

cond1 = df['DP'] > 40
cond2 = df['GQ'] > 40
cond3 = df['AB'] < 0.4

some_func(df, [cond1, cond2]) # should return df[cond1 & cond2]
some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2]

I would appreciate any help with this.

A: You can use functools.reduce for that:
from functools import reduce

def some_func(df, cond_list):
    return df[reduce(lambda x,y: x&y, cond_list)]
Or, like @AryaMcCarthy says, you can use and_ from the operator package:
from functools import reduce
from operator import and_

def some_func(df, cond_list):
    return df[reduce(and_, cond_list)]
or with numpy - like @ayhan says - which has also a logical and reduction:
from numpy import logical_and

def some_func(df, cond_list):
    return df[logical_and.reduce(cond_list)]
All three versions produce - for your sample input - the following output:
>>> some_func(df, [cond1, cond2])
       Sample  DP  GQ   AB
1  HG_12_34_2  50  45  0.9
2     KD_89_9  76  67  0.7
>>> some_func(df, [cond1, cond2, cond3])
Empty DataFrame
Columns: [Sample, DP, GQ, AB]
Index: []


Q: SQL Datetime as time query I would like the below select statement to be show as time rather than datetime.  I'm aware that a cast as solution is likely however given I am trying to Cast as a "grouped by time", I am not finding a solution.
SELECT
DATEADD(hour, DATEDIFF(hour, 0,dbo.tbReceiptLine.Time), 0) AS Hourly,
DATEADD(minute, DATEDIFF(minute, 0, dbo.tbReceiptLine.Time) / 30 * 30, 0) AS [30 Mins]

I would like to show this as time only.

A: In SQL Server 2008 onwards you can cast to time datatype:
SELECT CAST(dbo.tbReceiptLine.Time as time)

See The ultimate guide to the datetime datatypes