text:
Q: I am running into an error while running my code, which accepts temperatures from user and prints in reverse order, why is that so? I was writing this code, given as homework, to satisfy the following:
(Usage of the function realloc isn't permitted)

*

*initally allocate an array to hold up to 5 temperatures.

*prompt the user to enter temperatures and type the value -100.0 when they are finished.

*if the user fills up the array your program should
dynamically allocate a new array which is double the size.

*copy the old values across to the new array.
deallocate the old array.

*continue reading into the new array.
After you finish reading your array your program should, as before, output the temperatures read in reverse (most recent to oldest) with 1 decimal point of precision and a new line at the end of the input
Here is my approach:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int size = 5;
float *temperature_first = malloc(sizeof(float)*size);
float *temperature_second;
float inputArray;
int switch_array = 0;
int count = 0;

printf("'Please enter temperature; type '-100' to end: ");
while(inputArray !=-100){

  while((inputArray != -100)&&(count<=size)){
    if(switch_array==0){

      scanf("%f", &temperature_first[count]);
      inputArray = temperature_first[count];
    }

    else{
      scanf("%f", &temperature_second[count]);
      inputArray = temperature_second[count];
    }
    count++;
    }
    if((count>=size)){

      size  = size*2;

      if(switch_array==0){
      temperature_second = malloc(sizeof(float)*size);
      for(int elements = 0;elements<(size/2)+1;elements++){

        temperature_second[elements] = temperature_first[elements];
      }
        free(temperature_first);

        switch_array = 1;
      }
      else{
        temperature_first = malloc(sizeof(float)*size);
        for(int elements = 0;elements<(size/2)+1;elements++){

          temperature_first[elements] = temperature_second[elements];

        }

          free(temperature_second);

          switch_array = 0;
    }
  }
}
for(int i = count-2;i>-1;i--){
  if(i==0){
  if(switch_array==0)
  {
    printf("%0.1f", temperature_first[i]);
   }
   else{
     printf("%0.1f", temperature_second[i]);
   }
  }
  else{
    if(switch_array==0){
      printf("%0.1f ", temperature_first[i]);
    }
    else{
      printf("%0.1f ", temperature_second[i]);
    }
  }
}
printf("\n");

if(switch_array==0){
  free(temperature_first);
}
else{
  free(temperature_second);
}
return 0;
 }

while running a specific test:
Input: 16.5 18.8 20.5 21.3 16.2 15.0 17.0 19.7 21.2 56.3 12.5 44.5
Following line is used for compilation:
gcc -Wall -Werror=vla -std=c11 -o temperatures02 temperatures02.c

This is what I run into:
malloc(): corrupted top size
Aborted (core dumped).

I'm not too sure why.
Any help would be appreciated.
Thank you!

A: You simply do not allocate enough memory:
    if((count>size)||(count==size)){

      size  = size*2;

      if(switch_array==0){
      temperature_second = malloc(sizeof(float)*count);

You need size instead of count. Otherwise your entries count .. size-1 will end up in memory you do not own.
A much shorter version of your code could look like that:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int size = 5;
  float *temperatures = malloc(sizeof(float)*size); // TODO: Check for NULL
  float temperature;
  int count = 0;

  printf("Please enter temperature; type '-100' to end: ");
  scanf("%f", &temperature);
  // TODO: Check result for error!

  while (temperature != -100) {
    temperatures[count] = temperature;
    count++;

    if (count == size) {
      size *= 2;
#if DO_IT_LIKE_THE_TASK_DEMANDS_IT
      float *newarray = malloc(sizeof(float)*size);
      // TODO: Check for NULL!
      for (int i = 0; i < count-1; i++) {
        newarry[i] = temperatures[i];
      }
      free(temperatures);
#else
      float *newarray = realloc(temperatures, sizeof(float)*size);
      // TODO: Check for NULL!
#endif
      temperatures = newarray;
    }

    printf("Please enter temperature; type '-100' to end: ");
    scanf("%f", &temperature);
    // TODO: Check result for error!
  }

  // Print them backwards (not in the task but in your code
  // Last element was put into temperatures[count] before we did count++.
  // Therefore now we need to start at index count-1, not count-2

  for(int i = count-1;i>-1;i--) {
    if (i==0) {
      printf("%0.1f", temperatures[i]);
    }
    else {
      printf("%0.1f ", temperatures[i]);
    }
  }
  printf("\n");

  free(temperatures);
  return 0;
 }

Tested at https://www.onlinegdb.com/online_c_compiler shows:
Please enter temperature; type '-100' to end: 16.5
Please enter temperature; type '-100' to end: 18.8
Please enter temperature; type '-100' to end: 20.5
Please enter temperature; type '-100' to end: 21.3
Please enter temperature; type '-100' to end: 16.2
Please enter temperature; type '-100' to end: 15.0
Please enter temperature; type '-100' to end: 17.0
Please enter temperature; type '-100' to end: 19.7
Please enter temperature; type '-100' to end: 21.2
Please enter temperature; type '-100' to end: 56.3
Please enter temperature; type '-100' to end: 44.5
Please enter temperature; type '-100' to end: -100
44.5 56.3 21.2 19.7 17.0 15.0 16.2 21.3 20.5 18.8 16.5

...Program finished with exit code 0


text:
Q: Custom PC build suspended on wall: how to properly ground the PSU and the Motherboard? When building a custom case for a computer that will be mounted on the wall, hanging, suspended are there any special considerations for the PSU or grounding?
Assumption 1 – I assume the MB will need to make contact with the metal case and using brass standoffs are fine. Because the custom 'wall case' is mostly metal (20×20 extrusions), those standoffs can safely be mounted to the metal case, making metal-contact with the MB as one would in a normal case.
OR – In this situation should Nylon standoffs be used instead to insulate the MB from the frame? (Why do I think this: because of interference, RF, avoid making the computer into an antenna, etc.)
Assumption 2 – I assume the PSU will need to make grounded metal-to-metal contact with the case as well just like a normal build.
OR – In this situation should washers or nylon be used to insulate the PSU from the case since it's wall mounted? (Why do I think this: because of RF and to avoid static problems or making an electromagnet.)
Clear acrylic will be used for a MB bracket and a PSU bracket (to make it easier to secure those components to the 20×20 metal extrusion frame), which brings up the following considerations:

*

*If those custom acrylic mounting brackets will insulate the PSU from the metal case, then is additional grounding is needed to ground the PSU to the case?

*If those custom acrylic mounting brackets will insulate the Motherboard from the metal case, then is additional grounding is needed to ground the Motherboard to the case?

*Neither the MB nor the PSU needs to be grounded to the case, ergo: mounting them to acrylic frames with no metal contact or additional grounding is fine.

*Conclusion A: None of the above matter? I.e., ground or no ground, a high quality PSU and good MB will be fine mounted in a wall case because the wiring is grounded through the PSU->Plug->Outlet->Home wiring – therefore, no special considerations are needed. RF interference, static and electromagnetism will not be a problem for a suspended wall mounted computer system and each component can be insulated from the others with nylon standoffs, acrylic brackets, insulating washers; even the frame itself could be plastic or acrylic.

*Conclusion B: All of the above matter? I.e., following the path of the ground from the power outlet through the computer system => the PSU, the MB and the case should all be connected and grounded, a metal frame is a good idea, metal mounting plates are better than acrylic and nylon should be avoided.
Let us assume in all cases here that the unit is "floating in space" (connected only by the PSU power cord) and the wall itself may be glass, metal, wood, rubber or simply "air" if the unit is hung from wires. Let us also assume that audio speakers will be connected and that Wi-Fi, cellphones and radios may be in use near the unit.
In closing: Which of these conclusions is true (A or B), and which, if any, of my assumptions (1 & 2) is incorrect?
Because this was "closed" lets make the 4 questions "more clear" for the admins here...
I am asking "how to properly ground the PSU and the Motherboard on a WALL HANGING custom computer.
There are 4 simple questions:

*

*Do I need to ground the Motherboard to the case using metal screws?

*Do I need to ground the PSU using metal screws?

*Can I use Nylon on the Motherboard Risers?

*Can I use Nylon on the PSU bracket?

A: Electrically and from an RF standpoint, there is nothing special about a computer being on the floor, on a table, on a shelf, or on the wall. Higher up (regardless of how) means the radio waves have further line of site, but that's it. And there will be some difference if e.g.,  the table is metal, as that may reflect radio.
The big difference is that your case isn't fully metal. The metal enclosure blocks a lot of RFI, and standard components are designed to be in one. So your non-metal case might have your computer exceeding permitted radio emissions, regardless of whether it hangs from the ceiling or sits in the floor. Only someone with test equipment could tell you for sure.

A: Conclusion A is the answer. Basically all of the grounding is done through the cable from the main power supply cable between motherboard and PSU via the 24 pin connector. The PSU is then grounded through the AC power cord to the ground lug on your outlet.

A: The ground wire wire from the wall outlet connects to the ground pin on the computer's power cord.  This in turn connects to the PSU.  The black wires for the various power connectors in the PSU are connected to the ground.  For safety, the metal case of the PSU is also connected to ground.
You will notice that in typical computer builds, the structure is all metal and all those metal components are physically in contact with each other, either by directly touching and/or with metal screws.  This means all the bare metal components that someone can touch are grounded and should be safe to touch if there is a short.
Does this mean you have to have everything made of metal and touching? If everything is connected properly and nothing is shorted, then no, it does not have to be.  Technically speaking, all you need is the PSU to be connected to the motherboard by the connectors.
 However, connecting all the grounding points on the PSU, case, and motherboard electrically does make it safer.
Edit:
Yes, you can do a hanging computer.  So your conclusion A is correct.

*

*No

*No

*Yes

*Yes

redpajama_set_name: RedPajamaStackExchange


text:
Q: TinyXML seg fault Is there any inherent memory leakage problem associated with tinyXML? I don't know why I am getting this strange seg fault.
In the following function, whenever I try to increase the size of element name("Connecor" &"laneFro"), the following  if clause(in the loop) causes the program to crash.
void WriteXMLInput_Node_Connectors(Node* node,TiXmlElement * Node_)
{
    std::ostringstream out;
    TiXmlElement * Connectors = new TiXmlElement("Connectors"); Node_->LinkEndChild(Connectors);
    TiXmlElement * Connector;
    TiXmlElement * laneFrom;
    TiXmlElement * laneTo;

    for(std::map<const sim_mob::Lane*, sim_mob::Lane* >::const_iterator it = node->getConnectors().begin();it != (node->getConnectors().end()); it++)
    {
        Connector = new TiXmlElement("Connecor"); Connectors->LinkEndChild(Connector);
        laneFrom = new TiXmlElement("laneFro"); Connector->LinkEndChild(laneFrom);
//      laneTo = new TiXmlElement("laneTo"); Connector->LinkEndChild(laneTo);
        if(42792 == node->getID())
        {
            std::cout << "uninode " ;
            std::cout << uninode->getID();
            std::cout << " from: " << (*it).first << " ";
            std::cout << (*it).first->getLaneID_str();
            std::cout << "uninode " << uninode->getID() << " To: " << (*it).second->getLaneID_str();

    }
}

Thank you


text:
Q: Get " Class is not registered:" exception during Gremlin Query I'm using Gremlin to connect with Janusgraph. Right now, I'd like to program a gremlin query statement to get specific Vertex by label with ignoring case-sensitive. So, my query like this:
g.V(vertexId).inE(edgeLabel).outV().filter(it -> it.get().label().equalsIgnoreCase(label)) ;

However, the execution caused a exception:

java.lang.IllegalArgumentException: Class is not registered: com.demo.service.kg.KGService$$Lambda$506/1884099229
Note: To register this class use: kryo.register(com.demo.service.kg.KGService$$Lambda$506/1884099229.class);

My configuration is:
hosts: [localhost]
port: 8182
connectionPool: { maxContentLength: 7000000 }
serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV3d0,
          config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry],
serializeResultToString: true}}

Is there anyone knows what is going on?

A: Lambdas will not serialize that way. You have to submit them as strings
g.V(vertexId).inE(edgeLabel).outV().filter(
  Lambda.predicate("it -> it.get().label().equalsIgnoreCase(label)")) ;


text:
Q: Does the bracket [] operator only have a single use? I initially thought that it has a different use for pointers and for arrays. In the former case, it adds whatever is in brackets to the pointer and then dereferences the sum; in the latter case it would just yield the ith element of an array.
Then I realized that an array variable returns the pointer to the first element, so the operator does the same thing in each case: offset and dereference.
Does the bracket [] operator indeed only have a single use in C?

A: Whether it does "one thing" depends on what you think "one thing" means.
In C, the operator is defined like so
e1[e2]   means   *(e1+e2)

That's it.  One thing.  Or is it?  Suppose a is an array and i is an integer.  We can write:
a[3]
a[i]
3[a]
i[a]

and suppose p is a pointer and i is an integer.  We can write
p[3]
p[i]
3[p]
i[p]

Arrays or pointers.  Two things?  Not really.  You know that when we use the plus operator where one of the two operands is "an array" you are really doing pointer arithmetic.
The second part of your question - can it be used for things other than pointer arithmetic - is basically no in C, but yes in C++, because in C++ we can overload this operator.  However sometimes you will see [] in type expressions, but that is probably not what you are asking about because in that case, we aren't really using it as an operator (we're using it as a type operator, which is different).

A: [] is called array subscript operator, but syntactically it's used on a pointer. An array is converted to a pointer to the first element in this usage (and many others). So, yes, [] is the same for arrays and pointers.

C11  §6.5.2.1 Array subscripting
Constraints
One of the expressions shall have type ''pointer to complete object type'', the other
  expression shall have integer type, and the result has type ''type''.
Semantics
A postfix expression followed by an expression in square brackets [] is a subscripted
  designation of an element of an array object. The definition of the subscript operator []
  is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that
  apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).


text:
Q: How to skip rows based on regex with pandas.read_excel? I am trying to read in an excel sheet with pandas.read_excel. Its skiprows argument allows for skipping rows by supplying the row numbers. However, how can we skip rows based on a pattern match? I have different excel sheets where the number of rows I need to skip is variable so supplying the number of rows isn't going to work for my use case. Is there a way I can supply a pattern - for e.g. skip all rows before a row that contains a specific string (say 'Test')? If this can't be accomplished with pandas read_excel, is there an alternative workaround to read the excel into dataframe this way? Any suggestions would be much appreciated. Thanks.

A: My suggestion would be to read the entire excel sheet into a dataframe and afterwards drop the unwanted rows. As a simple example:
import pandas as pd

# Read out first sheet of excel workbook
df = pd.read_excel('workbook.xlsx')

# Find label of the first row where the value 'Test' is found (within column 0)
row_label = (df.iloc[:, 0] == 'Test').idxmax()

# Drop all rows above the row with 'Test'
df = df.loc[row_label:, :]


text:
Q: Ploting Stem plot in pandas I have the following code:
import pandas as pd
from pandas_datareader import data as web
import datetime

df = web.DataReader('tip', 'yahoo', start= '1,1,2017', end = datetime.datetime.today())
df1 = df.resample('W-Mon').mean()
df1["Adj Close"].pct_change().plot()

This produces this plot:

To plot in stem in pandas:
df1["Adj Close"].pct_change().stem()

Is producing this error:

AttributeError: 'Series' object has no attribute 'stem'

A: You could use matplotlib:
import matplotlib.pyplot as plt
plt.stem(df1["Adj Close"].pct_change().index,
        df1["Adj Close"].pct_change())
plt.show()

Then customise axis/title as you like.


text:
Q: Use substr until condition is met I have a vector from which I just need the first word. The words have different lengths. Words are separated by a symbol (. and _) How can I use the substr() function to get a new vector with just the first word?
I was thinking of something like this
x <- c("wooombel.ab","mugran.cd","friendly_ef.ab","hungry_kd.xy")
y <- substr(x,0, ???)

A: I think sub with some regular expressions would be the easiest solution:
sub(pattern = "[._].*", replacement = "", x = x)
# [1] "wooombel" "mugran"   "friendly" "hungry"

A: Try:
sapply(strsplit(x,'[._]'), function(x) x[1])
[1] "wooombel" "mugran"   "friendly" "hungry"

A: You could also use package stringr.  It has some really handy functions for string manipulation.
One that comes to mind for this problem is word.  It has a sep argument that allows the use of a regular expression.
> x <- c("wooombel.ab","mugran.cd","friendly_ef.ab","hungry_kd.xy")
> library(stringr)
> word(x, sep = "[._]")
# [1] "wooombel" "mugran"   "friendly" "hungry"

Another option that allows you to continue to use substr is str_locate.  So if we just subtract 1 from its result, we can get the desired first words.
> substr(x, 1, str_locate(x, "[._]")-1)
# [1] "wooombel" "mugran"   "friendly" "hungry"

A: An extraction approach with stringi:
library(stringi)
stri_extract_first_regex(x, "[a-z]+(?=[._])")

## [1] "wooombel" "mugran"   "friendly" "hungry"

Though "[^a-z]+(?=[._])" may be more explicit.
Regex explanation:
[^a-z]+                  any character except: 'a' to 'z' (1 or
                         more times)
(?=                      look ahead to see if there is:
  [._]                     any character of: '.', '_'
)                        end of look-ahead


text:
Q: Open Web Analytics protect with htaccess I am using Piwik and now new Open Web Analytics (also a Tracking Web analytics software) and now I would like to protect the open web analytics folder  with a .htaccess. It works with Piwik and doesn't work with Open Web Analytics
The code from the .htaccess is the following:
# Sample .htaccess file for your web document root

# Restrict outside access
AuthUserFile /../www/analytics.domain.com/httpdocs/.htpasswd
AuthGroupFile /dev/null
AuthName "Piwik"
AuthType Basic

<Files "*">
Require valid-user
</Files>

<Files ~ "^piwik\.(js|php)|robots\.txt$">
Allow from all
Satisfy any
</Files>

<Files ~ "^owa\.(js|php)|robots\.txt$">
Allow from all
Satisfy any
</Files>

# Disable session auto-start; incompatible with Zend_Session.
php_flag session.auto_start off

# Disable directory viewing.
Options -All

If I want to get access to the Piwik folder, I have to enter the .htaccess username and password but if I open the Website that I am tracking I don't need to enter the password. That's how it should also work for OWA. If I open the OWA folder it also aks for name and password but after adding the tracking code to the website, it asks for the name and password everytime I open the Website. So why does it work with piwik and not for OWA?


text:
Q: UNIFIED StageStyle and Transparent Scene produce black background instead of transparent JavaFX 8 has StageStyle.Unified, enabling to create OS X  style, unified toolbars. I have tested the following code works correctly in JDK 8u5.(the scene background is transparent and the button appears against the stage background.)
However in JDK 8u25 and JDK 8u31 there is a weird behavior. the scene background becomes black.
changing the scene color to anything other than transparent works fine, it displays that color.
It is looking like a bug to me unless I am missing something,
Any ideas?
public class UnifiedTest extends Application {

@Override
public void start(Stage primaryStage) {

    StackPane testPane = new StackPane();
    testPane.setStyle("-fx-background-color:transparent;");

    Label someText = new Label("TEXT AGAINST TRANSPARENT SCENE");
    testPane.getChildren().add(someText);

    Scene myScene = new Scene(testPane,500,500);
    myScene.setFill(Color.TRANSPARENT);

    primaryStage.setScene(myScene);
    primaryStage.initStyle(StageStyle.UNIFIED);
    primaryStage.setTitle("Application");
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}
Some more information:
By stage background I meant the background of the window that is provided by the OS.
I am trying to create a unified toolbar. According to JavaFX 8 API the way to do it is to use StageStyle.UNIFIED. this will give a window provided by the OSX.
It looks like this when there is no scene added:
http://imgur.com/iHEiVf0,fMbFr4e,bFSL8bA
However when I setFill(Color.TRANSPARENT) the scene background becomes black:
http://imgur.com/iHEiVf0,fMbFr4e,bFSL8bA#2
The desired result is to see the text against the background of the first link. It worked with JDK 8u5, but now I am using 8u31 and instead of that grey I get black. What is weird is that if I setFill(Color.RED) the background becomes red as expected
From the JavaFX 8 api:
public static final StageStyle UNIFIED
Defines a Stage style with platform decorations and eliminates the border between client area and decorations. The client area background is unified with the decorations. This is a conditional feature, to check if it is supported see Platform.isSupported(javafx.application.ConditionalFeature). If the feature is not supported by the platform, this style downgrades to StageStyle.DECORATED
` NOTE: To see the effect the Scene covering the Stage should have Color.TRANSPARENT

A: Looks like this is a bug, which is fixed for Java 8u60:

*

*JDK-8095040 StageStyle.UNIFIED not working on OSX 10.9.5
Kevin Rushforth comments on the bug tracker:

It looks like the regression was introduced some time in 8u20.


text:
Q: Magento 2.3 : Create plugin of __call method I need to create plugin for this below file :

vendor/elasticsearch/elasticsearch/src/Elasticsearch/Client.php

There are __call function in this file :
public function __call($name, $arguments) {
        if (isset($this->registeredNamespaces[$name])) {
            return $this->registeredNamespaces[$name];
        }
        throw new BadMethodCallException("Namespace [$name] not found");
    }

I need to create plugin of this function.

What I tried :

In frontend/di.xml I added this below line :
<type name="Elasticsearch\Client">
      <plugin name="Vendor_Module::elasticsearcherrorsolver"
                type="Vendor\Module\Plugins\Elasticsearch\Client"/>
</type>

Vendor\Module\Plugins\Elasticsearch\Client.php

<?php

namespace Vendor\Module\Plugins\Elasticsearch;

class Client {

    public function around__call(\Elasticsearch\Client $subject, callable $proceed, $name, $arguments) {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Rohan.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info('Your text message');
        $result = $proceed($name, $arguments);
        // if (!isset($this->registeredNamespaces[$name])) {
        //  return true;
        // }
        return $result;
    }
}

But, It's not working. What should I need to change to call this plugin?
Any help would be appreciated !!

A: Your plugin is correct but it is not picked up by the magento interception system because the Elasticsearch Client class is not instantiated via ObjectManager. it is instantiated using the good old new Client(...) approach.
See it in Elasticsearch\ClientBuilder::instantiate().
Plugins work only for classes that go through the object manager to get instantiated.
for the same reason you cannot pluginize the Phrase class, the one that translates texts when using __('some thext here').


text:
Q: capturing all form elements values in a single string I have used the following javascript function to capture the values entered for each element in a form.Once user clicks on submit button,the values entered by user for each control must be displayed.
The code works well for all controls except radiobuttons.
Can anyone suggest me how to do it?
function DisplayFormValues(){
            var str = '';
            var elem = document.getElementById('form1').elements;
            for(var i = 0; i < elem.length; i++)
            {

                str += "Name:" + elem[i].name + "\n";
                str += "Value:" + elem[i].value + "\n";
                str += "
";
            }
            document.getElementById('lblValues').innerHTML = str;
        }

A: Values of radio buttons and checkboxes are not easy to get because they share the same name in the DOM. You have to loop through each of these elements and check which among its children are checked.
So, you need to expand your loop. One way of doing this is:
function DisplayFormValues(){
    var theform = document.form1;
    var a = ['input', 'textarea', 'select'];
    var echo = '';
    for (var i = 0; i < a.length; i++) {
        var tag = a[i];
        var els = theform.getElementsByTagName(tag);
        for (var j = 0; j<els.length; j++) {
            el = els[j]; // the element
            if ((tag == 'input' && (el.type == 'text' || el.type == 'password')) || tag == 'select') {
                echo += '' + el.name + ': ' + el.value + '
';
            } else if ((tag == 'checkbox' || tag == 'radio') && el.checked) { // the element is checked!
                echo += '' + el.name + ': ' + el.value + '
';
            }
        }
    }
    document.getElementById('lblValues').innerHTML = echo;
}


text:
Q: Nullpointer exception in Listview when using custom class in android Hello i am trying to implement a listview which will display the contents of a class by TextView. However the adapter doesn't seem to take in the values of the objects as it throws a nullpointer exception.
this is my custom class
     public class SubjectClass {

String sName;
String sCode;
String teacher;
}

Given Belows is the code for my CUstomarrayadapter
        public CustomAdap(Activity context, ArrayList<SubjectClass> names) {
    super(context, R.layout.listtempl, names);
    this.context = context;
    this.names = names;
}

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.listtempl, null, true);
    TextView textView1 = (TextView) rowView.findViewById(R.id.label1);
    TextView textView2 = (TextView) rowView.findViewById(R.id.label2);
    TextView textView3 = (TextView) rowView.findViewById(R.id.label3);
    SubjectClass sClass= (SubjectClass)getItem(position);
    String s1 = sClass.sName;
    String s2 = sClass.sCode;
    String s3 = sClass.teacher;
    Toast.makeText(getContext(), sClass.sCode,Toast.LENGTH_SHORT).show();
    textView1.setText(s1);
    textView2.setText(s2);
    textView3.setText(s3);

    return rowView;
}

this is the xml file used by the adapter
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content" >
     <TextView android:text="@+id/label1" android:textColor="#F1235AFA"   android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:layout_alignParentTop="true" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView2" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_alignBaseline="@+id/textView1" android:layout_alignBottom="@+id/label2" android:layout_alignParentLeft="true"></TextView>
<TextView android:text="TextView" android:textColor="#2CD7E0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_below="@+id/label" android:layout_toRightOf="@+id/label3" android:layout_marginLeft="15dp"></TextView>

         </RelativeLayout>

This is my activity
    public class SampleActivity extends Activity
     {
    ListView listview;
   CustomAdap adapter;
   ArrayList<SubjectClass> values = new ArrayList<SubjectClass>();

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.list1);
    SubjectClass subjectClass = new SubjectClass();
    subjectClass.sCode="cs9410";
    subjectClass.sName="Principles of management";
    subjectClass.teacher="xyz";
    values.add(subjectClass);
    SubjectClass subjectClass1 = new SubjectClass();
    subjectClass1.sCode="cs9401";
    subjectClass1.sName="Ethics";
    subjectClass1.teacher="xxx";
    values.add(subjectClass1);

    listview =(ListView) findViewById(R.id.lv1);
    adapter = new CustomAdap(this, values);
    listview.setAdapter(adapter);
}

}//

A: In row layout file change android:text="@+id/label1" to android:id="@+id/label1".
For all 3 TextView:
 SubjectClass sClass = (SubjectClass) names.get(position);

A: I believe you need to change your code to
 SubjectClass sClass= names.get(position);


text:
Q: Visual Studio 2013 Connection to SQL Server 2014 Using Visual Studio, I cannot connect to a SQL Server. I think this is something specific to Visual Studio, and NOT the server itself. VS is on a laptop (workstation) and the server is on another subnet. Versions are listed in the title, and I have already considered the solution below:
Visual Studio 2013 incompatibility with MS SQL Server 2014

*

*My connection string works in PowerShell without issue.

*My connection works in Visual Studio when connecting with the Server Explorer.

*Connection does not work in the C# code, I've gone so far as stripping it down to a basic console project, to become as basic as possible.

*I have tried all iterations of the connection string that I could possibly find in forums. (I've been to over 30 forums by now, easily)

*I have tried both SQL Server authentication and Windows authentication. Both forms work in PowerShell and Visual Studio Server Explorer.

Please don't mark this as irrelevant, as this is related to C# and NOT SQL.
The server is set up correctly for remote access and connection types.
using System;
using System.Data.SqlClient;

namespace ConsoleApplication2 {
    class Program {
        static void Main(string[] args) {
            System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder.DataSource         = "SERVERNAME";
            builder.InitialCatalog     = "DATABASE";
            builder.IntegratedSecurity = true;
            Console.WriteLine(builder.ConnectionString);
            SqlConnection conn = new SqlConnection(builder.ConnectionString);
            conn.Open();
            Console.WriteLine(conn.State);
        }
    }
}

In PowerShell, same machine, this code works.
$dataSource                  = "SERVERNAME"
$database                    = "DATABASE"
$connectionString            = "Server = $dataSource; Database = $database; Integrated Security = $TRUE;"
$connection                  = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
Write-Host $connection.State

A: You should always use a ConnectionStringBuilder to create your connection strings. This ensures a valid syntax and avoids malicious injections:
System.Data.SqlClient.SqlConnectionStringBuilder builder =
    new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.DataSource = "SERVERNAME";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "DATABASE";
builder.UserID = "userid";
builder.Password = "password";
Console.WriteLine(builder.ConnectionString);

For your Example, this produces the following output:
Data Source=SERVERNAME;Initial Catalog=DATABASE;Integrated Security=True;User ID=userid;Password=password
Please note that Integrated Security=True; indicates that you want to use the current windows account credentials for authentication; UserID and password are unnecessary in this case.
Source: https://msdn.microsoft.com/en-us/library/ms254947%28v=vs.110%29.aspx

A: Ok you coud try this, note that when you are writing the connection string it uses two "//", and I think it would not be a problem, and in this way you coud use the appconfig or just create the string in a class and declare the conection string...
First create a class:
    public static class Connetion_string
    {
      public static string conection = "Server=.\\Server_name;Initial Catalog=Data_base_name;Integrated Security=True";
    }

Then you could write something like this...
     public void Some_procedure()
     {
        SqlConnection con = new SqlConnection(Conection_string.conection);
        try
            {
                con.Open();
                //Here the code to execute soomething from data base....
                con.Close();
            }
            catch (Exception ex)
            {
                string ms;
                ms = ex.Message;
            }
            //This will ensure that al resources in server are available
            finally
            {
                con.Close();
            }
    }


text:
Q: How do you export pictures from 4D's tool box? I am using 4D version 11.6 (72398) in remote mode and am trying to export three pictures from a database. How do you extract pictures from the tool box? Screenshots and editing are not acceptable if avoidable.

A: The Picture Library area of the Tool Box does not have an export feature. However, the following commands will help you export the pictures:
PICTURE LIBRARY LIST gets an Array of Picture Names and an Array of Picture Reference ID's
GET PICTURE FROM LIBRARY uses the Picture Reference ID to get the picture from the Picture Library into a Picture variable.
WRITE PICTURE FILE writes the Picture variable to disk.
The following code could be used to export all of the pictures in the Picture Library to disk as PNG files.
C_TEXT($vsPicName;$vsFileName)
C_LONGINT($vlNbPictures;$vlPicture;$vlPicRef)
C_PICTURE($vgPicture)
ARRAY TEXT($asPicName;0)
PICTURE LIBRARY LIST($alPicRef;$asPicName)
$vlNbPictures:=Size of array($alPicRef)
If ($vlNbPictures>0)
    For ($vlPicture;1;$vlNbPictures)
        $vlPicRef:=$alPicRef{$vlPicture}
        $vsPicName:=$asPicName{$vlPicture}
        GET PICTURE FROM LIBRARY($alPicRef{$vlPicture};$vgPicture)
        If (OK=1)
            $vsFileName:=String($vlPicRef)+$vsPicName+".png"
            WRITE PICTURE FILE($vsFileName;$vgPicture;".png")
        End if
    End for
Else
    ALERT("The Picture Library is empty.")
End if

If you run the code above from Single-user or from the Server the files will be placed next to the structure file.
If you run the code above from from the Client the files will be placed into the 4D Client Cache folder which can be quickly opened using the following code:
SHOW ON DISK(Get 4D folder(4D Client Database Folder);*)


text:
Q: How to merge missing params fields from db to a params hash in rails Lets say the app recieves a param hash like this
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"sjfsj", "user"=>{"name"=>"Joe", "mobile"=>"12345678"}, "commit"=>"Save Changes"}

and this is the user model
{name: "value", mobile: "value", email: "value", many_others: "other_values" }

What am trying to do is create a new hash with all fields combined(params + missing_fields_from_db). So if the params has some missing keys it will be taken from model add to the new hash.
Like this:
{name: "Joe", mobile: "12345678", email: "value", many_others: "other_values" }

Is there a method available for that in ruby || rails?
Thank you

A: You are looking for a Hash#merge or Hash#reverse_merge. Difference:
a = { foo: 1, bar: 2, baf: 3 }
b = { foo: 2, bar: 1, baz: 1 }
a.merge(b)
#=> {:foo=>2, :bar=>1, :baf=>3, :baz=>1}
a.reverse_merge(b)
#=> {:foo=>1, :bar=>2, :baz=>1, :baf=>3}

Note, that Hash#merge is a pure Ruby method, Hash#reverse_merge comes from Rails.


text:
Q: Anonymous functions pre PHP 5.3.0 Is there an alternative to anonymous functions in versions of PHP previous to 5.3.0?

A: There is create_function but it generally isn't recommended. If you're using OOP, you'd be better off defining a one-off private member to use with a callback instead.

A: Yes, create_function()

A: There are two choices.
First is to create a function, inside a function. Unfortunately, it will pollute the global namespace.
The second choice is to use
create_function.


text:
Q: AttributeError, 'dict' object has no attribute 'iteritems'; Flask-SQLAlchemy error while committing to database I've been trying to get this to run for a while but seemingly to no avail. I have a webapp that requests the user input data, which is then committed to the db. When I hit add through the browser, the data is passed to the db however Werkzeug spits a number of errors back, which I've detailed below in the trace.
My views.py:
from flask import request, flash, render_template, url_for, redirect
from aalert import app, db
import flask_whooshalchemy
from flask_login import LoginManager, login_required, logout_user
from aalert.forms import *

from aalert.models import User, PubInfo, PrivInfo

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(userid):
    return User.query.filter(User.id==userid).first()

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, password = form.password.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('signup.html', form=form)

#pubinfo index
@app.route('/')
def index():
    entries = PubInfo.query.all()
    return render_template('disp_tables.html',
                           entries=entries)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first_or_404()
        if user.is_correct_password(form.password.data):
            login_user(user)
            return redirect(url_for('add'))
        else:
            flash('Incorrect username and password!')
    return render_template('login.html', form=form)

@app.route('/show_all')
@login_required
def show_all_data():
    entries = PubInfo.query.join(PrivInfo, PubInfo.id==PrivInfo.id)
    return render_template('disp_all.html',
                           entries)

@app.route('/add', methods=['POST', 'GET'])
#@login_required #login required to add functions, points to @login_manager.user_loader
def insert():
    form = AddEntry()
    if request.method == 'POST':
        if not request.form['firstname'] or not request.form['lastname'] or not request.form['age'] or not request.form['height'] or not request.form['last_loc'] or not request.form['missing_since'] or not request.form['contact_info'] or not request.form['home_address']:
            flash('Please ensure all fields are filled out!')
        else:
            pubentry = PubInfo(request.form['firstname'],
                               request.form['lastname'],
                               request.form['age'],
                               request.form['height'],
                               request.form['last_loc'],
                               request.form['missing_since'])

            priventry = PrivInfo(request.form['contact_info'],
                                 request.form['home_address'])
            db.session.add(pubentry)
            db.session.add(priventry)
            db.session.commit()
            flash('Record successfully added.')
            return redirect(url_for('index'))
    return render_template('add.html', form=form)

@app.route('/search', methods=['POST', 'GET'])
def search():
    form = SearchForm()
    if request.method == 'POST':
        result = pubinfo.query.whoosh_search(request.form['search_query'])
        return render_template('results.html', result=result)
    return render_template('search.html', form=form)

@app.route('/logout')
def logout():
    logout_user()

    return redirect(url_for('index'))

@app.route('/test')
def test():
    return redirect(url_for('login'))

The trace from the error:
Traceback (most recent call last):
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/scire/programs/python/aalert/aalert/views.py", line 75, in insert
    db.session.commit()
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 801, in commit
    self.transaction.commit()
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 399, in commit
    self.session.dispatch.after_commit(self.session)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
    fn(*args, **kw)
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py", line 231, in after_commit
    models_committed.send(session.app, changes=list(d.values()))
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/blinker/base.py", line 267, in send
    for receiver in self.receivers_for(sender)]
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp>
    for receiver in self.receivers_for(sender)]
  File "/home/scire/programs/python/aalert/env/lib/python3.5/site-packages/flask_whooshalchemy.py", line 239, in _after_flush
    for model, values in bytype.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

A: In Python3 dict.items() does the same thing that dict.iteritems() did in Python2. Just replace iteritems() with items()!

A: pip uninstall flask-whooshalchemy

then
pip install flask-whooshalchemy3

A: i recently encountered this same error while trying to use flask-sqlalchemy in python3 and was almost stuck. then i remember that https://blog.miguelgrinberg.com/post/about-me had done something like this before and decided to try it out
$ pip uninstall flask-whooshalchemy
$ pip install git+git://github.com/miguelgrinberg/flask-whooshalchemy.git
This worked for me
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-x-full-text-search
Enjoy. ..


text:
Q: What is the best way to identify updated items in an in memory list? I'm using Siaqodb for my client side database engine in a Sync Framework silverlight project. I've switched to siaqodb because microsofts client side solution loads the entire database into memory at once and, as such, has a hard time handling large data.
I've bound a list of SiaqodbOfflineEntity objects to a silverlight datagrid in order to create an editable datagrid. Unlike microsofts solution, you can't bind the database entries directly to the datagrid. You have to query the database and bind a list of in memory objects to the datagrid. This causes a problem in that the database isn't immediatly updated when the datagrid cell is changed. I'm trying to find the best way to handle updates to the database after a change in the cell. I can't just update each item to the database because the siaqodb engine will mark the item as dirty even if no change was made to the object. This will cause conflicts when trying to sync. holding a cached version of the original list and then comparing each property of each object to find which ones have changed seems like it would work, but seems to be a bit cumbersome. I've also tried looking at some of the datagrids events but RowEditEnded doesn't appear to fire when a cell is edited and CurrentCellChanged seems to fire whenever I switch rows (odd).
There's got to be a better solution to this. Anyone have any ideas?

A: So I've gotten this to work by changing my offline entity classes to implement iNotifyPropertyChange and I think this is a reasonable solution. I set the PropertyChanged event to a function that saves the object to the database. There is a VS package called notifypropertyweaver that will inject this code at compile time, reducing the amount of work needed to be done on auto-generated entity code.


text:
Q: Filtering by condition in Python dataset I'm struggling with a sorting operation of a stata file in Phyton3: I was asked to keep only the households without kids out of a dataset/table:
I used a filtering condition to filter these rows out of the table:
filtering_condition = df["kids"] > 0

df_nokids = df.loc[filtering_condition,"kids"]

This, however, gives me an unknown error:
KeyError                                  Traceback (most recent call last)
/opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/indexes/base.py in get_loc(self, key, method, tolerance)
1944             try:
-> 1945                 return self._engine.get_loc(key)
   1946             except KeyError:

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item     (pandas/hashtable.c:12322)()

KeyError: 'kids'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-321-e72cd8a67065> in <module>()
      1 #keep only the households without kids and use this dataset for the   rest of the assignment
----> 2 filtering_condition = df["kids"] > 0
      3 df_nokids = df.loc[filtering_condition,"kids"]

/opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in  __getitem__(self, key)
   1995             return self._getitem_multilevel(key)
   1996         else:
-> 1997             return self._getitem_column(key)
   1998
   1999     def _getitem_column(self, key):

/opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in  _getitem_column(self, key)
   2002         # get column
   2003         if self.columns.is_unique:
-> 2004             return self._get_item_cache(key)
   2005
   2006         # duplicate columns & possible reduce dimensionality

/opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/core/generic.py    in _get_item_cache(self, item)
   1348         res = cache.get(item)
   1349         if res is None:
-> 1350             values = self._data.get(item)
   1351             res = self._box_item_values(item, values)
   1352             cache[item] = res

/opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/core/internals.py     in get(self, item, fastpath)
   3288
   3289             if not isnull(item):
-> 3290                 loc = self.items.get_loc(item)
   3291             else:
   3292                 indexer = np.arange(len(self.items))   [isnull(self.items)]

 /opt/anaconda/anaconda3/lib/python3.5/site-packages/pandas/indexes/base.py    in get_loc(self, key, method, tolerance)
   1945                 return self._engine.get_loc(key)
   1946             except KeyError:
-> 1947                 return     self._engine.get_loc(self._maybe_cast_indexer(key))
   1948
   1949         indexer = self.get_indexer([key], method=method,    tolerance=tolerance)

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12322)()

KeyError: 'kids'

Any explanations of what I am doing wrong?
Thanks!
Datafile:

A: Do you mean something like this:
df_kids = df[df['kids']>0]

This selects the rows where the 'kids' column is not zero.


text:
Q: How to refer slot element from its slotted element in lit-element? I have a component named 'stack-item' which have a slot , its html will look like this

1

<slot></slot>

I have used this component like this
<stack-item>
   <another-component></another-component>
</stack-item>

From 'another-component' how do i get the element reference for class ='slot-style' for calculating the slot width and other properties ?
I wrote a workaround
let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;

but is there a clean way of achieving this?

A: I don't know if this can be considered dramatically simpler, but the scenario you give indicates that you already know the host component is stack-item and that component has a slot wrapper with the class name 'slot-style'. Given that you can obtain a reference like this (this works from within the component as well as the host document):
let slotElement = document.querySelector("stack-item").shadowRoot.querySelector(".slot-style");
//display width
console.log(slotElement.clientWidth);

A: this.shadowRoot.host is equivalent to this.
So you could try:
this.parentElement.shadowRoot.querySelector( 'div.slot-style' )


text:
Q: How to get sender wise report from sendgrid? I've subscribed sendgrid from azure, and I'm using 3 different sender to send emails, when I check the activity feed from sendgrid i'm getting limited information,

I need to get a sender wise report, I've tried in azure and there is no log. Is webhook can deliver these report?


text:
Q: how to find quickly all mongo documents having at least one element in an array I have the following query
db.runCommand(
    {"text":"item","search":"\"price\" ",
     "project":{"_id":1},
     "limit":1,
     "filter":{"quotes":{"$not":{"$size":0}}}}
);

But the filter part is taking a long time. For your understanding, "quotes" is a simple array of embeded documents. Is it possible to create an index to find all elements having at least one quote quickly?
EDIT:
To be more specific: The question is not only about "how to query" but "how to make a useful index".

A: I think the quicker way is this one:
db.collection.find({array: {$elemMatch: {$exists: true}}})

A: The negation operators like $not and $nin generally perform slower.  Can you check if the below query performs better and meets your needs?
db.collection.runCommand("text", {"search":"\"price\" ",
                                  "project":{"_id":1},
                                  "limit":1,
                                  "filter":{"quotes.0":{"$exists":true}}}
);


text:
Q: java.lang.StringIndexOutOfBounds error import java.util.Scanner;

public class s
{
    public static void main(String[] args)
    {
        Scanner input=new Scanner (System.in);
        String string=input.next();
        System.out.println(string.charAt(7));
    }
}

I get this error when i run the program and i don't understand why. All i want to do is print the 7th character.
PS E:\Users\adiad\Documents\Scuola\Informatica\Madeo\Pratica> java s
hello world
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
        at java.base/java.lang.StringLatin1.charAt(Unknown Source)
        at java.base/java.lang.String.charAt(Unknown Source)
        at s.main(s.java:9)

A: You are using next(), which only reads the hello the first time you call it. You would get the world if you called next() again.
Use nextLine() if you want to read hello world in one go.
You can refer to the documentation to read more about the different methods available on the Scanner class.


text: Q: Windows returns to the same exact state after reboot So, I'm using windows 11 on Lenovo Thinkpad E590. The problems started after installing Docker desktop and Splash. It was working just fine when suddenly blue screen of death appeared with syren like sound. After that,I can't do any changes on my pc. I can't install any software,to be precise it installs but doesn't open. I can't uninstall or delete anything,even if i succeed, they reappear after restart. I tried to format whole ssd with no success. Diskpart says that it succeeded in cleaning,but actually nothing happens. I've also tried 3rd party partition tools using Hiren's boot but still no success. I've also tried Lenovo Secure Wipe from bios and it says it succeded but in reality it didn't. I've also tried chkdsk and it says no problems detected


text:
Q: How to solve C# SqlNull Exception nullable on string? I get this error:

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
at Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
at Microsoft.Data.SqlClient.SqlBuffer.get_String()
at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)
at lambda_method11(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.Enumerator.MoveNext()   at System.Collections.Generic.List1..ctor(IEnumerable1 collection)   at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at ReportCrewApi.Services.ViewMastereIsAktifServices.GetMastereIsAktifs() in D:\Punya Ricky\Works\Insosys\Local\API for report\ReportCrewAPI\Services\ViewMastereIsAktifServices.cs:line 26

I tried using string? before but when I take a look at this doc, for string, the reference will be nullable, so I didn't use it. But I keep getting the same error like that. I've already take a look at my data on database
Columns in the database table:
       (<NIK, varchar(10),>
       ,<NIK_lama, varchar(10),>
       ,<Nama, varchar(100),>
       ,<KodeOrganisasi, varchar(20),>
       ,<Unit, varchar(255),>
       ,<Jabatan, varchar(50),>
       ,<KodeLokasi, int,>
       ,<LokasiKerja, varchar(100),>
       ,<KodeManajemen, int,>
       ,<ManajemenLevel, varchar(30),>
       ,<TanggalMasuk, datetime,>
       ,<TanggalDiangkat, datetime,>
       ,<KodeStatus, int,>
       ,<StatusHubunganKerja, varchar(100),>
       ,<TanggalLahir, datetime,>
       ,<BulanLahir, int,>
       ,<KodeKelamin, int,>
       ,<JenisKelamin, varchar(20),>
       ,<KodePerkawinan, int,>
       ,<StatusPerkawinan, varchar(100),>
       ,<KodePerumahan, int,>
       ,<StatusPerumahan, varchar(100),>
       ,<Owner, char(1),>
       ,<JumlahAnak, int,>
       ,<Kp, varchar(50),>
       ,<Ko, varchar(20),>
       ,<umur, int,>
       ,<TahunMasaKerja, smallint,>
       ,<BulanMasaKerja, smallint,>
       ,<KodeAgama, int,>
       ,<Agama, varchar(100),>
       ,<TempatLahir, varchar(25),>
       ,<KodeDarah, int,>
       ,<Darah, varchar(100),>
       ,<Alamat, varchar(100),>
       ,<SekolahK, varchar(200),>
       ,<LokasiK, varchar(200),>
       ,<JurusanK, varchar(200),>
       ,<TahunK, int,>
       ,<IPK, float,>
       ,<KodePendidikan, int,>
       ,<Pendidikan, varchar(100),>
       ,<KodeTransportasi, int,>
       ,<Transportasi, varchar(100),>
       ,<CountHobi, int,>
       ,<CountBahasa, int,>
       ,<LokasiAbsen, varchar(4),>
       ,<NomorHP, varchar(25),>
       ,<GolonganHP, varchar(5),>
       ,<NoKTP, varchar(40),>
       ,<NoAstek, varchar(25),>
       ,<NoBPJSKesehatan, varchar(50),>
       ,<Passport, varchar(20),>
       ,<Initial, varchar(15),>
       ,<KepesertaanPensiun, tinyint,>
       ,<BebanKp, varchar(20),>
       ,<BebanKo, char(1),>
       ,<BebanUnit, varchar(255),>
       ,<NamaPasangan, varchar(50),>
       ,<TanggalLahirPasangan, int,>
       ,<UmurPasangan, int,>
       ,<AlamatKTP, varchar(100),>
       ,<TanggalAwalPerjanjian, datetime,>
       ,<TanggalAkhirPerjanjian, datetime,>
       ,<RecentTglAwalPerjanjian, datetime,>
       ,<RecentTglAkhirPerjanjian, datetime,>
       ,<RecentTglMulaiMutasi, datetime,>
       ,<RecentTglSelesaiMutasi, datetime,>
       ,<TanggalPHK, datetime,>
       ,<BulanPHK, int,>
       ,<NoPolisi, varchar(25),>
       ,<Telepon, varchar(25),>
       ,<NPWP, varchar(50),>
       ,<SIM, varchar(20),>
       ,<KodePos, varchar(6),>
       ,<ExtensionTelpon, varchar(25),>
       ,<KodePHK, int,>
       ,<KeteranganPHK, varchar(100),>
       ,<unit_cnn, varchar(300),>
       ,<posisi_cnn, varchar(300),>
       ,<tgl_mulai_cnn, nvarchar(10),>
       ,<tgl_selesai_cnn, nvarchar(10),>
       ,<no_sk_cnn, varchar(100),>
       ,<lokasi_kerja_cnn, varchar(100),>
       ,<NoAkun, int,>
       ,<KodeSukuUsaha, int,>
       ,<NamaSukuUsaha, int,>
       ,<email, varchar(200),>
       ,<UnitShortName, varchar(255),>
       ,<Hobby, varchar(255),>
       ,<rekening_nama, varchar(50),>
       ,<rekening_no, varchar(50),>
       ,<NamaAnak1, varchar(30),>
       ,<TanggalLahirAnak1, datetime,>
       ,<NamaAnak2, varchar(30),>
       ,<TanggalLahirAnak2, datetime,>
       ,<NamaAnak3, varchar(30),>
       ,<TanggalLahirAnak3, datetime,>
       ,<NamaAnak4, varchar(30),>
       ,<TanggalLahirAnak4, datetime,>
       ,<division_code, varchar(50),>
       ,<division_name, varchar(300),>
       ,<department_code, varchar(50),>
       ,<department_name, varchar(300),>
       ,<kode_divisi_statistik, tinyint,>
       ,<nama_divisi_statistik, varchar(30),>
       ,<kode_sts_kry_statistik, smallint,>
       ,<nama_sts_kry_statistik, varchar(50),>
       ,<directorate_code, varchar(50),>
       ,<directorate_name, varchar(300),>)

I tried to compare my data models but nothing is different.
Here is my model class:
public class ViewMastereIsAktif
{
    [Key]
    [StringLength(10)]

    public string NIK { get; set; }

    [StringLength(10)]
    public string NIK_lama  {get; set;}
    [StringLength(100)]
    public string Nama { get; set; }
    [StringLength(20)]
    public string KodeOrganisasi { get; set; }
    [StringLength(255)]
    public string Unit { get; set; }
    [StringLength(50)]
    public string Jabatan { get; set; }
    #nullable enable
    public int? KodeLokasi { get; set; }
    [StringLength(100)]
    public string LokasiKerja { get; set; }
    #nullable enable
    public int? KodeManajemen { get; set; }
    [StringLength(30)]
    public string ManajemenLevel { get; set; }
    #nullable enable
    public DateTime? TanggalMasuk { get; set; }
    #nullable enable
    public DateTime? TanggalDiangkat { get; set; }
    #nullable enable
    public int? KodeStatus { get; set; }
    [StringLength(100)]
    public string StatusHubunganKerja { get; set; }
    #nullable enable
    public DateTime? TanggalLahir { get; set; }
    #nullable enable
    public int? BulanLahir { get; set; }
    #nullable enable
    public int? KodeKelamin { get; set; }
    [StringLength(20)]
    public string JenisKelamin { get; set; }
    #nullable enable
    public int? KodePerkawinan { get; set; }
    [StringLength(100)]
    public string StatusPerkawinan { get; set; }
    #nullable enable
    public int? KodePerumahan { get; set; }
    [StringLength(100)]
    public string StatusPerumahan { get; set; }
    #nullable enable
    public char Owner { get; set; }
    #nullable enable
    public int? JumlahAnak { get; set; }
    [StringLength(50)]
    public string Kp { get; set; }
    [StringLength(20)]
    public string Ko { get; set; }
    #nullable enable
    public int? umur { get; set; }
    #nullable enable
    public Int16 TahunMasaKerja { get; set; }
    #nullable enable
    public Int16 BulanMasaKerja { get; set; }
    #nullable enable
    public int? KodeAgama { get; set; }
    [StringLength(100)]
    public string Agama { get; set; }
    [StringLength(25)]
    public string TempatLahir { get; set; }
    #nullable enable
    public int? KodeDarah { get; set; }
    [StringLength(100)]
    public string Darah { get; set; }
    [StringLength(100)]
    public string Alamat { get; set; }
    [StringLength(200)]
    public string SekolahK { get; set; }
    [StringLength(200)]
    public string LokasiK { get; set; }
    [StringLength(200)]
    public string JurusanK { get; set; }
    #nullable enable
    public int? TahunK { get; set; }
    #nullable enable
    public float IPK { get; set; }
    #nullable enable
    public int? KodePendidikan { get; set; }
    [StringLength(100)]
    public string Pendidikan { get; set; }
    #nullable enable
    public int? KodeTransportasi { get; set; }
    [StringLength(100)]
    public string Transportasi { get; set; }
    #nullable enable
    public int? CountHobi { get; set; }
    #nullable enable
    public int? CountBahasa { get; set; }
    [StringLength(4)]
    public string LokasiAbsen { get; set; }
    [StringLength(25)]
    public string NomorHP { get; set; }
    [StringLength(5)]
    public string GolonganHP { get; set; }
    [StringLength(40)]
    public string NoKTP { get; set; }
    [StringLength(25)]
    public string NoAstek { get; set; }
    [StringLength(50)]
    public string NoBPJSKesehatan { get; set; }
    [StringLength(20)]
    public string Passport { get; set; }
    [StringLength(15)]
    public string Initial { get; set; }
    #nullable enable
    public Byte? KepesertaanPensiun { get; set; }
    [StringLength(20)]
    public string BebanKp { get; set; }
    #nullable enable
    public char BebanKo { get; set; }
    [StringLength(255)]
    public string BebanUnit { get; set; }
    [StringLength(50)]
    public string NamaPasangan { get; set; }
    #nullable enable
    public int? TanggalLahirPasangan { get; set; }
    #nullable enable
    public int? UmurPasangan { get; set; }
    [StringLength(100)]
    public string AlamatKTP { get; set; }
    #nullable enable
    public DateTime? TanggalAwalPerjanjian { get; set; }
    #nullable enable
    public DateTime? TanggalAkhirPerjanjian { get; set; }
    #nullable enable
    public DateTime? RecentTglAwalPerjanjian { get; set; }
    #nullable enable
    public DateTime? RecentTglAkhirPerjanjian { get; set; }
    #nullable enable
    public DateTime? RecentTglMulaiMutasi { get; set; }
    #nullable enable
    public DateTime? RecentTglSelesaiMutasi { get; set; }
    #nullable enable
    public DateTime? TanggalPHK { get; set; }
    #nullable enable
    public int? BulanPHK { get; set; }
    [StringLength(25)]
    public string NoPolisi { get; set; }
    [StringLength(25)]
    public string Telepon { get; set; }
    [StringLength(50)]
    public string NPWP { get; set; }
    [StringLength(20)]
    public string SIM { get; set; }
    [StringLength(6)]
    public string KodePos { get; set; }
    [StringLength(25)]
    public string ExtensionTelpon { get; set; }
    #nullable enable
    public int? KodePHK { get; set; }
    [StringLength(100)]
    public string KeteranganPHK { get; set; }
    [StringLength(300)]
    public string unit_cnn { get; set; }
    [StringLength(300)]
    public string posisi_cnn { get; set; }
    [StringLength(10)]
    public string tgl_mulai_cnn { get; set; }
    [StringLength(10)]
    public string tgl_selesai_cnn { get; set; }
    [StringLength(100)]
    public string no_sk_cnn { get; set; }
    [StringLength(100)]
    public string lokasi_kerja_cnn { get; set; }
    #nullable enable
    public int? NoAkun { get; set; }
    #nullable enable
    public int? KodeSukuUsaha { get; set; }
    #nullable enable
    public int? NamaSukuUsaha { get; set; }
    [StringLength(200)]
    public string email { get; set; }
    [StringLength(255)]
    public string UnitShortName { get; set; }
    [StringLength(255)]
    public string Hobby { get; set; }
    [StringLength(50)]
    public string rekening_nama { get; set; }
    [StringLength(50)]
    public string rekening_no { get; set; }
    [StringLength(30)]
    public string NamaAnak1 { get; set; }
    #nullable enable
    public DateTime? TanggalLahirAnak1 { get; set; }
    [StringLength(30)]
    public string NamaAnak2 { get; set; }
    #nullable enable
    public DateTime? TanggalLahirAnak2 { get; set; }
    [StringLength(30)]
    public string NamaAnak3 { get; set; }
    #nullable enable
    public DateTime? TanggalLahirAnak3 { get; set; }
    [StringLength(30)]
    public string NamaAnak4 { get; set; }
    #nullable enable
    public DateTime? TanggalLahirAnak4 { get; set; }
    [StringLength(50)]
    public string division_code { get; set; }
    [StringLength(300)]
    public string division_name { get; set; }
    [StringLength(50)]
    public string department_code { get; set; }
    [StringLength(300)]
    public string department_name { get; set; }
    #nullable enable
    public Byte? kode_divisi_statistik { get; set; }
    [StringLength(30)]
    public string nama_divisi_statistik { get; set; }
    #nullable enable
    public Int16 kode_sts_kry_statistik { get; set; }
    [StringLength(50)]
    public string nama_sts_kry_statistik { get; set; }
    [StringLength(50)]
    public string directorate_code { get; set; }
    [StringLength(300)]
    public string directorate_name { get; set; }
}

Before I check the doc, I've already tried everything using #nullable enable, public string? Property {get; set} = null and I've been googling it in others questions (here actually) but they all say the same that's not using string?,  the error pointing at my service when it says my string is null
ViewMastereIsAktifServices.cs
public class ViewMastereIsAktifServices : IViewMastereIsAktifServices
{
    private EFRMContext _efrm_context;
    private INVENTORYContext _inventory_context;

    public ViewMastereIsAktifServices(EFRMContext eFRMContext, INVENTORYContext iNVENTORYContext)
    {
        _inventory_context = iNVENTORYContext;
        _efrm_context = eFRMContext;
    }

    public IEnumerable<ViewMastereIsAktif> GetMastereIsAktifs()
    {
        //here is line 26
        var mstIsaktif = _inventory_context.view_mastereisaktif.OrderByDescending(x => x.NIK).ToList();
        return mstIsaktif;
    }
}

I really doubt that the problem is in the models, because I got the warning on the models, that says

Non-nullable property 'LokasiKerja' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

and every string after that property give me the same warning (I didn't get why the string get those warning when the property Jabatan isn't), that's why when I tried to run get my data on postman it give me the error (on very top above), I've been stuck at this point for 6 hours. How can I solve that?

A: This error occurs when the model expects the column to be Required, even though the error message specifically talks about nullability the two concepts, though related, are in this case different.

Please remove the multiple calls to #nullable enable from the model, this is a compiler directive that is either on or off for the rest of the code, you are continually setting it to ON, but in this case, we are not actually disputing the nullability of the value, strings by default are nullable and will work fine in this context.

The question is, which Model... you have not tagged this as such but it looks like an OData Service Implementation (you mentioned postman as well)
In this case it seems as if the OData Model is the culprit, in that model I suspect your field is marked as Required.
To prove this, locate your EdmModel builder script and either remove any Required declarations for the LokasiKerja field, or you could put this at the end of your builder fluent configuration:
modelBuilder.Entity<ViewMastereIsAktif>()
    .Property(x => x.LokasiKerja).IsRequired(false);

Now when you request the data feed, if it is the Required state that is causing trouble the error message will either be resolved, or will be referring to the next column that is Required but is null.
Showing your fluent configuration for this entity might also help to resolve the issue.
A quick search on SO finds this solution which may also help: https://stackoverflow.com/a/64001223/1690217

FYI The reason the error stack points us towards SQL being the cause is due to the LINQ deferred logic and the projection that OData imposes on the actual SQL that is executed and deserialized.


text:
Q: Batching & CAT Command I'm trying to add a string to the beginning of many files, creating a new file extension whilst maintaining the filename.
cat string.txt file001.old > file001.new
cat string.txt file002.old > file002.new
cat string.txt file003.old > file003.new
etc...

I tried to batch it by:
for i in *.old
do
    cat string.txt $i > $i.new
done

But this didnt exactly work, my skills are limited...
Thanks in advance for any help.

A: There are several ways to do it. This may be the simplest:
for i in *.old
do
  echo string.txt > ${i%old}new
  cat $i >> ${i%old}new
done

A: Or this shorter alternative
for i in *.old
do
  echo string.txt | cat - $i > ${i%old}new
done

or even with heredoc instead of pipe
for i in *.old
do
  cat - $i <<< string.txt > ${i%old}new
done

A: Thanks guys... I forgot to add the punctuation marks, Should look something like this:
for i in *.old
do
    cat string.txt "$i" > "$i".new
done

The output would look like "file002.old.new"
Where I used SED to remove the old extention
But I will definitely be trying the alternate methods
Thanks again, Nem


text:
Q: How can I check for stored procedure consistency across multiples servers I've got a stored procedure on 10 distinct servers, how can I check across all servers for stored procedure consistency?
I'm currently pulling the definition for each server manually, and comparing it in notepad++ compare tool.
It's quite time consuming, and surely I'm not the first one to have this problem.

A: Kankuru is a great and FREE monitoring tool for SQL Server developed here in France. Aside from its monitoring capabilities, it also has a DB compare tool that is easy and simple to use.
It will not only show you if your stored procedures, tables, indexes, types, etc. exist on two servers, but also what those differences are between those two servers.

Here is another compare screen

It's very easy to use and as mentioned before, won't cost you a dime.
To setup Kankuru

*

*Create an empty database in some SQL Server called Kankuru. The kankuru database just stores configuration information and some history and its very compact.

*Start Kankuru and from the Home Menu select Configuration

*Configure kankuru to use the server\instance and database that you just created.

There is documentation, but its in French. Google translate will be able to get you through one way or another.

A: One option to consider is to use SQLCMD to execute code on multiple servers from a single source.  You further could log the process for each server by qualifying a distinct log file on each instance calling the code.


text:
Q: How can I get TypeScript to type-check the spread operator in React props? This code properly flagged in TS:
<MyComponent nonexistentProp="foo" />
This code is not:
<MyComponent { ...{ nonexistentProp: "foo" }} />
It seems trivial for TS to check that improper props are not getting passed in - how can we enable this checking to ensure that we're passing in the expected props?

A: I suspect this type checking is subject to the same constraints as regular TypeScript code:
interface Contract {
  a: string;
}

const allowed: Contract = {
  a: "bc",
};

const notAllowed: Contract = {
  a: "bc",
  b: "dc",
};

const aboutToBeAllowed = {
  a: "bc",
  b: "dc",
};

const alsoAllowed: Contract = aboutToBeAllowed;

The problem shown here is that TypeScript has it's limitations, in that it's a structural type system.
It is only able to enforce the constraints that us humans think it should be doing in all cases during an object literal assignment (see notAllowed assignment).
The alsoAllowed case is essentially the same as the notAllowed variant, but it works.  This is because the anonymous object satisfies the Contract constraints.
Similarly, in your TSX example, this is essentially the same behavior as regular TypeScript:
interface Props { a: string; };
const MyComponent: React.SFC<Props> = (props) => <div />;

const myCompOk1 = <MyComponent a="ab" />;

const myCompBad1 = <MyComponent a="ab" b="cd" />;

const anonPropsNoExtra = { a: "bc" };
const myCompOk2 = <MyComponent {...anonPropsNoExtra} />;

const anonPropsWithExtra = { a: "bc", b: "cd" };
const myCompOk3 = <MyComponent {...anonPropsWithExtra} />;

I don't believe it's possible for it to enforce it the way you're looking for


text:
Q: oauth2callback.php uri misdirect error I am trying to do the Hello analytics php quick start https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/web-php#enable.
I have these redirects uris added to the google console developer
http://example.info/index.php
http://example.info/oauth2callback.php
I have the example code set up as following
index.php
        <?php
    // Load the Google API PHP Client Library.
    require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');

    // Start a session to persist credentials.
    //session_start();

    // Create the client object and set the authorization configuration
    // from the client_secretes.json you downloaded from the developer console.
    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

    // If the user has already authorized this app then get an access token
    // else redirect to ask the user to authorize access to Google Analytics.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      // Set the access token on the client.
      $client->setAccessToken($_SESSION['access_token']);

      // Create an authorized analytics service object.
      $analytics = new Google_Service_Analytics($client);

      // Get the first view (profile) id for the authorized user.
      $profile = getFirstProfileId($analytics);

      // Get the results from the Core Reporting API and print the results.
      $results = getResults($analytics, $profile);
      printResults($results);
    } else {
      $redirect_uri = 'http://example.info/oauth2callback.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

    function getFirstprofileId(&$analytics) {
      // Get the user's first view (profile) ID.

      // Get the list of accounts for the authorized user.
      $accounts = $analytics->management_accounts->listManagementAccounts();

      if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
            ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
          $items = $properties->getItems();
          $firstPropertyId = $items[0]->getId();

          // Get the list of views (profiles) for the authorized user.
          $profiles = $analytics->management_profiles
              ->listManagementProfiles($firstAccountId, $firstPropertyId);

          if (count($profiles->getItems()) > 0) {
            $items = $profiles->getItems();

            // Return the first view (profile) ID.
            return $items[0]->getId();

          } else {
            throw new Exception('No views (profiles) found for this user.');
          }
        } else {
          throw new Exception('No properties found for this user.');
        }
      } else {
        throw new Exception('No accounts found for this user.');
      }
    }

    function getResults(&$analytics, $profileId) {
      // Calls the Core Reporting API and queries for the number of sessions
      // for the last seven days.
      return $analytics->data_ga->get(
          'ga:' . $profileId,
          '7daysAgo',
          'today',
          'ga:sessions');
    }

    function printResults(&$results) {
      // Parses the response from the Core Reporting API and prints
      // the profile name and total sessions.
      if (count($results->getRows()) > 0) {

        // Get the profile name.
        $profileName = $results->getProfileInfo()->getProfileName();

        // Get the entry for the first entry in the first row.
        $rows = $results->getRows();
        $sessions = $rows[0][0];

        // Print the results.
        print "
First view (profile) found: $profileName
";
        print "
Total sessions: $sessions
";
      } else {
        print "
No results found.
";
      }
    }

 oauth2callback.php
    <?php
    require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->setRedirectUri('http://example.info/index.php');
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

    if (! isset($_GET['code'])) {
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
      $redirect_uri = 'http://example.info/index.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

I get error 400 the redirect URI in the request, http://example.info/index.php, does not match the ones authorized for the OAuth client, even though I am sure it does.

A: I was facing prety much same problem. What happened in my case was that I had many different services configured and since the api services user experience is very bad, I was setting up the call back url for another project.
So, Its a quick try..just copy and past the link in the error screen google shows you:

*That's an error.

Error: redirect_uri_mismatch


text:
Q: Sorting mySQL into organized lists with PHP I am pulling college classes and details out of a MySQL database and sorting them onto a webpage with PHP.
Currently my script is simple.  It pulls several fields and organizes them by class title:
Class name:  Programming 101

*

*Credit hours: 4

*Time: 11:00am - 12:50pm

*Days: M T W

*Room #: 361

Sometimes we have 3 or 4 of the same class going on, so this can create a rather long page.
I'm trying to simplify the way the page looks.

So instead of having repeated class names:
Class name: Programming 101

*

*Credit hours: 4

*Time: 11:00am - 12:50pm

*Days: M T W

*Room #: 361

Class name:  Programming 101

*

*Credit hours: 4

*Time: 11:30am - 2:50pm

*Days: Th F

*Room #: 123

You could see this:
Class name:  Programming 101
Credit hours: 4

*

*Time: 11:00am - 12:50pm

*Days: M T W

*Room #: 361

*

*Time: 11:30am - 2:30pm

*Days: Th F

*Room #: 123

Class name:  Programming 102
Credit hours: 4

*

*Time: 1:00am - 2:30pm

*Days: M W

*Room #: 231

*

*Time: 2:30am - 4:30pm

*Days: T F

*Room #: 222

Here is my current script:
$sql = "SELECT crs_title, trm_cde, last_name, first_name, begin_dte, end_dte, crs_cde, begin_tim, end_tim, monday_cde, tuesday_cde, wednesday_cde, thursday_cde, friday_cde, saturday_cde, sunday_cde, bldg_cde, room_cde, udef_5_2_1, crs_capacity, crs_enrollment, section_sts FROM BTC_Web_Schedule_view WHERE yr_cde = 2014 AND trm_cde = 'fa' ORDER BY crs_title, trm_cde";
                $rs = odbc_exec($conn,$sql);

                while (odbc_fetch_row($rs))
                {
                    $crs_title = odbc_result($rs,"crs_title");
                    $trm_cde = odbc_result($rs,"trm_cde");
                    $crs_cde = odbc_result($rs,"crs_cde");
                    $begin_tim = odbc_result($rs,"begin_tim");
                    $end_tim = odbc_result($rs,"end_tim");
                    $begin_time = substr($begin_tim, 11, -7);
                    $end_time = substr($end_tim, 11, -7);
                    $begin_dte = odbc_result($rs,"begin_dte");
                    $end_dte = odbc_result($rs,"end_dte");
                    $monday_cde = odbc_result($rs,"monday_cde");
                    $tuesday_cde = odbc_result($rs,"tuesday_cde");
                    $wednesday_cde = odbc_result($rs,"wednesday_cde");
                    $thursday_cde = odbc_result($rs,"thursday_cde");
                    $friday_cde = odbc_result($rs,"friday_cde");
                    $saturday_cde = odbc_result($rs,"saturday_cde");
                    $sunday_cde = odbc_result($rs,"sunday_cde");
                    $first_name = odbc_result($rs,"first_name");
                    $last_name = odbc_result($rs,"last_name");
                    $fullname = $first_name.$last_name;
                    $bldg_cde = odbc_result($rs,"bldg_cde");
                    $room_cde = odbc_result($rs,"room_cde");
                    $udef_5_2_1 = odbc_result($rs,"udef_5_2_1");
                    $crs_capacity = odbc_result($rs,"crs_capacity");
                    $crs_enrollment = odbc_result($rs,"crs_enrollment");
                    $seats_left = $crs_capacity - $crs_enrollment;
                    $section_sts = odbc_result($rs,"section_sts");

                    echo "

$crs_title
 | $crs_cde

";
                    echo "

Time: ".date('g:ia', strtotime($begin_time))." - ".date('g:ia', strtotime($end_time))."
";
                    echo "Start date: ".date("F jS, Y",strtotime($begin_dte))."
";
                    echo "End date: ".date("F jS, Y",strtotime($end_dte))."
";
                    echo "Days: $monday_cde $tuesday_cde $wednesday_cde $thursday_cde $friday_cde $saturday_cde $sunday_cde
";
                    echo "Instructor: $fullname
";
                    echo "Building: $bldg_cde
";
                    echo "Room: $room_cde
";
                    echo "Fee: $$udef_5_2_1
";
                    echo "Seats remaining: $seats_left
";
                    echo "Enrollment status: $section_sts

";
                }
                odbc_close($conn);

I appreciate any advice.  Thank you.

A: Normalize your database?
Other then that:
while (odbc_fetch_row($rs))
{
    $crs_title = odbc_result($rs,"crs_title");
    $first_name => odbc_result($rs,"first_name");
    $last_name => odbc_result($rs,"last_name");
    $fullname = $first_name.$last_name;
    $begin_tim = odbc_result($rs,"begin_tim");
    $end_tim = odbc_result($rs,"end_tim");
    $crs_capacity = odbc_result($rs,"crs_capacity");
    $crs_enrollment = odbc_result($rs,"crs_enrollment");
    $courses[$crs_title][] = array(
        $trm_cde = odbc_result($rs,"trm_cde")
        'crs_cde' => odbc_result($rs,"crs_cde"),
        'begin_tim' => $begin_tim,
        'begin_time' => substr($begin_tim, 11, -7),
        'end_tim' => $end_tim,
        'end_time' = substr($end_tim, 11, -7),
        'begin_dte' => odbc_result($rs,"begin_dte"),
        'end_dte' => odbc_result($rs,"end_dte"),
        'monday_cde' => odbc_result($rs,"monday_cde"),
        'tuesday_cde' => odbc_result($rs,"tuesday_cde"),
        'wednesday_cde' => odbc_result($rs,"wednesday_cde"),
        'thursday_cde' => odbc_result($rs,"thursday_cde"),
        'friday_cde' => odbc_result($rs,"friday_cde"),
        'saturday_cde' => odbc_result($rs,"saturday_cde"),
        'sunday_cde' => odbc_result($rs,"sunday_cde"),
        'first_name' => $first_name,
        'last_name' => $last_name,
        'fullname' => $first_name.$last_name,
        'bldg_cde' => odbc_result($rs,"bldg_cde"),
        'room_cde' => odbc_result($rs,"room_cde"),
        'udef_5_2_1' => odbc_result($rs,"udef_5_2_1"),
        'crs_capacity' => $crs_capacity,
        'crs_enrollment' => $crs_enrollment,
        'seats_left' = $crs_capacity - $crs_enrollment,
        'section_sts' => odbc_result($rs,"section_sts"),
    );
    foreach ($courses as $crs_title => $data) {
        /* html output */
        $count = count($data);
        foreach ($data as $subdata) {
            //multiple times
        }
    }
}

A: A few things to consider:
Change your query to do as much of the sorting as possible before even retrieving the data. For example, you could ORDER BY course title first (then secondarily by other fields like start date).
Build an array from the data such that you can easily output in teh way you want:  For example:
$array = array();
while (odbc_fetch_row($rs)) {
     //  ... get your data (probably use something besides odbc_result so you can get ther whole array at once .. but for this example just assume I am using your same variables.
     $array[$crs_title] = array(
        // place your other course data here in array
     );
}
foreach($array as $course_title => $course_data) {
    // present your data
}


text:
Q: Identification of $L^2(0,T;H^2(\Omega))$ with $L^\infty(Q_T)$ Let $T>0$ and $\Omega \subset \mathbb{R}^n$ be a bounded set with smooth boundary. Define $Q_T:=\Omega \times (0,T).$ In which case can the Hilbert space $L^2(0,T;H^2(\Omega))$ be identified with $L^\infty(Q_T)$?

A: Never.
If $f\in L^2((0,T))$ is unbounded then $f\cdot\chi_{\Omega}$ is in $L^2((0,T);H^2(\Omega))$ but not in $L^{\infty}(\Omega_T)$.
If $u\in L^{\infty}(\Omega)$ is not in $H^2(\Omega_T)$, then $u\cdot\chi_{(0,T)}$ is in $L^{\infty}(\Omega_T)$ but not in $L^2((0,T);H^2(\Omega))$.


text:
Q: How to close the program after the user enters a character and presses the enter key? I just started learning C++ programming. My program runs perfectly but i also need it to close when the user enter s a character and presses the enter key. I have no idea how that is supposed to be done. any help will be really appreciated. My code so far is(runs fine) :
#include <iostream>
using namespace std;

int main()
{
    int money_spent, money_tendered;

    cout << "Enter the total amount spent: \n";
    cin >> money_spent;

    cout << "Enter the amount tendered: \n";
    cin >> money_tendered;

    int balance = money_tendered - money_spent;
    int ten_bills = balance / 1000;
    balance = balance % 1000;
    int five_bills = balance / 500;
    balance = balance % 500;
    int dollar_coins = balance / 100;
    balance = balance % 100;
    int quater_coins = balance / 25;
    balance = balance % 25;
    int dimes = balance / 10;
    balance = balance % 10;
    int nickels = balance / 5;
    balance = balance % 5;
    int pennies = balance;

    cout << " \n \n"
        << "Your change is: \n"
        << ten_bills << " tenn dollar bill(s). \n"
        << five_bills << " five dollar bill(s). \n"
        << dollar_coins << " one dollar coin(s). \n"
        << quater_coins << " quater(s). \n"
        << dimes << " dime(s). \n"
        << nickels << " nickel(s). \n"
        << pennies << " pennie(s). \n";

    return 0;
}

A: Add
cin.ignore();
cin.get();

before
return 0;

You need cin.ignore(), to ignore the ENTER you typed after entering money_tendered. Otherwise this ENTER will be captured by cin.get() instead of the last character you are going to enter.

A: use
getchar();

It's a standard c-function.

A: You need to change your cin to read a string.  Then you need to check to see if that string is "s".  If so you want to return 0.  Otherwise you want to convert the string to an integer and store it in money_spent or money_tendered.  Then you want to wrap the entire procedure in a while(1) { } loop so that it doesn't exit automatically.

A: Add the following line at the end of your program.
system("pause");
One the application comes to this line it will show you
Press any key to continue . . . message. Once you click a button the application automatically exit the process.


text:
Q: how to make static "polymorphic" member variables Basically what I am trying to do here is make an ID for each derived type of Shape. ( Square is 1, Circle is 2, etc.)
How can I make a static member variable that has polymorphic capabilities? How would I create the getters and setters?
class Shape {
public:
    Shape() {}
    static int ID;
};

class Square : public Shape {
public:
    Square() {}

};

class Circle : public Shape {
public:
    Circle() {}

};

class Person {
public:
    int shape_type_ID
    Shape* ptr;
    Person(){}
};

int Shape::var{ 5 };

Is this a copy of this question?
How to initialize `static` member polymorphically
EDIT:
In my current design, each instance of Person contains a pointer ( I am not sure about the type of pointer ) that points to some Shape object. I want to restrict each Person object to only being able to reference one derived type of Shape.
E.g. Person 1's pointer can only reference Circles, Person 2's pointer can only reference Squares, Person 3's pointer can only reference Triangles.
But I want 1 single Person class with 1 type of pointer ( probably Shape ). In theory that should be do-able. One of the problems is that there should be as many Person objects as there are Shape derived types (one for Square, one for Circle, one for Triangle). How do I know how many Person objects to make?

A: When you want polymorphism you should use virtual methods, not static members.
class Shape {
public:
    virtual int ID(){ return 0; }
    virtual ~Shape(){}
};

class Square : public Shape {
public:
    virtual int ID() override { return 1;}
};

class Circle : public Shape {
public:
    virtual int ID() override { return 2; }
};

A: you can do something like this if you really need to, but I suggest just making a constructor in base that accepts an id and pass it from the childs to the parent
int getNextId()
{
    static int lastId{0};
    return lastId++;
}

template<typename T>
int getDerivedId()
{
    static int id{getNextId()};
    return id;
}

struct Base {
};

struct Derived0 final : Base {
};

struct Derived1 final : Base {
};

int main() {
    return !(getDerivedId<Derived0>() == 0 && getDerivedId<Derived1>() == 1);
}


text:
Q: Определение цвета каждого пикскеля с помощью Jimp Мне нужно по очереди узнать цвет каждого пикселя и производить в программе вычисления . Я хочу использовать jimp , но не знаю как . Прошу помощи у вас .

A: Картинка, cкрипт:
const jimp = require('jimp');

(async () => {

  const img = await jimp.read(`${__dirname}/q.png`);

  for (
    const { x, y, idx }
    of
    img.scanIterator(0, 0, img.bitmap.width, img.bitmap.height)
  ) {

    const colorHex = img.getPixelColor(x, y);

    const colorRgba = jimp.intToRGBA(colorHex);

    console.log(`x=${x}, y=${y}:    colorHex=${colorHex}, colorRgba=${JSON.stringify(colorRgba)}`);
  }

})();

Вывод:
x=0, y=0:    colorHex=0, colorRgba={"r":0,"g":0,"b":0,"a":0}
x=1, y=0:    colorHex=4294967295, colorRgba={"r":255,"g":255,"b":255,"a":255}
x=2, y=0:    colorHex=4211607807, colorRgba={"r":251,"g":8,"b":8,"a":255}
x=0, y=1:    colorHex=16904447, colorRgba={"r":1,"g":1,"b":240,"a":255}
x=1, y=1:    colorHex=50276095, colorRgba={"r":2,"g":255,"b":38,"a":255}
x=2, y=1:    colorHex=4277994239, colorRgba={"r":254,"g":253,"b":2,"a":255}

В документации это - раздел Low-level manipulation.


text:
Q: When is injective contraction isometry Let $f:X \to Y$ be a injective linear map between (semi-)normed spaces, s.t $B_Y = f(B_X)$, $B_X,B_Y$ being the unit balls. Is $f$ an isometry? If so, was there a superfluous requirement?
EDIT: I guess the answer should be yes, since $f^{-1}(\mathring{B_Y})$ should be $\mathring{B_X}$, hence $||f(x)||=1$ for $||x||=1$.

A: Yes.
First $f$ is surjective. Indeed, let $y \in Y$. $\frac{y}{||y||} \in B_Y = f(B_X)$  hence there is $x \in B_X$ s.t $f(x)=\frac{y}{||y||}$ and so $f(||y||x)=y$ by linearity. We conclude that $f$ is surjective and hence bijective (we already know it is injective by assumption)
Because of the facts that $B_Y = f(B_X)$ and that $f$ is bijective, we have $B_X=f^{-1}(B_Y)$ thus $||f^{-1}(y)|| \leq ||y||$ for all $y \in Y$. (*)
Now let $y \in Y$. There exists $x \in X$ s.t $y=f(x)$.
Then $||f^{-1}(y)|| = ||f^{-1}( f(x) )|| = ||x|| \geq ||f(x)|| = ||y||$ (**)
Using (*) and (**) we deduce that  $||f^{-1}(y)||=||y||$ for all $y \in Y$.
Finally, for all $x \in X$ we have:  $||x||=||f^{-1}(f(x))|| = ||f(x)||$ so $f$ is an isometry.


text:
Q: How to debug source IP which try to access SSH server through port forwarding by SSH my case is likely following case: SSH client(192.168.0.11) -> public cloud VM with SSH server and setup port forwarding (139.90.90.90)(CentOS7.9)-> one internal SSH server(10.24.24.24)(CentOS 7.9).
I have created port forwarding to access one of my internal SSH server and I can access it through a public cloud VM with specific port.
ssh -L *:10100:10.24.24.24:10100 -N -f aa@139.90.90.90

My laptop SSH client can access 139.90.90.90:10100 successfully.
But recently, I found one issue: since I open port on Internet, there have many invalid SSH login requests which sometimes make the server cost additional resources. It should be not safe, so I use firewalld-cmd to reject some source IP.
My question is about how to detect those source IPs? Since at internal SSH server, it will just show public cloud IP address which 139.90.90.90. For example, like following on my internal Linux Server (/var/log/secure):

May 10 23:48:46 z1 sshd[17066]: input_userauth_request: invalid user nano [preauth]
May 10 23:48:46 z1 sshd[17066]: pam_unix(sshd:auth): check pass; user unknown
May 10 23:48:46 z1 sshd[17066]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=139.90.90.90
May 10 23:48:48 z1 sshd[17066]: Failed password for invalid user nano from 139.90.90.90 port 40800 ssh2

Any idea how can I find out the source IP then I may block that in my public cloud server through firewalld.
Thanks,
Eugene

A: Anyway, I didn't find a way to identify it accurately. But I found one possible to help block those attackers (hackers). Change the SSH config file with " LogLevel DEBUG1", then you should see many entries like "server_request_direct_tcpip: originator 128.199.32.98 port 48498, target 211.95.84.14 ", at that point, you can check if those IPs are valid.
Then you can make a script to check if invalid IP, and block the connection.
firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=$IP reject"

You can also make a white list to allow valid connections.


text:
Q: Object reference not set to an instance of an object using combobox.selecteditem.tostring(); I'm trying to replace certain lines of text in my .text file but am getting the error specified above. Please help, I don't know what the error means and have looked everywhere to try to find a way to solve this problem. Nothing has really made sense to me, thanks in advance! If you need any other info,  please ask instead of just setting my post to off-topic, I really don't get what that means either.
Current Code:
    private void DeleteButton2_Click(object sender, EventArgs e)
    {
        if (comboBox2.SelectedItem == "")
        {
            MessageBox.Show("Please Select a Contact.");
        }
        else
        {

            comboBox2.Items.Remove(comboBox2.SelectedItem);
            comboBox1.Items.Remove(comboBox2.SelectedItem);
            string currentselection = comboBox2.SelectedItem.ToString();
            File.WriteAllLines(currentselection + ".txt",       File.ReadAllLines(currentselection + ".txt").Select(line => line.Replace(currentselection, "")));
        }
    }

A: You get Object reference not set to an instance of an object when trying to access something that is null. In your case, comboBox2.SelectedItem appears to be null. You'll need to check for that before accessing it. Doing == "" is not the same thing!
Change your:
if (comboBox2.SelectedItem == "")

To:
if (comboBox2.SelectedItem == null)

Also, you'll notice that once you have deleted the item - trying to access it with SelectedItem won't work anymore.

A: try this . put a break point under this line.
comboBox2.Items.Remove(comboBox2.SelectedItem); - first one
Watch how the checkbox2.items change and the seletItem is null.

A: It means SelectedItem is null.  SelectedItem will be null if nothing is selected in the combobox.
A NullReference exception always means you are trying to access a member on a value that is null.  You should use a debugger and check all the variables when that error occurs.