text:
Q: NavigationDrawer : java.lang.NullPointerException: Attempt to invoke virtual method Viewgroup.getPaddingLeft() on a null object reference I am implementing a navigation drawer in a base activity and using it in few other activities extending the base activity. i have made sure all the views are  defined in my xml. However, i get the error
java.lang.NullPointerException: Attempt to invoke virtual method
'int android.view.ViewGroup.getPaddingLeft()' on a null object reference

The error is shown on the line setContentView(layoutResId) in the activity extending the base activity.
I am doing this
@Override
protected void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.drawer_layout);
    super.onCreate(savedInstanceState);

   }

setContentView(R.layout.drawer_layout); is before super.onCreate(savedInstanceState);  as i am extending the base activity that does the work for navigation drawer.
I am sure all my layouts have proper ids that is needed for the drawer activity (the base activity). The code is below:
drawer_layout.xml
public class DemoNavActivity extends DrawerAppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.drawer_layout);
    super.onCreate(savedInstanceState);

    }
}

DrawerAppCompatActivity.java
public class DrawerAppCompatActivity extends AppCompatActivity {

public DrawerLayout mDrawerLayout;
public ListView mPreferenceList;
public ActionBarDrawerToggle mDrawerToggle;

public CharSequence mDrawerTitle;

public CharSequence mTitle;

public String[] navMenuTitles;
public TypedArray navMenuIcons;

public ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter adapter;

TextView user_name, user_email,btnLogin;
CircleImageView profileImage;
LinearLayout user_details, drawer;
FacebookUser user;
Gson gson;

public static SharedPreferences prefs;
public static SharedPreferences.Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    prefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    editor = prefs.edit();

    gson = new Gson();

    user_name = (TextView) findViewById(R.id.user_name);
    user_email = (TextView) findViewById(R.id.user_email);
    btnLogin = (TextView) findViewById(R.id.btnLogin);
    profileImage = (CircleImageView) findViewById(R.id.userProfileImage);
    user_details = (LinearLayout) findViewById(R.id.user_details);
    drawer = (LinearLayout) findViewById(R.id.drawer);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getApplicationContext(), FacebookLoginActivity.class));
            mDrawerLayout.closeDrawer(Gravity.LEFT);
        }
    });

    if (prefs.getString("user","").equals("")){
        user_details.setVisibility(View.GONE);
        btnLogin.setVisibility(View.VISIBLE);
    }else{
        user_details.setVisibility(View.VISIBLE);
        btnLogin.setVisibility(View.GONE);

        user = gson.fromJson(prefs.getString("user", ""), FacebookUser.class);

        Picasso.with(this).load(user.image).into(profileImage);
        user_name.setText(user.name);
        user_email.setText(user.email);
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mPreferenceList = (ListView) findViewById(R.id.list_preferences);

    ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) drawer
            .getLayoutParams();
     params.width = getResources().getDisplayMetrics().widthPixels * 4/5 ;
//        params.width = LinearLayout.LayoutParams.MATCH_PARENT;
    drawer.setLayoutParams(params);

//set adapter to listview
    mPreferenceList.setBackgroundColor(getResources().getColor(
            R.color.bg_grey));

    navDrawerItems = new ArrayList<NavDrawerItem>();

    mTitle = mDrawerTitle = getTitle();
    navMenuTitles = getResources().getStringArray(
            R.array.prefrence_names);
    navMenuIcons = getResources().obtainTypedArray(
            R.array.preference_icons);

    for (int i = 0; i < navMenuTitles.length; i++) {
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons
                .getResourceId(i, -1)));
    }

    navMenuIcons.recycle();

    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mPreferenceList.setAdapter(adapter);
    mPreferenceList.setOnItemClickListener(new SlideMenuClickListener());

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_menu, R.string.app_name,
            R.string.app_name) {

        public void onDrawerClosed(View drawerView) {
//                getSupportActionBar().setTitle(mTitle);
            invalidateOptionsMenu();
        };

        public void onDrawerOpened(View drawerView) {
//                getSupportActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu();
        };
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.bhitta_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
    }else if(id == R.id.action_preferences){
        mDrawerLayout.openDrawer(Gravity.LEFT);
    }
    return super.onOptionsItemSelected(item);
}

private class SlideMenuClickListener implements AdapterView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        displayView(position);
    }
}

private void displayView(int position) {
    switch (position){

        case 0:
            Toast.makeText(DrawerAppCompatActivity.this, "asdlkfjlsdf", Toast.LENGTH_SHORT).show();
            break;

    }
}

}

This very code used to work before but now i am not able to rectify what's going wrong.
Please advise.


text:
Q: How to bring git master branch up to date with a named branch? Me and my homework parter are new to git and managed to mess with the branches somehow. I'm not sure how we got to this state or what to do from here.
There used to be a branch named "lior's_saturday_work" which my partner tried to merge back into the project and this is the result.

How do we bring the master branch up to date with the lior\'s_saturday_work?

A: Try this please :
git checkout master
git merge lior's_saturday_work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tomcat hangs due to large requests I have a Grails application which is deployed in Apache Tomcat server. Everything works fine but sometimes the application receives around 100-200 requests in succession(Due to an API integration and these many requests are sent by the API to my application that too within a few minutes and not by my application to the API) and tomcat starts to hang(There are no errors though).
The request is mostly to perform some small DB updates from the data sent by the API used.
Is there a way i can handle this? Any jvm setting or any code changes to handle this?

A: you need to increase the max threads in your tomcat server
<Connector port="8080" address="localhost"
     maxThreads="250" <!-- here -->
      maxHttpHeaderSize="8192"
     emptySessionPath="true" protocol="HTTP/1.1"
     enableLookups="false" redirectPort="8443" acceptCount="100"
     connectionTimeout="20000" disableUploadTimeout="true" />

https://web.archive.org/web/20160410090326/http://www.genericarticles.com/mediawiki/index.php?title=How_to_optimize_tomcat_performance_in_production

A: Before increasing the NIO thread limit, make sure your I'O operations able to handle the load. If I/O operations unable to handle the load thread will be pilled up quickly again it and will hit the threshold of NIO thread limit due to Backpressure from DB.


text:
Q: My Function will not inject text into my HTML I am creating a quiz for my web site and I would like for my function to be able to inject text into my HTML. It has worked for every other function but this one does not work. I have tried to change my injection method. I have also tried to use a JQuery method to inject my text but it still wont let me.

function quiz() {
  var f = 0;
  alert(f);
  if (document.getElementById("answer1").checked == true) {
    f++;
  };
  if (document.getElementById("answer2").checked == true) {
    f++;
  };
  if (document.getElementById("answer3").checked == true) {
    f++;
  };
  if (document.getElementById("answer4").checked == true) {
    f++;
  };

  function checkpass() {
    var a = ""
    if (f == 4) {
      a = "Y"
      alert(a)
    } else {
      a = "N"
      alert(a)
    };
  };
  checkpass();
  alert(document.getElementById("score"))
  document.getElementById("score").innerHTML = `Score:${f}/4 ${a}`;
};

Answer True or False on qustions

Is ___

  <form>
    <input class="Radio-Button" id="answer1" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer2" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer3" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer4" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

  <button onclick="quiz()">Submit</button>

Score:Not Submitted

A: Your problem is here:
document.getElementById("score").innerHTML = `Score:${f}/4 ${a}`;

You are trying to access the variable "a" that's inside checkpass function, You need to put the variable outside from the checkpass functions.
This is your code
function checkpass() {
    var a = ""
    if (f == 4) {
      a = "Y"
      alert(a)
    } else {
      a = "N"
      alert(a)
    };
  };

It should be something like this:
var a = "";
function checkpass() {
    if (f == 4) {
      a = "Y"
      alert(a)
    } else {
      a = "N"
      alert(a)
    };
  };

And by the way, variable "f" is declared correctly it's not the problem because the error says "message": "Uncaught ReferenceError: a is not defined" and variable "a" is after variable "f" So it's more like it can't access variable "a" not var "f"

A: <!DOctyPE html>

Answer True or False on qustions

Is ___

              <form>
                    <input class="Radio-Button" id="answer1" name="T/F" type="radio">
                    True

                    <input class="Radio-Button" name="T/F" type="radio">
                    False
              </form>

Is ___

              <form>
                    <input class="Radio-Button" id="answer2" name="T/F" type="radio">
                    True

                    <input class="Radio-Button" name="T/F" type="radio">
                    False
              </form>

Is ___

              <form>
                    <input class="Radio-Button" id="answer3" name="T/F" type="radio">
                    True

                    <input class="Radio-Button" name="T/F" type="radio">
                    False
              </form>

Is ___

              <form>
                    <input class="Radio-Button" id="answer4" name="T/F" type="radio">
                    True

                    <input class="Radio-Button" name="T/F" type="radio">
                    False
              </form>

      <button onclick="quiz()">Submit</button>

Score:Not Submitted

A: You just have to move the definition of a to outside checkpass or return it because it's needed in the last line (which is outside checkpass). (I'm showing the latter because another answer already shows the first). You might want to look into the js debugger in devtools, because this kind of slips are not unusual, but easy to catch with debugger.
(Also I changed your "score" element alert because alerts are not like console.log - full, expandable objects will not be displayed, just string.)

function quiz() {
  var f = 0;
  alert(f);
  if (document.getElementById("answer1").checked == true) {
    f++;
  };
  if (document.getElementById("answer2").checked == true) {
    f++;
  };
  if (document.getElementById("answer3").checked == true) {
    f++;
  };
  if (document.getElementById("answer4").checked == true) {
    f++;
  };

  function checkpass() {
    var a = "";
    if (f == 4) {
      a = "Y"
      alert(a)
    } else {
      a = "N"
      alert(a)
    };
    return a;
  };
  var a = checkpass();
  alert(document.getElementById("score").outerHTML)
  document.getElementById("score").innerHTML = `Score:${f}/4 ${a}`;
};

Answer True or False on qustions

Is ___

  <form>
    <input class="Radio-Button" id="answer1" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer2" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer3" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

Is ___

  <form>
    <input class="Radio-Button" id="answer4" name="T/F" type="radio">   True
   <input class="Radio-Button" name="T/F" type="radio">   False
  </form>

  <button onclick="quiz()">Submit</button>

Score:Not Submitted

A: So the other answers explained what was wrong
Here is a version using recommended eventListener and a more elegant way of counting.
Also the HTML is simpler and if you want to submit the form, you will get the correct names
Note this quiz does not know or care how many questions there are

const correct = ["answer1", "answer2", "answer3", "answer4"];
document.getElementById("quizForm").addEventListener("submit", e => {
  e.preventDefault(); // stop submit
  const f = [...document.querySelectorAll(".Radio-Button:checked")]
    .filter(rad => correct.includes(rad.id)).length; // count correct answers
  const a = f === correct.length ? "Y" : "N";
  document.getElementById("score").innerHTML = `Score:${f}/${correct.length} ${a}`;
});
<form id="quizForm">

Answer True or False on questions

Is ___

    <input class="Radio-Button" id="answer1" name="T/F1" type="radio">True

    <input class="Radio-Button" name="T/F1" type="radio">False

Is ___

    <input class="Radio-Button" id="answer2" name="T/F2" type="radio">True

    <input class="Radio-Button" name="T/F2" type="radio">False

Is ___

    <input class="Radio-Button" id="answer3" name="T/F3" type="radio">True

    <input class="Radio-Button" name="T/F3" type="radio">False

Is ___

    <input class="Radio-Button" id="answer4" name="T/F4" type="radio">True

    <input class="Radio-Button" name="T/F4" type="radio">False

    <button>Submit</button>

Score:Not Submitted

</form>


text:
Q: With the $uwv$ method, why can $3v^2$ be negative? If we define $3v^2 = ab+bc+ca$, then doesn't that mean $3v^2$  must be positive due to the exponentiation and positive $3$?
I note that if for example $a = −1, b = −2, c = 3$ we get $3v^2 = −7$! I understand that the algebra is not tricking me but I am just not convinced that two positives multiply to form a negative.


text:
Q: Changing Google Analytics transport type to work around redirects We've implemented a Content Security Policy (CSP) header recently on the website where we restrict sources from which the content can be loaded on the page.
After that we've noticed a curious behaviour of Google Analytics with display features task enabled. It loads a tracking pixel from google-analytics.com/r/collect, then redirect to doubleclick.net domain which then redirects to google.com/ads/ga-audiences which then redirects further to google.gTLD/ads/ga-audiences, where gTLD is Google's geographic top-level domain depending on the user's location. As we didn't put every top-level domain in the CSP header we started to get reports on the CSP violations.
Unfortunately, everything I could find about that was how to disable displayFeaturesTask either in Google Analytics or in the tracking code. But nothing that could disable redirects while keeping the feature.
I have found out myself that by changing the transport type to either xhr or beacon changes tracking behaviour to call google-analytics.com/r/collect without further redirects.
My question is what impact does transport type have on tracking performance comparing to default image type?


text:
Q: Find groups match IN condition list incompletely I'm currently working on a stored procedure and I need to write a query, which selects all GroupIds that don't have all TypeIds.
Regarding this example:
Id | GroupId | TypeId |
---+---------+--------+
1  |  1      |  1     |
2  |  1      |  2     |
3  |  1      |  3     |
4  |  2      |  1     |
5  |  2      |  2     |
6  |  3      |  1     |
7  |  3      |  2     |
8  |  3      |  3     |
9  |  4      |  2     |

I'd like to select GroupIds 2 and 4, because those groupes don't have all three TypeIds 1, 2 and 3. GroupId 4 only has TypeId 2 while GroupId 2 only has TypeIds 1 and 2.
My current query looks like this, but doesn't work:
SELECT [A].ActorPoolId
FROM [OfferCatalog].[Actor] [A]
WHERE [A].ActorTypeId IN ('1', '2', '3')

Do you know how to solve this issue?

A: You can user a group by + having combination:
select [A].ActorPoolId
from [OfferCatalog].[Actor] [A]
where [A].ActorTypeId in ('1', '2', '3')
group by [A].ActorPoolId
having count(distinct [A].ActorTypeId) < 3

You can omit using distinct in case ActorTypeId is unique for each ActorPoolId.


text:
Q: "Fixing" large angles in C I need to be able to compare angles that are multiples of 45 in C (input always in degrees).
I've written the code for basic angles 0,45,90,135,180...
But I can also get large angles like 2070 which is the same as 90.
How do I do it? (Sorry if it's a terribly simple question, I'm just getting into this)
So far, I've tried converting the angle to radians and using the sine function. But the problem is that I can't compare them using the == operator.
This is the only way I've learned to compare values in C so far
double direction;
scanf("%d", &direction);

int x = sin(direction * 0.0174533);
//Wanted to use the == operator, so I thought I'd assign the sin to an int.

if (x == 1) {
    someInstruction();
}

The problem is that when I make it into an int, the value becomes 0 and not 1.

A: You don't need to calculate the sine of the angle if you like to compare them. Actually it will give you headaches because exact equality of floating point values has its own problem. I'm not going deeper in it, if you're interested the research is left as an exercise for you.
Instead I'd like to introduce the "modulo" operator to you. This operator does a integer division and returns the remainder. In C and derived languages the operator is "%".
So you let the user input the angle as integer and calculate the remainder of the division by 360: int remainder = input % 360;
Examples:
input remainder
   0    0
 135  135
2070  270
3645   45

A: when you convert double to int it truncate the number to the closest int in the case of sin it's either -1/0/1.
dummy example:
double x_d =1.2;
int x_i = x_d

will result in x_i=1
You need to keep it as double or even float so it will keep the output of the sin and you can do the testing you desire.
As Arya11 mentioned a more elegant way to approach the issue is using the modulo operator % which you need to only check if the direction is a multiple of the desired angle.


text:
Q: Python Flake 8 Lint can't ignore specific errors working in Sublime Text 3 I set specific errors ("D", "E123", "E126") to ignore in default Flake8Lint.sublime-settings:
{
    "python_interpreter": "auto",
    "builtins": [],
    "pyflakes": true,
    "pep8": true,
    "pydocstyle": true,
    "naming": true,
    "import-order": true,
    "import-order-style": "google",
    "complexity": -1,
    "pep8_max_line_length": 79,
    "select": [],
    "ignore": ["D", "E123", "E126"],
    "ignore_files": []
}

But those errors are still detected and displayed. Does anyone know how to fix it? Thank you!

A: I have two suggestions:

*

*Use Sublime Linter. It looks like you are using the Python Flake8 Lint package which is no longer maintained (see the note at the top of the readme here). Sublime Linter is a great package which is well maintained and very extensible.

*Once you have Sublime Linter installed and running, follow the instructions at https://hightower.space/thoughts/sublime-linter-ignore-guide/ for ignoring linter errors. I ran into some similar problems trying to ignore linter errors and wrote a short guide on how to ignore Sublime Linter errors.

If you don't want to install Sublime Linter, you can see if any of these changes work:
"ignore": "D,E123,E126",

or replace the "ignore" key with:
"args": "--ignore D,E123,E126",

I know flake8 changed the way rules are ignored earlier this year (there is an issue about it here) and I'm guessing the package you are using hasn't been updated to facilitate this change.


text:
Q: Wrapping class method via alias_method_chain in plugin for Redmine I am not sure if this problem is a general Rails problem or Redmine specific.
There is a class User which has a class method try_to_login. I wrote a module containing a method_alias_chain to wrap that method and provide additional functionality. This works fine if I go into the console and call try_to_login. My wrapper will be executed and everything is fine. However, when I run this on the server just the vanilla method is called. The wrapper is never touched. I added a logger command to the vanilla method to be sure and it is in deed being called.
Here is a simplified version of the code:
require_dependency 'principal'
require_dependency 'user'
require 'login_attempt_count'

module UserLoginAttemptLimiterPatch

  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      class << self
        alias_method_chain :try_to_login, :attempt_limit
      end
    end
  end

  module ClassMethods
    def try_to_login_with_attempt_limit(login, password)

      user = try_to_login_without_attempt_limit login, password

      #stuff here gets called via console but not via browser

      user
    end

    def authentication_failed(login)
      #important code here
    end

  end
end

User.send(:include, UserLoginAttemptLimiterPatch)

In addition this module is required when the plugin is loaded.

A: How are you requiring the module?  If you are running in development mode, the User class could be reloaded after the first request which would clear out your patch and alias_method_chain.
You can get around it by doing the patch inside of a Dispatcher (which runs with every code reload):
require 'dispatcher'

Dispatcher.to_prepare do
  Issue.send(:include, MyMooPatch)
end

Reference: http://theadmin.org/articles/2009/04/13/how-to-modify-core-redmine-classes-from-a-plugin/


text:
Q: Is it alright to override MappingJackson2HttpMessageConverter to support HAL+JSON? In my Spring Boot application, I have assigned the HAL object-mapper to MappingJackson2HttpMessageConverter. This is because my custom media-types end with +json and end up being recognized by the default converter. The custom MappingJackson2HttpMessageConverter instance registered by Spring HATEOAS only recognizes application/hal+json. My custom media-types are of the form application/vnd.service.entity.v1.hal+json, which are recognized by the default instance (because it supports application/json and application/*+json). However, the default instance does not serialize links properly into the HAL convention. I have been able to get around it by registering the mapper like so:
@Bean
public HttpMessageConverters customConverters() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(
            new MediaType("application", "json", Charset.defaultCharset()),
            new MediaType("application", "*+json", Charset.defaultCharset()),
            new MediaType("application", "hal+json")
    ));

    ObjectMapper halObjectMapper = beanFactory.getBean(HAL_OBJECT_MAPPER_BEAN_NAME, ObjectMapper.class);
    converter.setObjectMapper(halObjectMapper);

    return new HttpMessageConverters(converter);
}

There is a concern that I am now polluting regular JSON serialization/deserialization with HAL concerns, but I cannot think of any other way (short of explicitly specifying every single custom media-type I use) to do this. Thoughts?


text:
Q: C# Loading data adapter from excel, is there a maximum column count? I'm running into an issue trying to create a c# data table from an excel spreadsheet. The code is simple but for some reason when I step through it, the data table only loads with 256 of the 700 columns that are in the spreadsheet. Looking at the code below, Settings.Excel_Proj_Select is just "Select * from Project_Data$". Is there a maximum column count and if so, is there a way around this to get the full sheet into a data table?
        public static DataTable getRowData()
        {

        OleDbConnection cnn = new OleDbConnection(Settings.ExcelCN);
        OleDbCommand oconn = new OleDbCommand(Settings.Excel_Proj_Select, cnn);
        cnn.Open();
        OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        cnn.Close();

        dt.Columns.Add("Extract_Date", typeof(string));
        foreach (DataRow row in dt.Rows)
        {
            row["Extract_Date"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        return dt;
    }

Any info is appreciated. Thank you!

A: There appears to be a 255 max number of columns when using the Ole provider for this, yes.
But you can use a simple workaround by specifying the range in your queries:
//Modify the range to suit your needs
SELECT * FROM Project_Data$[RANGE]:[HERE]

You can then run multiple queries, each which SELECT different ranges, then combine the data.
Please see here for another method using OpenXML.


text:
Q: What is the general way of finding a probability that Markov chain goes to absorbing state Given an NxN matrix like the on shown here:
$$
\mathbf{M} = \matrix{~ \\
              & 0 & 0.5 & 0 & 0 & 0 & 0.5\\
              & 0.5 & 0 & 0 & 0.3 & 0.2 & 0 \\
              & 0 & 0 & 1 & 0 & 0 & 0\\
              & 0 & 0 & 0 & 1 & 0 & 0\\
              & 0 & 0 & 0 & 0 & 1 & 0\\
              & 0 & 0 & 0 & 0 & 0 & 1
              }
$$
What is the general way of finding the probability of going from state_0 (represented by first row) into each absorbing state (s2, s3, s4, s5 in this case) for any NxN matrix, if it is guaranteed that the matrix will have at least one absorbing state?


text:
Q: Azure Blob Storage with Apache Flink 1.10 I am trying to use Azure Blob Storage with Apache Flink 1.10 for checkpointing purposes.
I followed all the instructions mentioned in [Flink Documentation][1] https://ci.apache.org/projects/flink/flink-docs-release-1.10/ops/filesystems/azure.html
Step 1:
mkdir ./plugins/azure-fs-hadoop
cp ./opt/flink-azure-fs-hadoop-1.10.0.jar ./plugins/azure-fs-hadoop/
Step 2:
This is what I have in flink-conf.xml
#Azure Storage Key
**fs.azure.account.key.<storage-account>.blob.core.windows.net:xxxxxxxxxxxxxxxxxx**
Step 3:
Use Azure Blob storage for checkpointing
This is what I have in my flink job
final StateBackend stateBackend = new FsStateBackend("wasb://flink-blob@$<storage-account>.blob.core.windows.net/checkpoint");
I am not sure if i missed anything here but when I submit the job, I get below Exception (AskTimeoutException from Actor).
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:335)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:205)
    at org.apache.flink.client.ClientUtils.executeProgram(ClientUtils.java:138)
    at org.apache.flink.client.cli.CliFrontend.executeProgram(CliFrontend.java:664)
    at org.apache.flink.client.cli.CliFrontend.run(CliFrontend.java:213)
    at org.apache.flink.client.cli.CliFrontend.parseParameters(CliFrontend.java:895)
    at org.apache.flink.client.cli.CliFrontend.lambda$main$10(CliFrontend.java:968)
    at org.apache.flink.runtime.security.NoOpSecurityContext.runSecured(NoOpSecurityContext.java:30)
    at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:968)
Caused by: java.lang.RuntimeException: java.util.concurrent.ExecutionException: org.apache.flink.runtime.client.JobSubmissionException: Failed to submit JobGraph.
    at org.apache.flink.util.ExceptionUtils.rethrow(ExceptionUtils.java:199)
    at org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.executeAsync(StreamExecutionEnvironment.java:1741)
    at org.apache.flink.streaming.api.environment.StreamContextEnvironment.executeAsync(StreamContextEnvironment.java:94)
    at org.apache.flink.streaming.api.environment.StreamContextEnvironment.execute(StreamContextEnvironment.java:63)
    at org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.execute(StreamExecutionEnvironment.java:1620)
    at com.example.flink.checkpointing.CheckpointExample.main(CheckpointExample.java:78)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:321)
    ... 8 more
Caused by: java.util.concurrent.ExecutionException: org.apache.flink.runtime.client.JobSubmissionException: Failed to submit JobGraph.
    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
    at org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.executeAsync(StreamExecutionEnvironment.java:1736)
    ... 17 more
Caused by: org.apache.flink.runtime.client.JobSubmissionException: Failed to submit JobGraph.
    at org.apache.flink.client.program.rest.RestClusterClient.lambda$submitJob$7(RestClusterClient.java:359)
    at java.base/java.util.concurrent.CompletableFuture.uniExceptionally(CompletableFuture.java:986)
    at java.base/java.util.concurrent.CompletableFuture$UniExceptionally.tryFire(CompletableFuture.java:970)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088)
    at org.apache.flink.runtime.concurrent.FutureUtils.lambda$retryOperationWithDelay$8(FutureUtils.java:274)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
    at java.base/java.util.concurrent.CompletableFuture.postFire(CompletableFuture.java:610)
    at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1085)
    at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:478)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.flink.runtime.rest.util.RestClientException: [Internal server error., <Exception on server side:
akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://flink/user/dispatcher#75666936]] after [10000 ms]. Message of type [org.apache.flink.runtime.rpc.messages.LocalFencedMessage]. A typical reason for `AskTimeoutException` is that the recipient actor didn't send a reply.
    at akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:635)
    at akka.pattern.PromiseActorRef$.$anonfun$apply$1(AskSupport.scala:650)
    at akka.actor.Scheduler$$anon$4.run(Scheduler.scala:205)
    at scala.concurrent.Future$InternalCallbackExecutor$.unbatchedExecute(Future.scala:870)
    at scala.concurrent.BatchingExecutor.execute(BatchingExecutor.scala:109)
    at scala.concurrent.BatchingExecutor.execute$(BatchingExecutor.scala:103)
    at scala.concurrent.Future$InternalCallbackExecutor$.execute(Future.scala:868)
    at akka.actor.LightArrayRevolverScheduler$TaskHolder.executeTask(LightArrayRevolverScheduler.scala:328)
    at akka.actor.LightArrayRevolverScheduler$$anon$3.executeBucket$1(LightArrayRevolverScheduler.scala:279)
    at akka.actor.LightArrayRevolverScheduler$$anon$3.nextTick(LightArrayRevolverScheduler.scala:283)
    at akka.actor.LightArrayRevolverScheduler$$anon$3.run(LightArrayRevolverScheduler.scala:235)
    at java.base/java.lang.Thread.run(Thread.java:834)

End of exception on server side>]
    at org.apache.flink.runtime.rest.RestClient.parseResponse(RestClient.java:390)
    at org.apache.flink.runtime.rest.RestClient.lambda$submitRequest$3(RestClient.java:374)
    at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1072)
    ... 4 more```

A: I think your problem is twofold. The true failure cause is hidden because of the AskTimeoutException. This problem has been solved with FLINK-16018 which will be released with Flink 1.10.1. The problem is that the timeout value is too aggressive so that a long lasting job submission will fail on the client side.
For the true failure cause, I would recommend to take a look at Flink's jobmanager.log. It should contain information about what went wrong. I would suspect that there is a misconfiguration of the Azure Blob Storage.

A: That's correct. You must set your checkpoints.dir and savepoints.dir in the following format and use
fs.azure.account.key.<storage-account-name>.blob.core.windows.net:<key>

wasbs://<container>@<storage-account-name>.blob.core.windows.net/<directory>/


text:
Q: How to send and receive protobuf messages over Akka Tcp I'm using ScalaPB for my protobuf compiler which generates Scala case classes, parsers and serializers for my protocol buffers.
I have a simple protobuf message in a .proto file that has been compiled to a Scala case class thanks to ScalaPB.
option java_outer_classname = "MovementProtos";

message Move {
    required string direction = 1;
    required string mode = 2;
}

This file is compiled and allows me to do something like:
val move = Move(direction = "up", mode = "walk")

I have an Akka actor handling a TCP connection.
class PacketHandler extends Actor {

  def receive: Receive = {
    case m: Move =>
      // successfully matched against Move case class message
    case Tcp.Received(data) =>
      // didn't match any messages
    case _: Tcp.ConnectionClosed =>
      context.stop(self)
  }
}

If I send a Move protobuf message to my PacketHandler, will it successfully match against my Move case class with how I've wrote my receive?
How do I send a Move protobuf message? Let's say when it successfully matches against a Move protobuf message it echoes it back.
def receive: Receive = {
  case m: Move =>
    // successfully matched against Move case class message
    // now echo back 'm' over the wire
    sender ! Tcp.Write(???)
  ...
}

I have no client to test my PacketHandler actor so I've been using telnet.
It would also be useful to know what the encoded Move message looks like exactly so I can create my connection over telnet and send the encoded message over the wire and test whether it gets decoded when it reaches PacketHandler.

A: One way is to send instances as Akka messages. ie. sender ! Tcp.Write(m). The instances are sent with all the binary overhead of a Scala class. But that sort of defeats the point of using protocol buffers.
Bandwidth is usually one of the scarcest/slowest resources in a system so typically you would use the protobuf serialization and deserialization functions for rpc. You serialize using any of the to~ functions (ie. toByteString) and deserialize using  parseFrom.


text:
Q: Is libunwind implementation of abi in libcxxabi? I was trying to build libcxx/libcxxabi/libunwind when I realized that I didn't actually understand what role they play.
I checked libcxxabi spci, and found that it defines API used in C++ exception. But I can't find any document about libunwind,  and one blog(New libunwind implementation in libc++abi) I found by google says that libunwind is the implementation of libcxxabi.
So, is libunwind really like that, implements ABI in libcxxabi, if so, why we have libcxxabi?

A: I built libunwind myself and checked the symbols in libunwind by using nm and got these:
nm: libunwind.cpp.o: File format not recognized
nm: Unwind-EHABI.cpp.o: File format not recognized
nm: UnwindLevel1.c.o: File format not recognized
nm: UnwindLevel1-gcc-ext.c.o: File format not recognized
nm: Unwind-sjlj.c.o: File format not recognized

UnwindRegistersRestore.S.o:
0000000000000000 T _ZN9libunwind16Registers_x86_646jumptoEv

UnwindRegistersSave.S.o:
0000000000000000 T unw_getcontext

That seems to imply that libunwind just implements the unwind functions, nothing else.


text:
Q: Button click not changing the .html in jquery Can someone tell me what is happening, why my counter in id="love" is not increasing  when  button with id="buttonattr" is clicked, here's my code :
<button class="btn btn-default buttonattr"style="font-family:Pangolin"   onclick="myhit(\''+this["post"]+'\',\''+this["love"]+'\');myclick()"> Love</button>
'+this["love"]+' students

for script:
    var toAdd=1;var newValue=0;
var overall=1;
function myhit(post,love){

oldValue=parseInt(love);
if(toAdd>0){
 newValue= oldValue + toAdd;
}
else{
 newValue=overall+toAdd;
}
toAdd *= -1;
 overall=newValue;
$.post('porthome4_.php',{post1:post,love:newValue},function(info){});
}
function myclick(){
$('.buttonattr').click(function(){
$(this).find('#love').html(overall);
$(this).find('#love').append(' students');
 });
}

A: You need to use the click() event after the DOM ready state:
$(function() {
   // Handler for .ready() called.
   $('.buttonattr').click(function(){
     $(this).find('#love').html(overall);
     $(this).find('#love').append(' students');
   });
});

A: Your jQuery should be wrappered with
$(document).ready({
//code here
})

This ensures the document is ready before registering Dom events.
Jquery Document Ready Explanation

A: function myclick(){
    $('.buttonattr').click(function(){
        $(this).find('#love').html(overall);
        $(this).find('#love').append(' students');
    });
}

The binding of the click event is done in a function.
That means that as long as you don't call that function, it's as if you never wrote that code above.
Remove that myclick() function and it may work.
Put that whole code in a $(document).ready() and it will be even better, since nothing would happen before the DOM is fully loaded, reducing the possibility that some event binding is attempted before the elements that should be bound are loaded, preventing them for being bound :
$(document).ready(function() {
   // Your code here
});


text:
Q: What is $a_n$, if $\sum_0^\infty a_n x^n = (\sum_0^\infty x^n )(\sum_0^\infty x^{2n})$ I found a answer here https://math.stackexchange.com/a/2174836/533661
But why the answer uses $\sum x^n=\frac{1}{1-x}$? To use that, we must assume $|x|<1$, but the question does not assume that.
And how the answer got $a_n$ from $a_{2n+1}=a_{2n}, a_{2n}=a_{2n-1}+1$

A: \begin{eqnarray*}
\sum_{n=0}^{\infty} x^n \sum_{m=0}^{\infty} x^{2m} = \frac{1}{(1-x)} \frac{1}{(1-x^2)}
\end{eqnarray*}
Multiply top & bottom by $(1+x)$ and split the function into its odd & even powers.
\begin{eqnarray*}
\frac{1+x}{(1-x^2)^2} &=& \color{blue}{\frac{1}{(1-x^2)^2}} +\frac{x}{(1-x^2)^2} \\
&=& \color{blue}{\sum_{i=0}^{\infty} (i+1) x^{2i}} +\sum_{i=0}^{\infty} (i+1) x^{2i+1}.
\end{eqnarray*}
The above series can be considered as "Formal Power series" to represent the sequence $1,1,2,2,3,3,\cdots$ and for combinatorialists their convergence in an analytic sense is not of interest.

A: hint
For the second point:
If we put $$b_n=a_{2n+1}$$
then
$$b_n=a_{2n}=a_{2n-1}+1=b_{n-1}+1$$
thus $ (b_n) $ is arithmetic. So,
$$b_n=b_0+n=a_1+n=a_{2n+1}$$
and
$$a_{2n}=a_{2n+1}=a_1+n$$

A: Well, we could write it this way:
$$\begin{aligned} \sum_{n=0}^\infty a_n x^n &= \left(\sum_{j=0}^\infty x^j \right)\left(\sum_{k=0}^\infty x^{2k}\right)\\
& =\sum_{j=0}^\infty \sum_{k=0}^\infty x^j x^{2k} \\
& =\sum_{j=0}^\infty \sum_{k=0}^\infty x^{j+2k} \\
\end{aligned}
$$
but if we notice that
$$\sum_{x=0}^\infty  x^n=\frac{1}{1-x}$$
and
$$\sum_{x=0}^\infty  x^{2n}=\frac{1}{1-x^2}$$
so that
$$\sum_{n=0}^\infty a_n x^n = \frac{1}{1-x} \cdot \frac{1}{1-x^2}$$
we could make use of the coefficients for the McLauren series.  Better yet, write this as a partial fraction expansion (as was done over at the link to the solution) and read off the coefficients.
Both series converge if and only if $|x|<1$, so that is understood.


text:
Q: Make QWidget disappears after click not on it I'm showing QTableWidget, and want it to disappear after some item in this table was selected and if user clicked outside  QTableWidget area.
connect(tableWidget, SIGNAL(itemClicked(QTableWidgetItem *)), tableWidget, SLOT(close()));

this line do what I want after selecting item. Is it a way of make widget disappears after clicking not on it without  subclassing it (I can subclass and write my own losefocus event handler, for example, but without subclassing would be better)?

A: let's assume, you have MainWidget, that contains everything within it. It has clicked() signal. Connect that to some slot and in that slot hide tableWidget ( tableWidget()->hide() )

A: This is probably not a very elegant solution, but it might work:

*

*Subclass QTableWidget

*Make sure that the table widget has the keyboard focus while you display it.

*Reimplement void QWidget::focusOutEvent ( QFocusEvent * event ) (close the table widget, when you lose focus)

A: My solution was to put QTableWidget into QWidget and made the latter Qt::Popup - an it acts exactly how I need


text:
Q: Force Maven to Fail if Java Runtime is Above A Given Version I have a situation with a legacy project, where I need a project to fail if Maven is invoked with a JDK runtime other than 1.8 or 1.9. The reason being that the current project has dependencies that were part of the JDK once, but not anymore starting with JDK 11.
This is distinct from specifying source and target versions for the maven-plugin compiler (which are currently set at 8.)
The build already fails, complaining about unresolvable dependencies, but I would like it to fail with a message saying "you need to use a JDK 8/9 runtime" instead (clarity is always king.)
This is just a stop-gap measure to avoid people sending panic emails about things not compiling because they used JDK 11+, and where I cannot rely on everybody setting their own JDK's in their toolchains.xml.

A: You can use the maven enforcer plugin:
<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>3.0.0-M3</version>
        <executions>
          <execution>
            <id>enforce-java</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireJavaVersion>
                  <version>[1.8,9]</version>
                </requireJavaVersion>
              </rules>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

CAUTION: I didn't test the range expression.
Source: https://maven.apache.org/enforcer/enforcer-rules/requireJavaVersion.html


text:
Q: PHP no registra en la DB MySQL Al querer insertar datos en MYSQL, el código de PHP no lo hace. Traté de basarme en otro código que realiza la misma acción, para ver si veia el error, pero no lo pude encontrar de ninguna manera.
(Los datos provienen de un formulario)
guardar.php
<?php

    include("con_db.php");

    if (isset($_POST['submit'])) {

        if  (strlen($_POST['nombre'])     >= 1 &&
            strlen($_POST['apellido'])   >= 1 &&
            strlen($_POST['telefono'])   >= 1 &&
            strlen($_POST['mail'])       >= 1 &&
            strlen($_POST['dni'])        >= 1 &&
            strlen($_POST['nacimiento']) >= 1 &&
            strlen($_POST['domicilio'])  >= 1 &&
            strlen($_POST['localidad'])  >= 1 &&
            strlen($_POST['provincia'])  >= 1 &&
            strlen($_POST['cp'])         >= 1) {

                $fecareg    = date("d/m/y");
                $nombre     = trim($_POST['nombre']);
                $apellido   = trim($_POST['apellido']);
                $telefono   = trim($_POST['telefono']);
                $mail       = trim($_POST['mail']);
                $dni        = trim($_POST['dni']);
                $nacimiento = trim($_POST['nacimiento']);
                $domicilio  = trim($_POST['domicilio']);
                $localidad  = trim($_POST['localidad']);
                $provincia  = trim($_POST['provincia']);
                $cp         = trim($_POST['cp']);
                $consulta   = "INSERT INTO pacientes(id, fecareg, nombre, apellido, telefono, mail, nacimiento, dni, domicilio, localidad, provincia, cp) VALUES ('$facareg','$nombre','$apellido','$telefono','$mail','$dni','$nacimiento','$domicilio','$localidad','$provincia','$cp')";
                $resultado  = mysqli_query($conex,$consulta);

                if ($resultado) {
                    ?>
                        <META HTTP-EQUIV="REFRESH" CONTENT="1;URL=../index.html">
                    <?php
                } else {
                    ?>

Ups ha ocurrido un error

                    <?php
                }
        } else {
            ?>

Completa los campos

            <?php
        }
    }

?>

con_db.php
<?php

    $conex = mysqli_connect("localhost", "root", "12345!!", "excel");

?>

A: *

*fijate si realmente funciono la conexion a la bd
$enlace = mysqli_connect("127.0.0.1", "mi_usuario", "mi_contraseña", "mi_bd");

if (!$enlace) {
 echo "Error: No se pudo conectar a MySQL." . PHP_EOL;
 echo "errno de depuración: " . mysqli_connect_errno() . PHP_EOL;
 echo "error de depuración: " . mysqli_connect_error() . PHP_EOL;
 exit;
}

*revisa la consulta para ver si no hay error de sintaxis
esto se ve raro
$consulta   = "INSERT INTO pacientes(id, fecareg, nombre, apellido, telefono, mail, nacimiento, dni, domicilio, localidad, provincia, cp) VALUES ('$facareg','$nombre','$apellido','$telefono','$mail','$dni','$nacimiento','$domicilio','$localidad','$provincia','$cp')";

deberia algo asi
mysqli_query("INSERT INTO tabla (column 1, column2) VALUES ('".$_POST['value1']."', '".$_POST['value2']."')");

A: Prueba que la conexión sea exitosa, seguido de que tu consulta lo haría de esta manera.
    $mysqli = new mysqli('localhost', 'root', '12345!!', 'excel') or die (mysql_error($mysqli));

    $nombre = '';
    $apellido = '';

if (isset($_POST['submit'])){
    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];

    $mysqli->query("INSERT INTO pacientes (nombre, apellido) VALUES ('$nombre', '$apellido')") or die($mysqli->error);

header("location: index.php");

}


text:
Q: Alamofire with google geocoding api In one of my apps I need to geocode address string. At first I considered using CLGeocoder. However, after I tried it I stumbled upon a problem which I described in this question.
The solution was to use Google's Geocoding APIs instead. I have now switched to them and managed to get them working by having the following functions:
func startConnection(){
    self.data = NSMutableData()
    let urlString = "https://maps.googleapis.com/maps/api/geocode/json?address=\(searchBar.text!)&key=MYKEY"

    let linkUrl:NSURL = NSURL(string:urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)!
    let request: NSURLRequest = NSURLRequest(URL: linkUrl)
    let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
        connection.start()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? [String: AnyObject] {
            print(json)
        }
    }
    catch {
        print("error1")
    }
}

This works great and resolves the problem which I had with CLGeocoder. However, in addition to extracting the coordinates of place, I need to also use Google's Timezone APIs to extract the timezone for each place.
Doing this with the NSURLConnection or NSURLSession seems to me a bit difficult as I would need to keep track of which session/connection returns. So, I would like to have some solution which uses completion handlers.
I have tried using Alamofire framework (using the correct branch for Swift 2.0). However, it seems like request() function is the wrong one to use in this case. I have tried:
let parameters = ["address":searchBar.text!,"key":"MYKEY"]
Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.AllowFragments) { _, _, JSON in
            print(JSON)
        }

And all I am getting printed is "SUCCESS". I hope that I am doing something wrong and it can be fixed because I would really like to be able to use closures instead of delegate calls.
My questions are:

*

*Is it possible to use Alamofire with Google Geocoding APIs?

*If so, can you please tell me what am I doing wrong?

*If it is not possible, can you please suggest me how to design a system with NSURSessions or NSURLConnections which would allow me to use completion handlers for each call instead of delegates?

P.S. I am aware that I can use synchronous requests but I would really like to avoid using that option
Update
It was suggested that adding .MutableContainers as an option should make responseJSON work. I tried the code below:
let apiKey = "MYKEY"
var parameters = ["key":apiKey,"components":"locality:\(searchBar.text!)"]
Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.MutableContainers) { one, two, JSON in
    print(JSON)
}

And all I get printed is "SUCCESS".

A: Ok, I have finally figured this out (with the help from @cnoon). The value which is returned is of type Result. I couldn't find documentation for it, but the source code is available here.
In order to retrieve JSON below implementation can be used:
Alamofire.request(.GET, "https://mapss.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.MutableContainers) { _, _, JSON in
    switch JSON {

    case .Failure(_, let error):
        self.error = error
        break

    case .Success(let value):
        print(value)
        break

    }
}

The value printed is the correct representation of response from Geocoding APIs.


text:
Q: Is creating new phtml is allowed in magento go? Is creating/adding new phtml is allowed in magento go? Please let me know as I am new to magento go.

A: No you can not add any phtml file in magento go, magento go has not access of any file structure.
Besides you can only change in your theme css or add js code in design configuration Miscellaneous Scripts option.


text:
Q: Testing @ConfigurationProperties with Mockito I have  configuration class:
@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
    protected String config;
}

My service uses this config class (That gets the value from application.yml):
@Service
public class myService {

    @Inject
    private MyConfig myConfig;

    Public String getInfo (String param) {
        if (isEmpty(param)) { throw new InvalidParameterException; }
        return myConfig.getConfig();
    }
}

I'm trying to test it with Mockito:
@RunWith(MockitoJUnitRunner.class)
public class myTest {

    @InjectMocks
    private MyService myService;

    @Mock
    private MyConfig myConfig;

    @Test
    public void myTest1() {
        myService.getInfo("a");
    }

    @Test
    public void myTest2() {
        assertThrows(InvalidParameterException.class, ()->myService.getInfo(null));
    }
}

myTest fails since the config class is mocked, thus has null values.
What is the right way to test configuration class with Mockito?
Edit:
I have a number of config classes like the one above that are being used in myService.

A: You need to create getter which then can be mocked by Mockito.
@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
    protected String config;

    public String getConfig() {
        return config;
    }
}

.
@RunWith(MockitoJUnitRunner.class)
public class myTest {

    @InjectMocks
    private MyService myService;

    @Mock
    private MyConfig myConfig;

    @Before
    private void initializeConfig() {
        when(myConfig.getConfig()).thenReturn("someValue");
    }

    @Test
    public void myTest1() {
        myService.getInfo("a");
    }
}

But if you don't want to set the value explicitly in test, you should create a Spring integration test which would create the whole context and use the real objects. But this is out of scope of this question.

A: You should mark MyConfig with @Configuration so that Spring creates a Spring bean in the application context.
you also need to use @RunWith(SpringRunner.class)
The SpringRunner provides support for loading a Spring ApplicationContext and having beans @Autowired into your test instance.
Also change @Inject with @Autowired because i am not sure how @inject will be supported by spring
Service Class
@Service
public class myService {

    @Autowired
    private MyConfig myConfig;

    Public String getInfo {
        return myConfig.getConfig();
    }
}

Test class
@RunWith(SpringRunner.class)
public class myTest {

    @Mock
    private MyService myService;

    @InjectMocks
    private MyConfig myConfig;

This is way you should get real object in test
EDIT
Considering you don't want to mock myservice then we should replace your test class with below and let me know
@RunWith(SpringRunner.class)
public class myTest {

@autowired
private MyService myService;

@Test
public void myTest1() {
    myService.getInfo("<NAME_OF_PROPERTIES>");
}

@Test
public void myTest2() {
    assertThrows(InvalidParameterException.class, ()->myService.getInfo(null));
}

A: I had a similar issue, so I want to provide my solution, maybe will be helpful for someone, I had a test class that uses Mockito to mock some dependency, but I also needed to use a yaml and of course I didn't want to set values manually using "when(myConfig.getConfig()).thenReturn("someValue");"
I simply solved it by using SpringExtension along with MockitoExtension.
@EnableConfigurationProperties
@ContextConfiguration(classes = { MyConfig.class })
@Extensions({
        @ExtendWith(SpringExtension.class),
        @ExtendWith(MockitoExtension.class)
})
class MyTest {

    @Autowired
    private MyConfig myConfig;

}

for more details: How to test Externalized Configuration reading from yaml


text:
Q: Is there a chrome extension to setup proxies and switch between them using a programming language? I'm developing a selenium application that uses undetected chromedriver as a web driver, I want to use the application with a proxy, undetected chromedriver doesn't really have a functional way to add a proxy, I am wondering if there's a chrome extension that allows you to add a proxy using a programming language, I'm developing my selenium application in Python. Otherwise, I'll appreciate any way to implement a proxy to my application efficiently. Thanks for your time.
I tried selenium-wire, but the web drivers are missing quite so many classes and do behave poorly. I also tried a lot of chrome extensions, they require you to use their UI. I also tried a project I found at github but it doesn't support undetected chromedriver. There's a chrome extension that does what I need according to its description but it's not functional.


text:
Q: access method from template in wpf I'm using WPF with the caliburn micro framework to implement a MVVM pattern.
I've created a popup that gets filled with custom buttons inside a ListBox.
Now I want to call a method in my ViewModel when one of these buttons is clicked, but each approach I tried so far failed.
Here the code in comments works in the sense that it calls my method, but the parameter is always null.
<ListBox x:Name="lst" ItemsSource="{Binding OperatingModes}" ItemTemplate="{DynamicResource DataTemplate_Level1}" BorderThickness="0" ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <!--<i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown" >
            <cal:ActionMessage MethodName="SelectMode">
                <cal:Parameter Value="{Binding ElementName=lst, Path=SelectedItem}" />
            </cal:ActionMessage>
        </i:EventTrigger>
    </i:Interaction.Triggers>-->
</ListBox>

And this is the Template I'm using. Whenever I call this method, I'm getting "No target found for method SelectMode." As you can see, I've tried different aproaches, although I'm not sure that I used the TargetWithoutContext call properly.
As far as I can tell I need to somehow bind my template to the data context of the "normal" xaml code, but I failed so far. How do I access my method properly?
<DataTemplate x:Key="DataTemplate_Level1" x:Name="myListTemplate" >
    <ListBox ItemsSource="{Binding}" BorderThickness="0" ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">
        <StackPanel Orientation="Vertical" HorizontalAlignment="Center" cal:Bind.Model="{Binding}" cal:Action.TargetWithoutContext="{Binding DataContext, ElementName=lst}">
            <Button Style="{StaticResource InformButton}" Content="{Binding Path=Name}" FontSize="11" BorderBrush="BlueViolet" cal:Message.Attach="SelectMode($dataContext)">
                <!--<i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseRightButtonDown" >
                        <cal:ActionMessage MethodName="SelectMode">
                            <cal:Parameter Value="{Binding ElementName=myListTemplate, Path=SelectedItem.Name}" />
                        </cal:ActionMessage>
                    </i:EventTrigger>
                </i:Interaction.Triggers>-->
            </Button>
        </StackPanel>
    </ListBox>
</DataTemplate>


text:
Q: Erorr in python using both split and while loop and external text file I'm new to Python and so am confused by the following "list index out of range" error I get with the following code as my text file only contains 4 items in it which are first name, last name, hourly salary, total hours worked. Should this be changed to something that's not a while loop? If need be I can give the entire code. Any help would be greatly appreciated!
while line2 != "":
    line2 = " "
    line2 = line2.split( " " )
    if (line2[ 0 ]+ " " + line2[ 1 ]) != name1.rstrip( " \n " ):
    empFile3.write(line2[ 0 ] + " " + line2[ 1 ] + " " + line2[ 2 ] + " " + line2[ 3 ] + " \n " )

A: The problem is in line no. 2. Remove that. You are getting that error because you are trying to split an empty string.
while line2 != "":
    line2 = line2.split( " " )
    if (line2[ 0 ]+ " " + line2[ 1 ]) != name1.rstrip( " \n " ):
       empFile3.write(line2[ 0 ] + " " + line2[ 1 ] + " " + line2[ 2 ] + " " + line2[ 3 ] + " \n " )


text:
Q: regex take string at the center i have this string
SMPN 2 Aesesa Selatan
SMPN 2 Aesesa Selatan
Desa/Kel. Lange Dhawe
Kec. Aesesa Selatan
Kab. Nagekeo
Nusa Tenggara Timur
Type : USB
Progress : COMPLETED

with regex (PHP) how do i take the second apearance of this substring "SMPN 2 Aesesa Selatan"
i tried
/
(SMPN2)(.*)<\/br\s+>/

it takes the second starting from
 until the last
 after substring "USB"
also the first and second of "SMPN 2 Aesesa Selatan" could be different at all.

A: Use the negated character class in regex

([^
]*)

Demo


text:
Q: Android Google Map crashes while launching With the following codes my google map crashes when the intent is going to be started. Please help me fix the code. Thanks in advance.
MainActivity.java
package com.example.googlemaps;

import info.androidhive.googlemapsv2.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

public class MainActivity extends Activity {

    // Google Map
    private GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            // Loading map
            initilizeMap();

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

    }

    /**
     * function to load map. If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="com.example.googlemaps.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.googlemaps.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.example.googlemaps.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCBZtSAObwgqcDwz7szpyXOxn3tCIhucdU" />
    </application>

</manifest>

and the Logcat
08-11 07:42:23.320: E/AndroidRuntime(2117): FATAL EXCEPTION: main

08-11 07:42:23.320: E/AndroidRuntime(2117): Process: info.androidhive.googlemapsv2, PID: 2117
08-11 07:42:23.320: E/AndroidRuntime(2117): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.googlemapsv2/com.example.googlemaps.MainActivity}: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.os.Looper.loop(Looper.java:136)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at java.lang.reflect.Method.invokeNative(Native Method)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at java.lang.reflect.Method.invoke(Method.java:515)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at dalvik.system.NativeStart.main(Native Method)
08-11 07:42:23.320: E/AndroidRuntime(2117): Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:714)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:756)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.Activity.setContentView(Activity.java:1929)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.example.googlemaps.MainActivity.onCreate(MainActivity.java:20)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.Activity.performCreate(Activity.java:5231)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-11 07:42:23.320: E/AndroidRuntime(2117):     ... 11 more
08-11 07:42:23.320: E/AndroidRuntime(2117): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 7571000 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.common.GooglePlayServicesUtil.zzaa(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.internal.zzy.zzaz(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.internal.zzy.zzay(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.MapFragment$zzb.zzvu(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.MapFragment$zzb.zza(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.dynamic.zza.zza(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.dynamic.zza.onInflate(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at com.google.android.gms.maps.MapFragment.onInflate(Unknown Source)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.app.Activity.onCreateView(Activity.java:4785)
08-11 07:42:23.320: E/AndroidRuntime(2117):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
08-11 07:42:23.320: E/AndroidRuntime(2117):     ... 21 more

That's it. And I use eclipse Juno and api is 4.4.2 API 19

A: Add this below MAP_KEY inside the AndroidManifest.xml file.
<meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />


text:
Q: MC Connect - Select Email address from a connected DE in "data designer" we are having a MC Connector integration between SFCRM and SFMC . Currently the Journey settings ]doesnt allow to use any other data extension connected in the Conatct Builder to be used as source for Email address.It shows only synchronized DE .
We ensure the other DE  with email address is already connected to Journey Entry De in Contact Builder.  Why is the other DE not appearing in Contact Builder ?

A: Only Data Extensions that are connected as Populations will be listed in this drop down. You should only have 3 populations in the account. Populations
I would suggest putting the email address in the entry source DE and then use the option above this to select your email address as needed


text:
Q: Did the Meta Community Bulletin Board die? Came across this post somehow:
Nailing it up on your Community Bulletin Board
Which, in turn, took me to a host of other questions with screen prints of said bulletin board.  Yet, I can't remember seeing this bulletin board in the 4-something months I've been here.
Did it die, or does it just not get used much?  If it's dead, should there be some mention of its death so anyone who comes across those posts knows it's a "Legacy" thing?

A: It does exist, for example on other sites like SciFi:

So it isn't fully dead, it just seems like noone has posted anything to it on SO recently

A: From the post you linked to:

There are two missing pieces though:

*

*It's not particularly functional for Stack Overflow, because there's no way to create per-tag events. Apart from things like Meetups and major cleanup efforts, there aren't a lot of events that are worth intruding on every single reader's view.

*The best part - scheduled events - is moderator-only.

There were two stages planned for the implementation of that feature: the first stage (which would suffice for nearly all sites on the network) was a fairly light-weight event-and-meta view driven mostly by meta-votes and direct moderator intervention. The second stage - making it functional for Stack Overflow - required deeper integration with the site itself and the (generally tag/topic-focused) communities on it. Sadly, this latter part was never finished and eventually ended up blocked by a larger project which could/should/may integrate with it in some form.
For the time being, you'll see the board pop up on SO (and MSO) occasionally when there's a blog post or (rarely) when a moderator or team member adds an "event" to the schedule.

A: Depends on where you're expecting to see it. If you're talking about Stack Overflow, I don't believe there is anything to currently be displayed on the Community Bulletin. Generally only recent blog posts and recent featured posts show up on it for Stack Overflow (since not all Meta Stack Overflow questions would necessarily be specific to the Stack Overflow community). I'm not sure what the time threshold is for how long they stay there.
It's definitely not dead, though. For example, it shows up on Arqade and Super User.


text:
Q: Firestore onUpdate function not triggering The problem
I'm using Firebase cloud functions with the emulator, and for some reason, the onUpdate trigger is not triggering, yet the onCreate function does trigger.
All code is TypeScript, and it's transpiled to JS to work on cloud functions.
// functions/src/music.ts

// this function runs
export const onMusicCreated = functions.firestore
    .document('music/{musicId}')
    .onCreate(async (snapshot) => {
        console.log('on create is running')
    })

// this function doesn't run
export const onMusicUpdated = functions.firestore
    .document('music/{musicId}')
    .onUpdate(async (change) => {
        console.log('on update is running')
    })

Both functions are async because in the final code,
On the front-end, when I run the add function on the front-end, the onCreate function fires.
const { id } = await firebase.firestore().collection('music').add({ title: 'hello world' })

The console log runs as expected and the emulator outputs this into the console:
i  functions: Beginning execution of "onMusicCreated"
i  functions: Finished "onMusicCreated" in ~1s

Yet when I update that same document, the onUpdate function doesn't run.
// "id" is the same id as above
await firebase.firestore().doc(`music/${id}`).update({ title: 'new title' })

Nothing happens. I can confirm that the document is actually updated when I look in the firestore emulator. Am I missing something obvious? The front-end code is simplified as compared to my actual use, but the functions code isn't simplified at all. And I can confirm that the firestore document is created and updated as I'd expect.
No error messages in the console or the logs.
Debug steps

*

*I've checked to make sure the functions code was correctly transpiled to JS. I bothed looked at the code output, as well as updated the onCreate code multiple times to ensure that function updated

*I hollowed out all my code inside the functions (as shown above), so I can confirm that the function itself isn't running

*The onUpdate function technically accepts two parameters. Same results with both parameters.

*I have not tried the functions in production, only with the emulator.

Related posts
Why doesn't firestore onWrite trigger get invoked on firebase cloud functions emulator?
I'm not using any forbidden characters in the document selector, or at least I'm not getting that error message.
Firebase Cloud Functions for Firestore are not triggering
Using functions 3.11.0, and the functions are async, hence they should implicitly return Promise. Results are the same when explicetely returning a value (e.g., return 0)
https://firebase.google.com/docs/functions/firestore-events#trigger_a_function_when_a_document_is_updated
That's the official docs. As far as I can tell, I'm doing what the docs say. I could just be missing something blindingly obvious, though.
Other details

*

*macOS Big Sur 11.1 (20C69)

*Firebase CLI 9.1.0

The emulator should be up-to-date
Any ideas? Thanks!

A: Turns out I just forgot to import onMusicUpdated in the index.ts functions file. Hence the emulator never knew it existed!
Changed
// functions/src/index.ts

export { onMusicCreated } from './music'

to
// functions/src/index.ts

export { onMusicCreated, onMusicUpdated } from './music'


text:
Q: Getting 127.0.1.1 instead of 192.168.1.* ip ubuntu python I am new to python. I want to get the ipaddress of the system. I am connected in LAN. When i use the below code to get the ip, it shows 127.0.1.1 instead of 192.168.1.32. Why it is not showing the LAN ip. Then how can i get my LAN ip. Every tutorials shows this way only. I also checked via connecting with mobile  hotspot. Eventhough, it shows the same.
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)

Output:
Your Computer Name is:smackcoders
Your Computer IP Address is:127.0.1.1

Required Output:
Your Computer Name is:smackcoders
Your Computer IP Address is:192.168.1.32

A: How can I get the IP address of eth0 in Python?
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print s.getsockname()[0]

A: I got this same problem with my raspi.
host_name = socket.gethostname()`
host_addr = socket.gethostbyname(host_name)

and now if i print host_addr, it will print 127.0.1.1.
So i foundthis: https://www.raspberrypi.org/forums/viewtopic.php?t=188615#p1187999
host_addr = socket.gethostbyname(host_name + ".local")

and it worked.

A: This also worked for me:
gethostbyname(gethostname()+'.')

A: As per the above '/etc/hosts' file content, you have an IP address mapping with '127.0.1.1' to your hostname. This is causing the name resolution to get 127.0.1.1. You can try removing/commenting this line and rerun.

A: i get the same problem what your are facing. but I get the solution with help of my own idea, And don't worry it is simple to use.
if you familiar to linux you should heard the ifconfig command which return the informations about the network interfaces, and also you should understand about grep command which filter the lines which consist specified words
now just open the terminal and type
ifconfig | grep 255.255.255.0

and hit enter now you will get wlan inet address line alone like below
inet 192.168.43.248  netmask 255.255.255.0  broadcast 192.168.43.255

in your terminal
in your python script just insert
#!/usr/bin/env python
import subprocess
cmd = "ifconfig | grep 255.255.255.0"
inet = subprocess.check_output(cmd, shell = True)
inet = wlan.decode("utf-8")
inet = wlan.split(" ")
inet_addr = inet[inet.index("inet")+1]
print(inet_addr)

this script return your local ip address, this script works for me and I hope this will work for your linux machine
all the best

A: This solution works for me on Windows. If you're using Linux you could try this line of code instead:
IPAddr = socket.gethostbyname(socket.getfqdn())


text:
Q: React State doesn't change when I click on a div which exists outside the root node I have this code in react. While clicking on the target div, I want to change the state of the the App component. But it seems that the state never changes and i cant figure out why this is case. Am I doing something wrong here?
function App() {

const [var1, serVar1] = useState(true);
const ref1 = useRef();

  useEffect(() => {
    ref1.current = document.getElementById("target");
    ref1.current.addEventListener("click", () => {
      serVar1(!var1);
    });
  }, []);

  console.log(var1);

  return (

  );
}
  ReactDOM.render(<App />, document.getElementById('root'));

ssssssss

A: You can use React Portals. You have not explained your whole problem, why do you need this? Do you exactly want click listener on target div or it can some child element.
Here is a piece of code which can help you to think in that way and come up with right solution.

function App() {

  const [var1, serVar1] = useState(true);

  const doSomething = () => {
    serVar1(v => !v);
  }

  console.log(var1);

  return (

{var1 ? 'True' : 'False'}

     {ReactDOM.createPortal(
      <button onClick={doSomething} >Click Me / Toggle var1</button>,
      document.getElementByID('target'),
    )}

  );
}

A: Change the useEffect in this way:
useEffect(() => {

    function handleClick() {
      serVar1(!var1);
    }
    ref1.current = document.getElementById("target");
    ref1.current.addEventListener("click", handleClick);
    return () => {
      ref1.current.removeEventListener("click", handleClick)
    }
  });


text:
Q: Why does nameof() give an ambiguous invocation warning in a Linq expression, but not when I use the same value as a string? I'm getting a compiler warning that started happening when I upgraded to FluentAssertions 4.2.2. In the following code, if I call EndsWith(nameof(x)), I get an ambiguous invocation warning. If instead I define var foo = nameof(x) and call EndsWith(foo), it compiles cleanly. The code runs ok in both scenarios.
My questions are why is this happening, and is there a workaround other than storing the nameof() result in a variable?
[Test]
public void TestLastNamesAreSame()
{
    var original = new MyDTO("fred", "jones");
    var expected = new MyDTO("barney", "jones");

    // this gives an Ambiguous invocation warning
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameof(MyDTO.FirstName))));

    // but when I use a variable holding the same value, it works without warning
    const string nameOfFirstNameField = nameof(MyDTO.FirstName);
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameOfFirstNameField)));
}

public class MyDTO
{
    public string FirstName { get; }
    public string LastName { get; }

    public MyDTO(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

A: Are you sure that this is a compiler error/warning and not a ReSharper warning?
If it is the former, what is the CSNNNN error/warning number?
Have look at (Resharper: Ambiguous Invocation)


text:
Q: Alignment, total size and SSE I'm trying to define a custom point type for the PCL library. In that tutorial, they're talking about memory alignment, so I started off by trying to understand how it works.
In this page, they present a rather simple way of calculating the total alignment of a structure. For example, this structure
// Alignment requirements
// (typical 32 bit machine)

// char         1 byte
// short int    2 bytes
// int          4 bytes
// double       8 bytes

// structure C
typedef struct structc_tag
{
  char        c;
  double      d;
  int         s;
} structc_t;

will have a size of 24:
1 byte for the char + 7 bytes of padding + 8 bytes for the double + 4 bytes for the int + 4 bytes of padding

and for g++ 4.8.1, sizeof returns 24. So far, so good.
Now, in PCL they're defining the point types with this scheme (here's the most simple point, that holds the position in each axis) for SSE alignment.
union
{
  float data[4];
  struct
  {
    float x;
    float y;
    float z;
  };
};

sizeof returns 16. With the union it is made sure that the point type is SSE aligned (I read here that is 16 byte alignment) and with the struct the axis values are accessible.
Quoting from the PCL docs:

The user can either access points[i].data[0] or points[i].x for
  accessing say, the x coordinate.

Is my reasoning valid until here?

In my case, I want to change the floats for doubles in order to have more precision in the X and Y axis.
So, is it enough to declare the point type as:
union {
  float data[4];
  struct {
    double x;
    double y;
    float z;
  };
};

?
sizeof returns 24, which is not a multiple of 16 (so I understand it's not SSE aligned) but it is "double aligned".
My question is, how can I define my point type to be able to store the X and Y coordinates as double and still be SSE aligned?
PS: Also, if any of you know of a good resource for this, please tell me. I want to understand better this topic.
PS 2: I forgot to tell, the platform I'm trying all of this is a 64 bit one.
PS 3: If possible, I'm interested in pre-C++11 solutions. A compiler as old as g++ 4.4 (and its MinGW counterpart) must be able to build the new point type.

A: The size of the object and it's aligment are not the same thing.  If the size of the struct is 16 bytes or some multiple it does not mean it will necessarily be 16 byte aligned.
In your case since your code is compiled in 64-bit mode you just need to pad the struct to 32 bytes.  In 64-bit mode the stack is 16 byte aligned in Windows and Linux/Unix.
In 32-bit mode it does not have to be 16 byte aligned. You can test this.  If you run the code below in MSVC in 32-bit mode you will likely see that the address for each element of the array is not 16 byte aligned (you might have to run it a few times).  So even though the size of the struct is a multiple of 16 bytes it is not necessarily 16 byte aligned.
#include <stdio.h>

int main() {
    union a {
        float data[4];
        struct {
            double x;
            double y;
            float z;
            float pad[3];
    };
    a b[10];
    for(int i=0; i<10; i++) {
        printf("%d\n", ((int)&b[i])%16);
    }
}

If you want your code to work in 32-bit mode as well then you should align the memory.  If you run the code below in 32-bit mode on Windows or Linux you will see that it's always 16 byte aligned as well.
#include <stdio.h>
#ifdef _MSC_VER // If Microsoft compiler
#define Alignd(X) __declspec(align(16)) X
#else // Gnu compiler, etc.
#define Alignd(X) X __attribute__((aligned(16)))
#endif

int main() {
    union a {
        float data[4];
        struct {
            double x;
            double y;
            float z;
            float pad[3];
    };
    a Alignd(b[10]);
    for(int i=0; i<10; i++) {
        printf("%d\n", ((int)&b[i])%16);
    }
}

A: In order to have a struct which has 2 doubles and a float, and be SSE aligned (16 bytes), use :
#pragma pack(1)
struct T
{
 double x,y;   // 16 bytes
 float z;      // 4 bytes
 char gap[12]; // 12 bytes
};

sizeof(T) will be 32, so if the first point is 16-bytes aligned, the whole vector will be aligned.
In order to make the first point aligned you should use __attribute((aligned(16)) for stack variables, or aligned_alloc for heap memory.
But, most of the algorithms of PCL are written and hard-coded for floats and not doubles, so they won't work...
Refer : pcl-users link


text:
Q: Multiple Upload to MySql Database, foreach not submitting photos I had a script to upload a single file to a MySQL database that I tried to alter to upload multiple files, but I can't seem to get the foreach statement to check and insert each file.
HTML Form
<form id="add_photo_form" class="form-inline" action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

    <input type="hidden" name="album_id" value="<?php echo $_GET['album_id']; ?>" />

        Select Photo *
        <input class="form-control" type="file" name="photo_file[]" multiple="multiple" />

        <input class="btn btn-primary" type="submit" name="add_photo_submit" value="Submit" />

</form>

PHP Script
if (isset($_POST['add_photo_submit']))
{
    foreach($_FILES['photo_file'] as $new_photo)
    {
        $file_ext      = pathinfo('./albums/img/photos/'.basename($new_photo['name']),PATHINFO_EXTENSION);
        $file_name     = 'image_'.date('mdyHis').uniqid().'.'.$file_ext;
        $file_path     = './albums/img/photos/'.$file_name;
        $album_id      = $_POST['album_id'];
        $photo_file    = $file_name;

        if (!empty($new_photo['name']))
        {
            $uploadOk = 1;
            $check = getimagesize($new_photo['tmp_name']);
            if ($check == false)
            {
                $uploadError = 'This is not a valid image.';
                $uploadOk = 0;
            }
            if (file_exists($file_path))
            {
                $uploadError = 'This file already exists.';
                $uploadOk = 0;
            }
            if ($new_photo['size'] > 1000000000000000000) /* bytes */
            {
                $uploadError = 'The file is too large.';
                $uploadOk = 0;
            }
            if ($file_ext != 'jpg' && $file_ext != 'jpeg' && $file_ext != 'png' && $file_ext != 'gif')
            {
                $uploadError = 'Only JPG, JPEG, PNG, or GIF images are allowed.';
                $uploadOk = 0;
            }
            if ($insert = $db -> prepare("INSERT INTO photos (album_id, photo_file) VALUES (?, ?)"))
            {
                $insert -> bind_param('ss', $album_id, $photo_file);
                if ($uploadOk == 1)
                {
                    move_uploaded_file($new_photo['tmp_name'], $file_path);
                    if ($insert -> execute() == true)
                    {
                        echo '
 A new album was created.
';
                    }
                    else
                    {
                        echo '
 '.$insert -> error.'
';
                    }
                }
                else
                {
                    echo '
 '.$uploadError.'.
';
                }
                $insert -> close();
            }
        }

    }
}

If I remove the [] from photo_file[] in my HTML form and remove the foreach statement in the PHP script, I am able to upload a single image with no problems.
When I try to upload, I get no database error, no statement error, no file error, and no error log.
How can I fix my foreach statement to check and upload each image?

EDIT
  As per the accepted answer below, my new php script looks like the following. Hopefully this can help someone down the road.

if (isset($_POST['add_photo_submit']))
{
    $total = count($_FILES['photo_file']['name']);
    for($i=0; $i<$total; $i++)
    {
        $file_ext      = pathinfo('./albums/img/photos/'.basename($_FILES['photo_file']['name'][$i]),PATHINFO_EXTENSION);
        $file_name     = 'image_'.date('mdyHis').uniqid().'.'.$file_ext;
        $file_path     = './albums/img/photos/'.$file_name;
        $album_id      = $_POST['album_id'];
        $photo_file    = $file_name;

        if (!empty($_FILES['photo_file']['name'][$i]))
        {
            $uploadOk = 1;
            $check = getimagesize($_FILES['photo_file']['tmp_name'][$i]);
            if ($check == false)
            {
                $uploadError = 'This is not a valid image.';
                $uploadOk = 0;
            }
            if (file_exists($file_path))
            {
                $uploadError = 'This file already exists.';
                $uploadOk = 0;
            }
            if ($_FILES['photo_file']['size'][$i] > 1000000000000000000) /* bytes */
            {
                $uploadError = 'The file is too large.';
                $uploadOk = 0;
            }
            if ($file_ext != 'jpg' && $file_ext != 'jpeg' && $file_ext != 'png' && $file_ext != 'gif')
            {
                $uploadError = 'Only JPG, JPEG, PNG, or GIF images are allowed.';
                $uploadOk = 0;
            }
            if ($insert = $db -> prepare("INSERT INTO photos (album_id, photo_file) VALUES (?, ?)"))
            {
                $insert -> bind_param('ss', $album_id, $photo_file);
                if ($uploadOk == 1)
                {
                    move_uploaded_file($new_photo['tmp_name'], $file_path);
                    if ($insert -> execute() == true)
                    {
                        echo '
 A new album was created.
';
                    }
                    else
                    {
                        echo '
 '.$insert -> error.'
';
                    }
                }
                else
                {
                    echo '
 '.$uploadError.'.
';
                }
                $insert -> close();
            }
        }
    }
}

A: $total = count($_FILES['photo_file']['name']);

// Loop through each file
for($i=0; $i<$total; $i++) {
  //Get the temp file path
  $tmpFilePath = $_FILES['photo_file']['tmp_name'][$i];

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['photo_file']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

i think this may help you.
Origin: Multiple file upload in php


text:
Q: Fullcalendar events spanning for more than one day I have events on my fullCalendar that span for more than one day. I have the start date and end date and time. However,in my list view of the calendar, the time for the events that span for more than one day is not showing correct. My events start and end time is 8:00 a.m. to 5:00 p.m. but these events show 8:00 a.m. to 12:00 a.,m. for first day and 12:00 a.m. to 5:00 p.m. for next day.
How can I show these timings for the same event 8:00a.m. to 5:00p.m. even though the event spans for more than one day

A: The behaviour of the calendar is correct. Your event is continuous for all that time. It starts at the start time and ends at the end time, there is no break or gap.
If you have, say, a 3-day event, and want to show it as starting at 8am and finishing at 5pm on day 1, and then the same for day 2 and day 3, then you need to provide the data to fullCalendar as 3 separate events (each with a different date, but the same start/end times).
For example
[
  {
    "Pressure Equipment Safety Legislation Seminar",
    "start": "2019-03-26 08:00",
    "end": "2019-03-26 17:00"
  },
  {
    "Pressure Equipment Safety Legislation Seminar",
    "start": "2019-03-27 08:00",
    "end": "2019-03-27 17:00"
  }
  {
    "Pressure Equipment Safety Legislation Seminar",
    "start": "2019-03-28 08:00",
    "end": "2019-03-28 17:00"
  }
]

Alternatively, depending on which version of fullCalendar you are using, you may be able to take advantage of its recurring event features (new in version 4), or in earlier versions you can implement a custom recurring event solution such as this one.


text:
Q: Can we get a "welcome, check out our FAQ" notification for new users? I've just created my first (?) sock puppet account on Programmers. This is the first notification I was greeted with:

I think the first ever notification should point the new user to the FAQ, or, if setting your name and email is so important, perhaps there could be a second notification. Something along the lines of:

Hey! Check out our FAQ to see what questions we welcome!

The Programmers FAQ especially is awesome, kinda reads like a short novel, and I think we should help new users discover it as soon as possible. Thoughts?

An alternative would be to use the nice transparent, white bar that we get when we are automatically logged in, as Bryan Dunsmore suggests.


text:
Q: Python's support for hexadecimal escapes in the replacement text Could not found a corresponding PEP or a bug for one problem in Python's re module.
Does anyone know if the following is planned to be fixed?
From regular-expressions.info:

Python does not support hexadecimal escapes in the replacement text
  syntax, even though it supports \xFF and \uFFFF in string constants.

But it actually supports standard escapes like \n, \r, etc.
So, for example one cannot replace '<' character with '>' character using hexadecimal escapes:
>>> import re
>>> re.sub(r'\x3c', r'\x3e', '\x3c')
'\\x3e'

Instead of '\\x3e' it should be '>'.
Using escaped \n works fine:
>>> re.sub(r'a', r'\n', 'a')
'\n'

Thanks in advance!
UPD: Not using the raw string is not an option. For example if pattern and replacement strings are stored in a config file, so if I write \x3e in it, it will become '\\x3e' when read, instead of '>'.

A: The only workaround I know if is to not use a raw string for the replacement text and instead allow normal string evaluation to make \x3e into >. This works because, as you noted, python strings do support such sequences.
>>> import re
>>> re.sub(r'\x3c', '\x3e', '\x3c')
'>'

This means that in more complex replacement text you need more escapes, which could make it less readable, but at least it works.
I don't know if there is any plan to improve on this. I took a look at the existing documentation for the python 3.4 re module (under dev) and found no mention of including this kind of support.
However, if you have a need for more complex logic on the replacement, you can pass a function instead of replacement text for the repl argument of re.sub.


text:
Q: Match regex pattern multiple times I'm trying to write a regex that will match a given pattern between 2 and unlimited times.  Effectively I'm just trying to combine multiple line breaks in to one, if any exist at all.
Sample input:

ABC

Expected output:

ABC

If the regex was run on the above output then I would expect to see the exact same output.
There could be any amount of whitespace between the
 tags.
What I've tried:
$html = preg_replace('/(?:
\s?){2,}/s', null, $html);

A: Just look for a
 followed by optional space characters 2 or more times and replace with
:
$html = preg_replace('/(
\s*){2,}/', '
', $html);

You might replace with "
\n" if you want.