text:
Q: Ruby: if variable vs if variable.nil? I'm new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.
A nice thing about that property of the language is that you can write:
if !variable
  # do stuff when variable is nil
end

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:
if variable.nil?
  # do stuff when variable is nil
end

However I believe that the latter is a better option for two reasons:
1. I think it's more object oriented, especially in a language like Ruby where everything is an object and message exchange.
2. It is more readable, in my subject opinion, even if it is less compact.
Am I making a "newbie" mistake here?

A: Consider the following:
response = responses.to_a.first
This will return the first element of responses, or nil. Then because conditional statements treat nil as false we can write:
response = responses.to_a.first
if response
  # do something ('happy path')
else
  # do something else
end

Which is more readable than:
if response.nil?
  # do something else
else
  # do something ('happy path')
end

The if (object) pattern is very common in Ruby code. It also leads nicely to refactoring, e.g.:
if response = responses.to_a.first
  do_something_with(response)
else
  # response is equal to nil
end

Remember also that a Ruby method returns nil by default. So:
def initial_response
  if @condition
    @responses.to_a.first
  else
    nil
  end
end

can be simplified to:
def initial_response
  if @condition
    @responses.to_a.first
  end
end

So we can further refactor:
if response = initial_response
  do_something_with(response)
else
  # response is equal to nil
end

Now you can argue that returning nil is not always the best idea, since it means checking for nil everywhere. But that is another kettle of fish. Given that testing for object "presence or absence" is such a frequent requirement, the truthiness of objects is a useful aspect of Ruby, albeit surprising for newcomers to the language.

A: Write what you mean. Mean what you write.
Lets take a different test.  .vowel?
if char == 'a'
   # do stuff
end

vs
if char.vowel?
   # do stuff
end

Now, its obvious that these do not do the same thing.  But if you're only expecting char to be a or b it will work.  But it will confuse the next developer - the second block will be entered into for the conditions where char is [eiou] also.  But for a, it will work correctly.
Yes, it is the case that nil and false are the only falsy values in Ruby. However, if you are testing for nil by testing for nil || false, this isn't what you mean.
It means that the next developer (who happens to be a crazy axe murder who knows your home address) will read the code, and wonder why false should go in there too.
Write the code that conveys exactly what you mean.

A: Not only is if variable.nil? read more like natural language, it also guards against a programmer accidentally assigning it a false value and falling into your if statement, since Ruby is a loosely typed language.

A: Idiomatically, unless variable is preferable to if !variable. Negated if statements are often considered a code smell as it's easier to miss the negation when skimming.
The bigger picture here is that doing nil checks like this is also a bit of a code smell. For proper OO, aim to use the null object pattern so that this sort of check is never needed.
Tell objects what to do, don't ask them what they are. This is sometimes known as tell don't ask


text:
Q: Add padding on the left and right sides of the line/area chart How to add padding on the left and right sides of the line/area chart?
Here's how my chart looks like:

and this is how it should look like (the padding/margin part):

A: Modifying the axis range fig.update_xaxes() seems to be the best approach. And how you do the modifications will depend on your data size and type. Here's an example using dates where the range of the x-axis is increased by one day at the start and end of the source data:
Plot 1: Adjusted x-axis

Code:
import pandas as pd
import plotly.graph_objects as go

# data
yVals = [3, 2, 3, 5, 2, 6]
days = len(yVals)
dates = pd.date_range('1/1/2020', periods=numdays)

# plotly figure
fig = go.Figure()
fig.add_trace(go.Scatter(x=dates,
                         y=yVals,
                         fill='tozeroy')
             )

# adjustments
fig.update_xaxes(range=[dates[0]-1,dates[-1]+1])

fig.show()

Plot 2: Unadjusted x-axis

A: Inspired by vestland's answer but done in Javascript.
Before

After

Code
element = document.getElementById('traffic-overview');

data = [{
    x: ["2019-09-29", "2019-09-30", "2019-10-01", "2019-10-02", "2019-10-03", "2019-10-04", "2019-10-05", "2019-10-06", "2019-10-07", "2019-10-08", "2019-10-09", "2019-10-10", "2019-10-11", "2019-10-12", "2019-10-13", "2019-10-14", "2019-10-15", "2019-10-16", "2019-10-17", "2019-10-18", "2019-10-19", "2019-10-20", "2019-10-21", "2019-10-22", "2019-10-23", "2019-10-24", "2019-10-25", "2019-10-26", "2019-10-27", "2019-10-28"],
    y: [30, 66, 49, 154, 220, 224, 243, 164, 90, 71, 164, 199, 246, 251, 217, 85, 67, 156, 204, 218, 233, 204, 82, 59, 183, 205, 197, 219, 271, 116],
    fill: 'tozeroy',
    //fillcolor: '#9ed4fd',
    line: {
      color: '#008ffb'
    },
    //mode: 'lines',
    type: 'scatter'
}];

layout = {
    responsive: true,
    margin: { t: 10, b: 30, l: 30, r: 0 },
    xaxis: { range: ["2019-09-28", "2019-10-29"] } // <-- note this line!
};

Plotly.plot( element, data, layout );

JSFiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: p5.play - rotate collider along with sprite I'm using p5.play and I'm trying to have my sprite rotated at a slight angle, and I need a collider on it as well. I can do this:
let sprite = createSprite(x, y, width, height);
sprite.setCollider("rectangle", 0, 0, width, height);

But this doesn't rotate the collider, just makes it larger.

What I need is a collider matching the sprite, like here:

The setCollider function seems to ignore the rotation too.
Is it an error on my end or the library?

A: From looking at the documenation for p5.play, it sounds like this is not possible:

The sprite's current collider. It can either be an Axis Aligned Bounding Box (a non-rotated rectangle) or a circular collider.

So it sounds like if you want more advanced collision detection, you're going to have to do it manually. Googling something like "rotated rectangle collision detection" will return a ton of results.


text:
Q: Best way to expand info in hover AngularJs On mouse-over element must be expanded , on mouse-out must be collapsed.
In this way this functions works very slowly (expanded files visible after 2 second)
Whats the fastest wey expand on mouseover and collapse in this situation ?

      // mb-scrollbar is custom style scrollbar directive
      //Info about sport

//Controller

$scope.openGame = function(sport){
       this.hover = true;
       this.expandLeftMenuPrematchSport(sport, null, null, false);
       this.selectSport(sport,!$scope.sport[sport.id].expanded);
}

$scope.closeGame= function(sport){
       this.hover = false;
       this.expandLeftMenuPrematchSport(sport, null, null, false);
}

Images:
.On mouseover : https://i.stack.imgur.com/yXqbJ.png
SITE DEMO : https://www.loungebet.com/#/sport/?type=0&sport=-12&competition=566&game=5967702
(In left side ,sports)


text:
Q: How to solve a Camel3 fat-jar creation exception? I use Apache Camel 3.18.2 witch camel-main. To create a fat-jar I configured the following two plugins within my pom.xml:
  <plugin>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-maven-plugin</artifactId>
    <version>3.18.2</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>prepare-fatjar</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <mainClass>de.powerstat.camel.homeautomation.MainApp</mainClass>
        </manifest>
      </archive>
    </configuration>
    <executions>
      <execution>
        <id>make-assembly</id>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

As dependecies I have:
<dependencies>
  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-core</artifactId>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-main</artifactId>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-test</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-netty</artifactId>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-stream</artifactId>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-paho</artifactId>
  </dependency>

  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-quartz</artifactId>
  </dependency>

  <dependency>
     <groupId>de.powerstat.camel.component</groupId>
     <artifactId>camel-fbaha</artifactId>
    <version>1.0-SNAPSHOT</version>
  </dependency>

  <dependency>
     <groupId>de.powerstat.camel.component</groupId>
     <artifactId>camel-fbtr64</artifactId>
    <version>1.0-SNAPSHOT</version>
  </dependency>

  <dependency>
    <groupId>org.openmuc</groupId>
    <artifactId>jsml</artifactId>
    <version>1.1.2</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.18.0</version>
    <scope>runtime</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.18.0</version>
    <scope>runtime</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.18.0</version>
    <scope>runtime</scope>
  </dependency>

</dependencies>

But durin running mvn clean install I got:
[INFO] --- camel-maven-plugin:3.18.2:prepare-fatjar (default) @ myhome ---
[INFO] Found 5 Camel type converter loaders from project classpath
[INFO]
[INFO] --- maven-assembly-plugin:2.2-beta-5:single (make-assembly) @ myhome ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:single (make-assembly) on project myhome: Error reading assemblies: No assembly descriptors found. -> [Help 1]

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Exception in thread "ivy-httpclient-shutdown-handler" java.lang.NoClassDefFoundError:
org/apache/http/impl/conn/PoolingHttpClientConnectionManager$2
  at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.shutdown(PoolingHttpClientConnectionManager.java:413)
  at org.apache.http.impl.client.HttpClientBuilder$2.close(HttpClientBuilder.java:1244)
  at org.apache.http.impl.client.InternalHttpClient.close(InternalHttpClient.java:201)
  at org.apache.ivy.util.url.HttpClientHandler.close(HttpClientHandler.java:357)
  at org.apache.ivy.util.url.HttpClientHandler$1.run(HttpClientHandler.java:84)
  at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.conn.PoolingHttpClientConnectionManager$2
  at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
  at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
  at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
  at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
  ... 6 more

That looks to me like this is an implicit dependency that have not been added by the camel-maven-plugin.
So my question is how to solve this problem?
I also tried to use the maven-shade-plugin instead of maven-assembly-plugin:
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.4.0</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
        <configuration>
          <createDependencyReducedPom>true</createDependencyReducedPom>
          <filters>
            <filter>
              <artifact>*:*</artifact>
              <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
              </excludes>
            </filter>
          </filters>
        </configuration>
      </execution>
    </executions>
  </plugin>

Which then results in a fat-jar with the following exception during executing it:
[ERROR] 2022-09-30T22:04:48,426 15612/22 org.apache.camel.processor.errorhandler.DefaultErrorHandler Failed delivery for (MessageId:
08B251E5AD78E72-0000000000000000 on ExchangeId:
08B251E5AD78E72-0000000000000000). Exhausted after
delivery attempt: 1 caught:
org.apache.camel.InvalidPayloadException: No body available of type: java.lang.Integer but has type:
java.lang.String on: Message. Caused by: No type converter available to convert from type: java.lang.String to the required type: java.lang.Integer. Exchange[]. Caused by:
[org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type:
java.lang.String to the required type: java.lang.Integer]

So it looks the shade-plugin creates a fat-jar but missed something of camels dependencies.
Maybe this could be solved in one or the other way?
Last but not least the main question is how to create a Camel3 fat jar that is complete and works correctly?

A: Based on the error message

Error reading assemblies: No assembly descriptors found.

It looks like you are missing your assembly descriptor. You'll need to define  a descriptor or descriptorRef
descriptor example:
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.4.2</version>
        <configuration>
          <descriptors>
            <descriptor>src/assembly/src.xml</descriptor>
          </descriptors>
        </configuration>
        [...]
</project>

descriptorRef example:
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <!-- NOTE: We don't need a groupId specification because the group is
             org.apache.maven.plugins ...which is assumed by default.
         -->
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.4.2</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        [...]
</project>

If defining a descriptor, see the this about the descriptor format.


text:
Q: How do I get rid of my Criminal Record? In Fallen London, we all come from New Newgate Prison, and most of us go back there sooner or later. Each time your Suspicion hits 8, you're hauled off to court, where the magistrate will sentence you to jail. (The first time this happens, two points are knocked off of your Suspicion; this makes the jail sentence shorter.) Going before the Magistrate also appears to increase your Criminal Record quality by an unknown amount. (Criminal Record is an un-tracked quality; you can't see each change point as it is applied.)
I'm currently facing a dilemma: when faced with the prospect of jail, should I purchase a collection of Instant Ablution Absolution (which cost 1 Echo each, and takes off about 3 change points of Suspicion and one change point of Scandal), or should I just go to prison? The latter is generally more tempting; it's much cheaper, and you can generally work off about two-plus change points of Suspicion per action in prison, anyway. (Doing the auto-fire opportunities doesn't cost an action point if you're out of action points; there are also ways to simply pay your way out at a reasonably good rate: 50-pence-worth-of-items per 3-or-so change points.)
So, since prison isn't that daunting, I'm terribly tempted to just go there instead of trying to wash away my sins. That increasing Criminal Record of mine is daunting, though: it looks like it will eventually increase to the point that it becomes inconvenient (significantly reducing the value of the Instant Ablution Absolution, for one), but I don't know if I'll be able to reduce it later.
Is there a way to reduce my Criminal Record?

A: No, you cannot reduce your Criminal Record.
This has the side effect of making Suspicion the most punishing menace by a long shot, as not only does it eventually make Ablution Absolution ineffective, but as it increases, going to prison will cost you more and more goods and connections.
In addition, at the same time as the Absolution loses its effectiveness, you also lose the ability to cash in Connected: The Masters of the Bazaar to avoid adding on to it when you're caught!
So you're best off buying a large number of bottles. They're still quite effective as a Person of Some Importance, knocking off an average of 6 points of menace (1-10 Suspicion, and 1 Scandal), contrasted with the effective 2 points that laudanum or Tincture of Vigour provide.


text:
Q: reading and sorting files from a directory with for loop in python Hi Guys,
I have 13 .npy file in a directory. Some of them start with the same name.
Example:

B59_180322_153253.npy
B59_180322_173253.npy
B60_180324_153253.npy
B60_180324_173253.npy
B61_180324_173253.npy
B62_180324_173253.npy
  ....
  ....

I need to read them and concatenate the ones which starts with the same name (B59) in a for loop then assign to dictionary data. But I could not find an automated way for this.
Do you have any suggestion?
>

data = {'B59':[],
              'B62':[],
        'B65':[],

        'B67':[],

        'B68':[],

        'B79':[],

        'B80':[]}

The code works nicely when there are no multiple files which starts with the same name. ANY will be appreciated, thanks in advance.
Best

for file in glob.glob("*.npy"):
   experiment_id=file.split('_')[0]

   print(experiment_id)

   var = np.load(file)

  data[experiment_id]=var

A: Thank you very much.
Iterate over your txt files
With the below code I am able to create dictionary with keys that have file names. So I dont have write it myself.
But still the dictionary gets only the first npy file when there are 2 starting with the same name.
And this one did not work, so I removed it and
data[experiment_id].append(var)
direc = os.getcwd() # Get current working directory
text = '.npy' # Select your file delimiter

file_dict = {} # Create an empty dict

# Select only files with the ext extension
txt_files = [i for i in os.listdir(direc) if os.path.splitext(i)[1] == ext]

for f in txt_files:
   with open(os.path.join(direc,f)) as file_object:
   experiment_id=f.split('_')[0]
   print(experiment_id)
   file_dict[experiment_id]=np.load(f)

What do you think can be added on here?


text:
Q: configuring to use localStorage as endpoint instead of local server I am using a javascript library that generates annotations within an ePub.  I am hoping to use HTML5 localStorage for storing the annotation data.
Is there a way to have an endpoint url associated with localStorage?
In the hook that invokes the library there is a variable for 'server', which is currently set to a url for the local server, port 5000.
I am hoping to replace that with some pointer to localStorage, but I'm not sure what endpoint would be involved.  Seems like the only method for adding in information would be the method "localStorage.setItem", which in turn needs a variable name as an argument, so it wouldn't be appropriate as an endpoint.
The unadulterated hook, before I customized it is in this github repo,
My current version after editing, (which isn't functioning) is as follows:
    EPUBJS.Hooks.register("beforeChapterDisplay").annotate = function(callback, chapter){

        var chap = chapter.bodyEl,
            server = localStorage;
            files = [
                        EPUBJS.filePath + "annotator-full.js"
                     ];

        console.log(files);//show the pathways defined above

        EPUBJS.core.load(files, chapter.doc.head);
        $(chapter.doc.body).annotator().annotator('setupPlugins', {}, {

            Filter:false,
            Store: {
                annotationData: {
                  'uri': chapter.path
                },
                loadFromSearch: {
                    'limit': 100,
                    'uri': chapter.path
                }
            }

        });

        Util.mousePosition = function(e, offsetEl) {
          var offset;
          offset = $(offsetEl).position();
          return {
            top: e.pageY,
            left: e.pageX
          };
        };

            devAnnotator = new Annotator(chapter.doc.body)
            // .addPlugin('Auth', {
            //            tokenUrl: 'http://annotateit.org/api/token',//'http://localhost:5001/api/token'
            //          })
            // .addPlugin('Unsupported')
            // .addPlugin('AnnotateItPermissions')
            // .addPlugin('Store', {
            //   prefix: 'http://annotateit.org/api',//'http://localhost:5000',
            //   loadFromSearch: {
            //     uri: chapter.currentChapter.href
            //   },
            //   annotationData: {
            //     uri: chapter.currentChapter.href
            //   }
            // });

      //         devAnnotator.plugins.Auth.withToken(function (tok) {
      //           console.log(tok);
      //         })

        // EPUBJS.core.addCss("../libs/annotator/css/annotator.css", false, chapter.doc.head);

        if(callback) callback();

        function annotate(){
            // EPUBJS.core.addCss("css/annotator.css", false, chapter.doc.head);

            var s = document.createElement("script");
            s.type = 'text/javascript';

            console.log(jQuery);
            var a = "jQuery.migrateTrace = false;";
            a += "console.log(document.getElementById('c001p0002').getBoundingClientRect());";

            a += "var content = $('body').annotator().annotator('setupPlugins', {}, {Filter:false});";

            //-- Use Local Server:

            a += "var content = $('body').annotator(),";
            a += "  server = '" + server + "';";
            a += "  path = '" + chapter.path + "';";

            a += " content.annotator('addPlugin', 'Store', {";
            // The endpoint of the store on your server.
            a += "  prefix: server,";

            // Attach the uri of the current page to all annotations to allow search.
            a += "  annotationData: {";
            a += "  'uri': path";
            a += "  }";

              // This will perform a search action rather than read when the plugin
              // loads. Will request the last 20 annotations for the current url.
              // eg. /store/endpoint/search?limit=20&uri=http://this/document/only
            a += ","
            a += "  loadFromSearch: {";
            a += "  'limit': 20,";
            a += "  'uri': path";
            a += "  }";
            a += "});";

            s.innerHTML = a;

            chapter.doc.body.appendChild(s);

            if(callback) callback();
        }

}

A: Just to close the loop on this, solution:
The file isn't an actual ePub, it is a "shell" for ingesting an ePub with ePub.js and then displaying it in a custom way...


text:
Q: How to overwrite a file correctly? I would like to know how to overwrite a file in python. When I'm using "w" in the open statement, I still get only one line in my output file.
article = open("article.txt", "w")
article.write(str(new_line))
article.close()

Can you tell me please how can I fix my problem?

A: If you are in fact looking to overwrite the file line by line, you'll have to do some additional work - since the only modes available are read ,write and append, neither of which actually do a line-by-line overwrite.
See if this is what you're looking for:
# Write some data to the file first.
with open('file.txt', 'w') as f:
    for s in ['This\n', `is a\n`, `test\n`]:
        f.write(s)

# The file now looks like this:
# file.txt
# >This
# >is a
# >test

# Now overwrite

new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
    # Get the previous contents
    lines = f.readlines()

    # Overwrite
    for i in range(len(new_lines)):
        f.write(new_lines[i])
    if len(lines) > len(new_lines):
        for i in range(len(new_lines), len(lines)):
            f.write(lines[i])

As you can see, you first need to 'save' the contents of the file in a buffer (lines), and then replace that.
The reason for that is how the file modes work.

A: "overwrite" is a strange term;  especially since you expect to see more than one line from the above code
I am guessing you mean something like "write beyond".  The word for that would be "append' and you would want 'a' instead of 'w'.


text:
Q: Не полный перевод на английский в NetBeans 8.2 Хотел поменять язык нетбинса с русского на английский. Поставил --locale en в параметрах запуска. Но перевело не всё. Видно на скриншоте. Можно ли поменять язык полностью без переустановки?

upd. Навигатор перевелся после перезапуска, но всё же, если поискать то думаю можно таких багов, можно не мало найти


text:
Q: loading multiple xml files in to datagrid I have list of xml files. (reading from one directory)
I want to show all the records present in each xml files in datagrid.
here is code for the same ( xaml file)
  <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Elements[TestResult]}"  x:Name="dataGrid" Margin="10,0,-1,0">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="TestCaseId" Binding="{Binding Path=Attribute[TestCaseId].Value}" />
                            <DataGridTextColumn Header="Outcome" Binding="{Binding Path=Attribute[Outcome].Value}"/>
                            <DataGridTextColumn Header="Duration" Binding="{Binding Path=Attribute[Duration].Value}"/>
                            <DataGridTextColumn Header="Comment" Binding="{Binding Path= Attribute[Comment].Value}"/>
                        </DataGrid.Columns>
                    </DataGrid>

TestREsult Class
class TestResult
{
        [XmlAttribute("TestCaseId")]
        public string TestCaseId { get; set; }

        [XmlAttribute("Outcome")]
        public string Outcome { get; set; }

        [XmlAttribute("Duration")]
        public string Duration { get; set; }

        [XmlAttribute("Comment")]
        public string Comment { get; set; }
    }
Here is the code for loading each file in to datagrid

however I can able to see only last file data
  foreach (string item in Files)
        {

           var peopleList = XElement.Load(item);
           this.dataGrid.DataContext = peopleList;

        }

Here is the one xml file
 <TestResults URL="https://google.com/" StartDateTime="2016-11-11T14:52:25.2499848+05:30">
<TestResult TestCaseId="Smoke_21949" Outcome="Pass" Duration="00:03:09.9335101" Comment="" />
<TestResult TestCaseId="Smoke_31234" Outcome="Pass" Duration="00:02:56.1503179" Comment="" />
</TestResults>

A: You need to create a list and add to the list,
var peopleList = new List<XElement>();
foreach (string item in Files)
    {
       peopleList.Add(XElement.Load(item));
    }
this.dataGrid.DataContext = peopleList;


text:
Q: Cannot intercept context menu item click Can anyone tell me what is wrong with this code?
When user selects a word and does a right-click he can choose 'Open Wiki-Link' -
that's working fine. But for some reason nothing happens on a click,
the code in onMessage is not been executed. Why?
exports.main = function() {

    var tabs = require('tabs');
    //var sel = require('selection');
    var cm = require('context-menu');

    var menuItem = cm.Item({
        label: 'Open Wiki-Link',
        context: cm.SelectionContext(),
        contextScript: 'self.on("click", function() {' +
            'var text = window.getSelection().toString();' +
            'self.postMessage(text);' +
        '});',
        onMessage: function(text) {
            if (text.length === 0) {
                throw ('No text selected');
            }
            tabs.open('http://de.wikipedia.org/wiki/' + text);
        }
    });
};

A: Your code seems correct and matches the examples from the documentation pretty closely. I think that the only issue is a typo: it should be contentScript, not contextScript.


text:
Q: Mobile App GetIdentityAsync no value I have this code from Azure Services Mobile App, API custom controller. The result always the same "1:1". I test with all identity providers, google, facebook, twitter, and Microsoft Account, except AD. I think the problem is the call to GetIdentityAsync. Can anyone help me? Thanks
    [HttpGet]
    public async Task<string> GetIdentityInfo()
    {
        var user = (MobileAppUser)this.User;

        string str = "";
        string Provider = "YES", UserId = "NO";
        try
        {
            if (user != null)
            {
                Provider = "1"; UserId = "1";
                var microsoftCredentials = await user.GetIdentityAsync<MicrosoftAccountCredentials>();
                if (microsoftCredentials != null && microsoftCredentials.Claims != null)
                {
                    Provider = "MICROSOFT";
                    UserId = microsoftCredentials.UserId;
                }

                Provider = "2"; UserId = "2";
                var googleCredentials = await user.GetIdentityAsync<GoogleCredentials>();
                if (googleCredentials != null && googleCredentials.Claims != null)
                {
                    Provider = "GOOGLE";
                    UserId = googleCredentials.UserId;
                }

                Provider = "3"; UserId = "3";
                var facebookCredentials = await user.GetIdentityAsync<FacebookCredentials>();
                if (facebookCredentials != null && facebookCredentials.Claims != null)
                {
                    Provider = "FACEBOOK";
                    UserId = facebookCredentials.UserId;
                }

                Provider = "4"; UserId = "4";
                var twitterCredentials = await user.GetIdentityAsync<TwitterCredentials>();
                if (twitterCredentials != null && twitterCredentials.Claims != null)
                {
                    Provider = "TWITTER";
                    UserId = twitterCredentials.UserId;
                }
            }
            else
            {
                Provider = "NONE"; UserId = "NULL";
            }
        }
        catch (Exception ex)
        {
            str = "ERROR";
        }
        finally
        {
            str = Provider + ":" + UserId;
        }

        return str;
    }

A: We receive support from Microsoft Support Engineer Adrian Fernandez Garcia, and send an example that worked OK. The unique difference was that EMA_RuntimeUrl must be created manually in mobile app in azure portal in Application Properties, and assigned to Gateway address.
Actually this value is created automatically and don't have to create it manually.
This gave us the error URIFormat NULL value.
All is working OK now.
Thanks to Microsoft for the support.


text:
Q: new intent crashes when running startActivity(intent); I am trying to call another activity from the main in an option menu. when I call the main activity from its own option menu it will correctly work but calling another intent will make an exception and the app will crash. I used try and catch and found that it will crash when it reaches this line:
startActivity(intent);

below is my main java file and the app manifest file.
public class MainActivity extends Activity {

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

    ListView listView = (ListView) findViewById(R.id.times_list);
    TimeTrackerAdapter timeTrackerAdapter = new TimeTrackerAdapter();
    listView.setAdapter(timeTrackerAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.main, menu);
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.time_list_menu, menu);
    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item){
    if (item.getItemId() == R.id.add_time_menu_item) {
        Intent intent = new Intent(this, AddTimeActivity.class);
        try {
        startActivity(intent);
        }catch(Exception e){};
        //return true;
    }
    return super.onOptionsItemSelected(item);
}

public class TimeTrackerAdapter extends BaseAdapter {

    private ArrayList<TimeRecord> times = new ArrayList<TimeRecord>();

    public TimeTrackerAdapter() {
        times.add(new TimeRecord("38:23", "Feeling good!"));
        times.add(new TimeRecord("49:01", "Tired. Needed more caffeine"));
        times.add(new TimeRecord("26:21", "I'm rocking it!"));
        times.add(new TimeRecord("29:42",
                "Lost some time on the hills, but pretty good."));
    }

    @Override
    public int getCount() {
        return times.size();
    }

    @Override
    public Object getItem(int index) {
        return times.get(index);
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public View getView(int index, View view, ViewGroup parent) {
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(parent
                    .getContext());
            view = inflater.inflate(R.layout.time_list_item, parent, false);
        }
        TimeRecord time = times.get(index);

        TextView timeTextView = (TextView) view
                .findViewById(R.id.time_view);
        timeTextView.setText(time.getTime());

        TextView notesTextView = (TextView) view
                .findViewById(R.id.notes_view);
        notesTextView.setText(time.getNotes());

        return view;
    }
}

public class TimeRecord {
    private String time;
    private String notes;

    public TimeRecord(String time, String notes) {
        this.time = time;
        this.notes = notes;
    }

    public String getTime() {
        return time;
    }

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

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }
}

public class AddTimeActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_time);
    }

    public boolean onCreateOptionsMenu(Menu m) {
        super.onCreateOptionsMenu(m);
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.time_list_menu, m);
        return true;
    }
}

}
and for the manirfest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test02"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="3"
    android:targetSdkVersion="18" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.test02.AddTimeActivity" >
    </activity>
</application>

</manifest>

Logcat:

01-15 02:20:01.164: W/dalvikvm(3018): threadid=1: thread exiting with uncaught exception (group=0x41465700)
01-15 02:20:01.414: E/AndroidRuntime(3018): FATAL EXCEPTION: main
01-15 02:20:01.414: E/AndroidRuntime(3018): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.test02/com.example.test02.MainActivity$AddTimeActivity}; have you declared this activity in your AndroidManifest.xml?
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Activity.startActivityForResult(Activity.java:3390)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Activity.startActivityForResult(Activity.java:3351)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Activity.startActivity(Activity.java:3587)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.Activity.startActivity(Activity.java:3555)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.example.test02.MainActivity.onMenuItemSelected(MainActivity.java:44)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java??:986)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.??java:735)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:87??4)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.j??ava:166)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.widget.AbsListView$1.run(AbsListView.java:3463)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.os.Handler.handleCallback(Handler.java:730)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.os.Handler.dispatchMessage(Handler.java:92)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.os.Looper.loop(Looper.java:137)
01-15 02:20:01.414: E/AndroidRuntime(3018): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-15 02:20:01.414: E/AndroidRuntime(3018): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 02:20:01.414: E/AndroidRuntime(3018): at java.lang.reflect.Method.invoke(Method.java:525)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-15 02:20:01.414: E/AndroidRuntime(3018): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

A: Add it into AndroidManifest.xml
<activity
   android:name="com.example.test02.AddTimeActivity"
   android:label="@string/app_name">
 <intent-filter>
   <action android:name="android.intent.action.AddTimeActivity" />
   <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>
</activity>

A: You're not putting the activities in the same file right?
If you really wanted to use the activity as an inner class in another activity you need to put this in your android manifest instead:
   <activity android:name="com.example.test02.MainActivity$AddTimeActivity" >

I DONT RECOMMEND THIS THOUGH. Split your inner classes into two different class files.
In the package/folder: com.example.test02 you need to separate it and make two files AddTimeActivity.class and MainActivity.class and then you don't need to change anything in your manifest.
Have you tried making sure the package names match? Can you post your imports/package name in a comment to further clarify?

A: Here you create the AddTimeActivity  class inside MainActivity class.
Note: Write multiple nested classes inside one class when not needed is not a good coding standard.
Follow some steps:
1st: Just cut AddTimeActivity from MainActivity and create a new one.
2nd: In you manifest just use it as:
<activity android:name=".AddTimeActivity" />

and check..

A: If you want to use explicit intent in your app, or if you want to start another activity using the following code:
Intent intent_name = new Intent(MainActivity.this,ActivityName.class);

startActivity(intent_name);

And if your app crashes, then you should edit your AndroidManifest.xml file and define your activity which you want to start.
For example:

*

*If the activity you want to start is named as MyActivity and if your package name is com.mycomp.myapp, then you should add the definition given below:
<activity android:name="com.mycomp.myapp.MyActivity" />


text:
Q: Can python be set to perform a function only if a specific user in logged in? I have created a sort of web-based help desk ticket system for my work. I used  flask for my python web frame work and also have a couple of SQL databases set up for user accounts as well as the help desk tickets. Right now, anyone that is logged in can delete the tickets. I would like to have it so that only a specific user account (such as mine) can delete the tickets. Is there some way to facilitate that within the function to delete the tickets? I had though if an if statement but am not sure the param to use.
Here is the function to delete the tickets and where I assume this needs to be done:
 # Delete Ticket

@app.route('/delete_ticket/<string:id>', methods=['POST'])
@is_logged_in
def delete_ticket(id):
    # Create cursor
    cur = mysql.connection.cursor()

    # Execute
    cur.execute("DELETE FROM tickets WHERE id = %s", [id])

    # Commit to DB
    mysql.connection.commit()

    # Close connection
    cur.close()

    flash('Ticket Deleted', 'success')

    return redirect(url_for('dashboard'))

A: Just as you check if a user is logged in with @is_logged_in, you can have a similar decorator check for a particular role, such as @is_admin.
It's typically much better to assign user roles and check for these roles, than hardcode a check for a particular user's identity, since individual users join and leave often, but roles are relatively stable.


text:
Q: how to access value of JSON whose key contains dot Hello I want to access value of a key in JSON which is nested JSON
here is my json
{
  "errors": {
    "products.2.name": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "name",
        "value": ""
      },
      "kind": "required",
      "path": "name",
      "value": ""
    },
    "products.2.price": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "price",
        "value": null
      },
      "kind": "required",
      "path": "price",
      "value": null
    },
    "products.2.size": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "size",
        "value": ""
      },
      "kind": "required",
      "path": "size",
      "value": ""
    },
    "products.2.stock": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "stock",
        "value": null
      },
      "kind": "required",
      "path": "stock",
      "value": null
    },
    "products.2.unit": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "unit",
        "value": ""
      },
      "kind": "required",
      "path": "unit",
      "value": ""
    },
    "products.2.category": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "category",
        "value": ""
      },
      "kind": "required",
      "path": "category",
      "value": ""
    },
    "products.2.brand": {
      "name": "ValidatorError",
      "message": "This field is required",
      "properties": {
        "message": "This field is required",
        "type": "required",
        "path": "brand",
        "value": ""
      },
      "kind": "required",
      "path": "brand",
      "value": ""
    }
  },
  "_message": "register products validation failed",
  "name": "ValidationError",
  "message": "register products validation failed: products.2.name: This field is required, products.2.price: This field is required, products.2.size: This field is required, products.2.stock: This field is required, products.2.unit: This field is required, products.2.category: This field is required, products.2.brand: This field is required"
}

I want to display error message under input field like when user leave the text field empty I have to show the error message under the input field , for that I need to access the value of message inside products.2.name. I am trying but not able to do it and like products.2.name others "products.2.__"  all other field

A: Use bracket notation.
For example:
 myobject.errors["products.2.name"].message

A: Is this json supposed to be used by a 3rd party translation module?
If not, you can opt for
t.errors['products.2.name']
with t, contening all you json object


text:
Q: Dismissing Custom MKAnnotationView Callout I am customizing the MKAnnotationView by using this
http://blog.asolutions.com/2010/09/building-custom-map-annotation-callouts-part-1/
This works for single annotation. However, I want to use this for the multiple annotations. But the problem is that I am not able to give it a behavior of the original SDK's Pop up. For instance,

*

*If you touch outside the pop up fades out.

*Click on one pop up the previous pop up goes. Or click on the same pop up the nothing happens to the popUp.
How can I fix this?

A: See Customize the MKAnnotationView callout and the usage section of https://github.com/j4n0/callout Adding another custom annotation requires you to create a subclass of CalloutView.


text:
Q: Conditionally calling only some of the custom tags on a page when a form is submitted I'm trying to make a page where a user can select a method to execute and input arguments for it.
<form action="thisPage.jsp" method="post">

Select method to test:

    <select name = 'methods' onchange='this.form.submit()'>
    <custom:inputs selectedMethod="<%=request.getParameter(\"methods\")%>" />
    <input type="submit" name="go" value="OK" />
</form>

 Output:

<custom:hello arg="<%=request.getParameter(\"generatedInput\")%>" />

Currently I have two custom tags. The first tag, inputs, dynamically creates inputs for the user to fill, depending on the method chosen. The second tag takes the values of those inputs as an argument and displays output.
The issue is that when the form is submitted, both tags run. The tag responsible for the output shouldn't be called when the user is changing the currently selected method, or at least it should be able to know that the call was caused by method selection so it can return without executing. How can I do this, without making a separate static page for each method?

A: Try JSTL conditional tag:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

...

    <c:if test="${not empty param.generatedInput}">
        <custom:hello arg="${param.generatedInput}" />
    </c:if>

Thus, the output of hello tag will be included into page only if generatedInput param is not null and not empty string.

A: In the end I resorted to AJAX, converting the tag responsible for generating the inputs into a servlet, and writing a function to request from the servlet without reloading the page:
var generateInputs = function() {
    $.get("inputGeneratorServlet", {
        method : $('#methods').val()
    }, function(responseText) {
        $("#inputsDiv").html(responseText);
    });
};

$(document).ready(generateInputs());

Instead of generating the inputs from a tag, place a div and update the DOM under it with the response from the call to the generatorServlet.

Select method to test:

<form action="thisPage.jsp" method="post">

Select method to test:

    <select name = 'methods' onchange='generateInputs()'>
// the select above is actually part of the things the servlet generates
// under the div below, but I included it for clarity

    <input type="submit" name="go" value="OK" />
</form>

This way, changing the selected method doesn't submit the form, and the form is only submitted if the user presses the OK button, signifying that he has filled out the generated inputs.


text:
Q: python 'unflow' format=flowed email When sending
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

in an email on one line as quoted above, thunderbird converts it to this:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua.

I believe, this somehow has to do with this format=flowed header:
Content-Type: text/plain; charset=ISO-8859-15; format=flowed
Content-Transfer-Encoding: 7bit

When displaying the mail in thunderbird, it looks perfectly okay. The line is displayed as one line.
However, when parsing it using pythons Message.get_payload the newlines are still displayed, completely destroying the readability.
How can I make python convert these 'flowed' lines of text to normal ones?

A: Use the formatflowed library to convert such text to 'regular' text:
from formatflowed import convertToWrapped

text = convertToWrapped(msg.get_payload(), character_set=msg.get_charset())

Do note that you need to pass in a byte string, not a unicode value; the library decodes to Unicode for you.
Obligatory disclaimer: I am the author of that library, albeit quite some time ago now.


text:
Q: Applying a Curried Argument Given the following method:
scala> def f(x: Int, y: String) = x.toString + y
f: (x: Int, y: String)String

I can curry, getting a new method.
scala> f(55, _: String)
res8: String => String = <function1>

And then I can invoke the method with the curried argument:
scala> res8("foo")
res9: String = 55foo

But why can't I do this?
scala> f(55, _: String)("foo")
<console>:12: error: type mismatch;
 found   : String("foo")
 required: Int
       f(55, _: String)("foo")
                        ^

A: Add parentheses:
(f(55, _: String))("foo")


text:
Q: How can I exclude only recursive children of specific node in css selector? PLEASE, Help with selecting the specific case.
I have one DIV with id='map-container', there are different other elements in this DIV.
MY GOAL IS: Using CSS, select COMPLETELY ALL THE ELEMENTS in my HTML, except all the children of this DIV with id='map-container' (recursively).
So, if I have for example:
<body>
<div ...>
 some other divs
</div>
<div ...>
 some other divs
</div>
<div ...>
 some other divs
</div>
[<div id="map-container">
 some other divs
</div>]
</body>

ONLY PART, THAT IS IN [ ] SHOULDN'T BE SELECTED.
Thank you so much in advance!

A: bro, you just need not to exclude this elements, you just can override style you need with "unset" value. Maybe this will help.
#map-container * {
    css-style: unset;
}


text:
Q: Fix invalid nested lists with jQuery I have been left with a rather large legacy pile of HTML. I have multiple lists that have sub lists that have not been incorporated into list item, although this renders correctly, it still causes a problem in accessibility testing. Is there a jQuery method that allow me to correct this, until I can convince the content providers to do it properly?

list

list

list

list

list

list

last failed attempt...
$("ul ul").append(function () {
                return this.closest("li");
});

wanted outcome...

list

list

list

list

list

    **
**

list

A: Select only lists which are children of lists and use jQuery's appendTo() method to move them to the previous list element:
$('ul > ul').each(function() {
  $(this).appendTo($(this).prev('li'));
});

https://api.jquery.com/appendto/
Demo


text:
Q: Exclude route from netsh interface My setup is as follows:

*

*Windows 10, Corona forced home office, I'm an external contractor at a huge company

*I'm connecting to the VPN of my company, called MyVPN, some internal IPs of our client are accessible for us via this VPN

*I set up split tunneling with Set-VpnConnection "MyVPN" -SplitTunneling 1

*All the internal IPs I need to call with the VPN start are in the same IP range 999.0.0.0/8 (example IP range, thousands of different IPs beong to this company)

*So I added all these IPs via netsh interface ipv4 add route 999.0.0.0/8  "MyVPN"

*This works, I can call internal IPs via the VPN while all other calls don't go through my VPN

*My issue is now:

*

*I can't access all internal IPs via VPN, because of missing Firewall routes (I have to request  them which takes some time and a lot of discussions... So I want to avoid this)

*But some of these internal IPs can be accessed globally without the VPN

*So I now have the issue, that I can't access these IPs through my VPN, but I could access them if I turn my VPN off. But my netsh route routes them all to the VPN, which leads to a timeout

*I was thinking to somehow exclude these IPs from the netsh route, but I don't know how. Is there a way?

*

*Like netsh interface ipv4 exclude route 999.40.60.80  "MyVPN"

*The IPs I have an issue with are scattered throughout their whole range, no pattern or similarities

That's the output of netsh interface ipv4 show route (German :) "WLAN" is German for "WiFi")

I found it! Based on user1686's answer I tried some stuff and that's the solution
netsh interface ipv4 add route 999.40.60.80/32 "WLAN" 192.168.178.1

with WLAN beeing the name of my WiFi interface and 192.168.178.1 beeing my default gateway.

A: Just add normal routes through your regular Internet gateway:
netsh interface ipv4 add route 999.40.60.80/32 "WLAN" 192.168.178.1

Copy the 'gateway' value from your current 0.0.0.0/0 route.


text:
Q: How to get callback from button placed inside TableHeader to UiViewController (In Xamarin.iOS) I am having button placed inside TableHeader on its click , I want to send callback to my UIViewController.
Can anyone please suggest how to achieve it using mainly C# or otherwise Swift. I am writing code in C#

A: What's special about TableHeader?
public Action<object, EventArgs> VCAction;

btn.TouchUpInside += (s, e) =>
        {
            //VCAction.Invoke(s, e);
        };

or
btn.TouchUpInside += Btn_TouchUpInside;

void Btn_TouchUpInside(object sender, EventArgs e)
    {
         //VCAction.Invoke(s, e);
    }

A: In your  delegate method tableView(_:viewForHeaderInSection:) where you return your header cell, add this:
  [button addTarget:self action:@selector(yourActionMethod:) forControlEvents:UIControlEventTouchUpInside];

or Swift 3 Method
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside).

A: The target: of the UIButton should be set as the UIViewController & selector: as the function responsible for handling the tap gesture.


text:
Q: Is it possible to incorporate Angular into an existing .NET MVVM Project? I have a project that doesn't have a real front-end, but rather razor views sitting on top of an application and interacting with it's view model to access data. I'd like to use Angular with my existing project to componentize some of the repeated code to save myself time and maintainability.
Is this possible without rewriting all of my views?

A: You can gradually move it over one page at a time. Make an angular app and make it handle one of the full pages. When that loads it can act as an SPA and when you need to access other pages link out like normal. Then gradually move other pages into the SPA as needed.
The users will need to load Angular multiple times which reduces the benefit of an SPA, but with caching and a proper CDN this should not be a big concern.


text:
Q: adapting screen to portrait bug objective-c Alright so i was having a little bit of a problem with the view when the device went into landscape so i decided to change the location of my textfields by code with this:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];

NSLog(@"SPIN");

if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) {

    CGRect frame = [self.a frame];
    frame.origin.x = 20;
    frame.origin.y = 57;
    [self.a setFrame:frame];

    CGRect frame2 = [self.b frame];
    frame2.origin.x = 20;
    frame2.origin.y = 132;
    [self.b setFrame:frame2];

    CGRect frame3 = [self.c frame];
    frame3.origin.x = 20;
    frame3.origin.y = 207;
    [self.c setFrame:frame3];

} else {

    CGRect frame = [self.a frame];
    frame.origin.x = 83;
    frame.origin.y = 21;
    [self.a setFrame:frame];

    CGRect frame2 = [self.b frame];
    frame2.origin.x = 204;
    frame2.origin.y = 21;
    [self.b setFrame:frame2];

    CGRect frame3 = [self.c frame];
    frame3.origin.x = 330;
    frame3.origin.y = 21;
    [self.c setFrame:frame3];

}

}

it worked just fine, everything went where it was suppost to, the problem is when click on any of the textfields to write something all of them bug out and end up looking like this:
uh.. nevermind that apparently i need at least 10 reputation before i can post an image, so here's a description of what the image showed instead:
image shows 3 uisegmented controls and 3 textfields crammed stacked on top of each other on the very top of the screen
So i'm more of a hobbyist than a pro at this so i apologize if this is a stupid question, but what am i doing wrong here? and additionaly is there a better way of going about adapting your view?

A: Try using auto layout or may be auto resizing masks on different views which you are using. There is a property called as autoresizingmask in uiview.
You can check this for reference:
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html


text:
Q: Add number of characters and extend time of Rfc6238AuthenticationService I am using Rfc6238AuthenticationService at https://github.com/aspnet/Identity/blob/85012bd0ac83548f7eab31f0585dae3836935d9d/src/Microsoft.AspNet.Identity/Rfc6238AuthenticationService.cs
which uses rfc6238 https://www.rfc-editor.org/rfc/rfc6238
internal static class Rfc6238AuthenticationService
{
    private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    private static readonly TimeSpan _timestep = TimeSpan.FromMinutes(3);
    private static readonly Encoding _encoding = new UTF8Encoding(false, true);

    private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier)
    {
        // # of 0's = length of pin
        const int Mod = 1000000;

        // See https://www.rfc-editor.org/rfc/rfc4226
        // We can add an optional modifier
        var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
        var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier));

        // Generate DT string
        var offset = hash[hash.Length - 1] & 0xf;
        Debug.Assert(offset + 4 < hash.Length);
        var binaryCode = (hash[offset] & 0x7f) << 24
                         | (hash[offset + 1] & 0xff) << 16
                         | (hash[offset + 2] & 0xff) << 8
                         | (hash[offset + 3] & 0xff);

        return binaryCode % Mod;
    }

    private static byte[] ApplyModifier(byte[] input, string modifier)
    {
        if (String.IsNullOrEmpty(modifier))
        {
            return input;
        }

        var modifierBytes = _encoding.GetBytes(modifier);
        var combined = new byte[checked(input.Length + modifierBytes.Length)];
        Buffer.BlockCopy(input, 0, combined, 0, input.Length);
        Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length);
        return combined;
    }

    // More info: https://www.rfc-editor.org/rfc/rfc6238#section-4
    private static ulong GetCurrentTimeStepNumber()
    {
        var delta = DateTime.UtcNow - _unixEpoch;
        return (ulong)(delta.Ticks / _timestep.Ticks);
    }

    public static int GenerateCode(byte[] securityToken, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            return ComputeTotp(hashAlgorithm, currentTimeStep, modifier);
        }
    }

    public static bool ValidateCode(byte[] securityToken, int code, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            for (var i = -2; i <= 2; i++)
            {
                var computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep + i), modifier);
                if (computedTotp == code)
                {
                    return true;
                }
            }
        }

        // No match
        return false;
    }
}

Is it possible to add character limit in this class and make it configurable(like 6 chars)? Also, is it possible to extend the time of token and make it configurable(like 120 seconds)?

A: Here is the place, where OTP is truncated to the defined length:
return binaryCode % Mod;

So, you just need to change the value of the Mod to 1000000 to get 6-digits code.
A variable, responsible for time of token is timestepNumber. So change the logic in its calculation if needed.


text:
Q: how to configure nginx for different paths I would like to configure nginx for different locations on / and I have the following config.
server {
    listen 80;
    server_name bla.com;
    location = / {   // on exact route match such as 'bla.com'
        root /usr/share/nginx/html/folder; // it has index.html
    }
    location / { // rest all url such as bla.com/* are captured here eg. bla.com/temp/12
        root /usr/share/nginx/html/dist; // different folder
    }
}

How can I do this?
I also tried the below config with no luck -
server {
    listen 80;
    server_name bla.com;
    root /usr/share/nginx/html;
    location = / {
        try_files $uri /folder/index.html; // it has index.html
    }
    location / { // rest all url such as bla.com/* are captured here eg. bla.com/temp/12
        try_files $uri /dist/index.html; // different folder
    }
}

A: You can achieve this by creating something like this:
server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /var/www/website1/public_html;
    }

    location /temp {
        root /var/www/website2/public_html;
    }
}

You can also do this with individual files like this:
location /robots.txt {
    alias /var/www/website/public_html/robots.txt;
}


text:
Q: Failed Resolution of R$Drawable when using a bound Java Library I am binding the java library Material CalendarView. With a set of 12 transforms in Metadata.xml I could bind the library with 0 errors and 15 warnings. I have added Support Library v4 Component ver 23.1.1 in the binding project as the jar file had a dependency on that. Also I have ensured that all the Resource assets are included in the jar file.
When I use this library in an Android Sample like below,
var materialCalendar= new MaterialCalendarView(this);

this exception gets thrown
Failed resolution of: Lcom/prolificinteractive/materialcalendarview/R$drawable;

Java.Lang.NoClassDefFoundError: Failed resolution of:  Lcom/prolificinteractive/materialcalendarview/R$drawable; ---> Java.Lang.ClassNotFoundException: Didn't find class "com.prolificinteractive.materialcalendarview.R$drawable" on path: DexPathList[[zip file "/data/app/com.fingent.materialcalendarsample-1/base.apk"],nativeLibraryDirectories=[/data/app/com.fingent.materialcalendarsample-1/lib/x86, /vendor/lib, /system/lib]]
at --- End of managed exception stack trace ---
at java.lang.ClassNotFoundException: Didn't find class "com.prolificinteractive.materialcalendarview.R$drawable" on path: DexPathList[[zip file "/data/app/com.fingent.materialcalendarsample-1/base.apk"],nativeLibraryDirectories=[/data/app/com.fingent.materialcalendarsample-1/lib/x86, /vendor/lib, /system/lib]]
at at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.setupChildren(MaterialCalendarView.java:358)
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.<init>(MaterialCalendarView.java:237)
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.<init>(MaterialCalendarView.java:216)
at at md56fd5622393123d59c6c51d78708f2ed2.MainActivity.n_onCreate(Native Method)
at at md56fd5622393123d59c6c51d78708f2ed2.MainActivity.onCreate(MainActivity.java:28)
at at android.app.Activity.performCreate(Activity.java:5990)
at at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at at android.app.ActivityThread.access$800(ActivityThread.java:151)
at at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at at android.os.Handler.dispatchMessage(Handler.java:102)
at at android.os.Looper.loop(Looper.java:135)
at at android.app.ActivityThread.main(ActivityThread.java:5254)
at at java.lang.reflect.Method.invoke(Native Method)
at at java.lang.reflect.Method.invoke(Method.java:372)
at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
at Suppressed: java.lang.ClassNotFoundException: com.prolificinteractive.materialcalendarview.R$drawable
at at java.lang.Class.classForName(Native Method)
at at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
at ... 19 more
at Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3053/a94a03b5/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (IntPtr jobject, IntPtr jclass, IntPtr jmethod, Android.Runtime.JValue* parms) [0x00084] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:1029
at Android.Runtime.JNIEnv.FinishCreateInstance (IntPtr instance, IntPtr jclass, IntPtr constructorId, Android.Runtime.JValue* constructorParameters) [0x0000b] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.cs:306
at MaterialCalendarLibrary.MaterialCalendarView..ctor (Android.Content.Context p0) [0x000c5] in /Users/fingent/Projects/MaterialCalendarLibrary/MaterialCalendarLibrary/obj/Release/generated/src/MaterialCalendarLibrary.MaterialCalendarView.cs:505
at MaterialCalendarSample.MainActivity.OnCreate (Android.OS.Bundle savedInstanceState) [0x00009] in /Users/fingent/Documents/sreeraj/workspace/Xamarin.MaterialCalendarView/MaterialCalendarSample/MainActivity.cs:17
at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_savedInstanceState) [0x00011] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Android.App.Activity.cs:2475
 at at (wrapper dynamic-method) System.Object:0b8c341c-2f19-42d5-83e9-b3a815827e69 (intptr,intptr,intptr)
at --- End of managed exception stack trace ---
at java.lang.NoClassDefFoundError: Failed resolution of: Lcom/prolificinteractive/materialcalendarview/R$drawable;
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.setupChildren(MaterialCalendarView.java:358)
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.<init>(MaterialCalendarView.java:237)
at at com.prolificinteractive.materialcalendarview.MaterialCalendarView.<init>(MaterialCalendarView.java:216)
at at md56fd5622393123d59c6c51d78708f2ed2.MainActivity.n_onCreate(Native Method)
at at md56fd5622393123d59c6c51d78708f2ed2.MainActivity.onCreate(MainActivity.java:28)
at at android.app.Activity.performCreate(Activity.java:5990)
at at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at at android.app.ActivityThread.access$800(ActivityThread.java:151)
at at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at at android.os.Handler.dispatchMessage(Handler.java:102)
at at android.os.Looper.loop(Looper.java:135)
at at android.app.ActivityThread.main(ActivityThread.java:5254)
at at java.lang.reflect.Method.invoke(Native Method)
at at java.lang.reflect.Method.invoke(Method.java:372)
at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
at Caused by: java.lang.ClassNotFoundException: Didn't find class "com.prolificinteractive.materialcalendarview.R$drawable" on path: DexPathList[[zip file "/data/app/com.fingent.materialcalendarsample-1/base.apk"],nativeLibraryDirectories=[/data/app/com.fingent.materialcalendarsample-1/lib/x86, /vendor/lib, /system/lib]]
at at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at ... 18 more
at Suppressed: java.lang.ClassNotFoundException: com.prolificinteractive.materialcalendarview.R$drawable
at at java.lang.Class.classForName(Native Method)
at at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
at ... 19 more
at Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

Here is the link to the project in Github Xamarin Material CalendarView

A: It's about missing Resources that should be attached in Material CalendarView, you need an AAR file.
Just go Maven and get latest AAR file that published by Author: http://mvnrepository.com/artifact/com.prolificinteractive/material-calendarview/1.2.0
Remove the material-calendarview.jar and drag new file material-calendarview-1.2.0.aar on your binding project, done!

A: A Drawable is a graphic resource and the Java exception is on the following line (from the lib your binding):
buttonPast.setImageResource(R.drawable.mcv_action_previous);

So you are missing mcv_action_previous which a PNG-based arrow located in the res/drawable-xxxhdpi/mcv_action_previous.png within the project that you are binding.
Are all the resources included? Any of your binding transformations or binding warning about resources?


text:
Q: how to add alertProductNames to an incident in Azure Sentinel I'm using an API to create an incident in Azure Sentinel and it's working successfully but I want to add the alertproductnames with the API request to let it visible in azure sentinel.
this is the API URL:  PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/incidents/{incidentId}?api-version=2022-12-01-preview

as you can see in image 3 the alertproductnames is empty, and I tried to add it to the request body but it didn't work.

A: It is not possible to create alerts directly by adding them in the additonal properties of the Incident in Azure Sentinel, As Alerts needs to be created separately or gets triggered by an Incident.
Also, In the MS document:-Incidents - Create Or Update - REST API (Azure Sentinel) | Microsoft Learn > The request body does not contain any property with alertProductNames.
I tried to create an Incident with alertProductName but it was not created, Refer below:-
URI:-
https://management.azure.com/subscriptions/xxxxxxx-xxxx-xxxx-xx-e2b6e97cb2a7/resourceGroups/sentinelrg/providers/Microsoft.OperationalInsights/workspaces/LoganalyticsWS/providers/Microsoft.SecurityInsights/incidents/id?api-version=2022-12-01-preview

Body parameter:-
{

"properties": {

"title": "silicon Incident",

"description": "This is an silicon incident created using the Azure Sentinel API",

"severity": "Medium",

"status": "New",

"additionalData": {

"alertsCount": 1,

"bookmarksCount": 2,

"commentsCount": 2,

"alertProductNames": ["Azure Security Center"],

"tactics": [],

"techniques": ["T1189 - Drive-by-Compromise"]

}

}

}

Output:-

To create Alerts with ProductName there's a different API refer below:-
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/alertRules/{ruleId}?api-version=2022-12-01-preview

Request Body:-

{

"kind": "Scheduled",

"properties": {

"displayName": "My scheduled rule",

"description": "An example for a scheduled rule",

"severity": "High",

"enabled": true,

"tactics": [

"Persistence",

"LateralMovement"

],

"techniques": [

"T1037",

"T1021"

],

"query": "Heartbeat",

"queryFrequency": "PT1H",

"queryPeriod": "P2DT1H30M",

"triggerOperator": "GreaterThan",

"triggerThreshold": 0,

"suppressionDuration": "PT1H",

"suppressionEnabled": false,

"eventGroupingSettings": {

"aggregationKind": "AlertPerResult"

},

"customDetails": {

"OperatingSystemName": "OSName",

"OperatingSystemType": "OSType"

}

}

}

Output:-

References:-
Alert Rules - Create Or Update - REST API (Azure Sentinel) | Microsoft Learn
List Alert by Incidents:-
Incidents - List Alerts - REST API (Azure Sentinel) | Microsoft Learn


text:
Q: Linq failing to connect... or is it? I have a web-application which is reciving the following while trying to connect to a database hosted on another server.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Now, there problem here is that the connection strings, and the server paths area all perfect.

*

*The site run correctly when run via cassini, on my local machine. (Connections strings are correct.)

*Other sites hosted on the same server are able to access the databse. (Server paths ara all active.)

*While the error says it's been unable to connect, Activity Monitor is aware of the query, and the Server Logs show no error. (Just odd.)

Google & Bing have massively failed with this, so I guess it's time to hit the Stack!

A: Open the Sql Server Conifguration Manager, expand Sql Server 2005 Network Configuration, click Protocols for <Yourserverinstance>, then check TCP/IP is enabled.


text:
Q: JMeter unable to fetch redirect url my URL(https://www.test.com) has parameters
response_type,client_id,redirect_uri:https://wwwx.dummy.com, scope
When I paste my URL with params in chrome, I get the redirect URL as
https://wwwx.dummy.com?code=XXXXXXXXXXXXXXXXX
But  in Jmeter I am unable to get this code parameter

*

*Enabled debug post processor

*capturing regular expression from URL (.*)

*trying to post the redirect url in next http request

I dont see redirect url in any of the sub samples.
kindly help

A: Instead of using a 3rd-party website you can use a local address like http://localhost:8081/foo/bar as the redirect_uri so the request will go to your local JMeter instance instead of the remote website.
You can extract the code from the request's Location header using Regular Expression Extractor
If you don't want the sampler to fail you can use i.e. HTTP Mirror Server in order to "catch" the request.


text:
Q: Change Typeface of Tab titles - ActionBarSherlock Is it possible to change the typeface of the ActionBarSherlock Tab titles programmatically to a custom font?
I've searched around for a method but only come across where the typeface used is a default.

A: I imagine it would be similar to what I have here http://thehax.org/code-cuts/setting-a-custom-font-throughout-your-entire-app/
I extend textview and set the typeface there, but You should be able to get the textview object and do it there.
String otfName = "FrutigerLTStd-Cn.otf";
               Typeface font = Typeface.createFromAsset(c.getAssets(), otfName);
               this.setTypeface(font);


text:
Q: Rotating a hitbox and detect that rotation in a calculation I am making a 3D Java game but i have got problems when rotating a hitbox. I, upon this point, only used a method which detects if a Vector3f is in a box.
But in my game I want to rotate houses, for example, so that method won't work. I could use circulair hitboxes but that wouldn't work for every instance of objects.
So far i have used this simple calculation to detect if a location is in a hitbox.
    public boolean isinbox(Vector3f pos) {
    Vector3f entPos = ent.getPosition();

    float x1 = entPos.x + xOffset;
    float z1 = entPos.z + zOffset;
    float y1 = entPos.y + yOffset;

    float x2 = entPos.x - xOffset;
    float z2 = entPos.z - zOffset;
    float y2 = entPos.y;

    return pos.x < x1 && pos.x > x2 && pos.z < z1 && pos.z > z2 && pos.y > y2 && pos.y < y1;
}

This works in many ways, but I can't figure out how to rotate them and still be able to detect it. The xOffset is the ofset if side a to the center and negative side b to the center.
How would I be able to rotate a hitbox and detect if an Vector is in it?

A: There are a couple of ways of getting around this issue and one (or more) ways of solving this issue:
Solving It
SAT Collision
SAT Stands for Separating Axis Theorem.
TutsPlus and MetaSoftware are great websites to learn how it works and how to implement it.

The Separating Axis Theorem (SAT for short) essentially states if you are able to draw a line to separate two polygons, then they do not collide. It's that simple. (gamedevelopment.tutsplus.com)

Here is the basic idea:

It can also be used for more complex shapes:

Getting Around It
AABB Collision
This is done by assuming that collisions will only ever happen on the X/Y axis (never on an axis defined by an arbitrary line).
Here is an example of what this looks like:

Therefore, you must define this axis-aligned hitbox by using the minimum X-and-Y values and the maximum X-and-Y values of the original box.
Circle Collision
This is a much simpler collision check which only detects when two objects are within a certain distance of each other.
Here is an example of what this looks like:

The way this works is that if the distance between the two objects is less than the sum of each circle's radius, then the objects are colliding.
Using an External Library

*

*Bullet Physics

*Box2D


text:
Q: Shred XML For Each Row in SQL Table I have a table that contains two columns, and ID, and XML data. I'd like to shred the XML for each ID. I'm pulling out a single value within the XML and all the XML is structured the same I'm just not sure how to loop through the table and apply XML query to each row.
The query I need to apply is as follows:
Select top 1
Element1 = XV.value('(.)[1]','nvarchar(32)')
from @xml.nodes('Parameters/Parameter/Value') as x(XV)

So the end results would have two columns, ID and shredded value from XML.

A: Without any knowledge about your actual XML and how you want to shred it to get some values it is impossible to answer in completness, but this shoudl point you in the right direction:
Returns the ID and the XML as is
 SELECT ID
       ,TheXmlColumn
 FROM YourTable

This returns the ID and a value out of your XML
 SELECT ID
       ,TheXmlColumn.value('Some XPaht','SomeType') AS SomeValueFromXML
 FROM YourTable

And if there are more embedded rows it would be something like this
 SELECT ID
       ,nd.value('Some XPaht','SomeType') AS SomeValueFromXMLRow
 FROM YourTable
 OUTER APPLY TheXmlColumn.nodes('SomeXPath') AS A(nd)

My magic glass bulb tells me, that you might need something like this:
 SELECT ID
       ,TheXmlColumn.value('(Parameters/Parameter/Value)[1]','nvarchar(max)') AS SomeValueFromXML
 FROM YourTable


text:
Q: install.packages() is executed with no error, but library() cannot find/get the called package. Why? If install.packages is executed with no error, then why library(...) cannot find/get the called package?
install.packages("D:/R/PAKETLER/circumplex-master.zip", repos = NULL, type = "win.binary")
library(`circumplex-master`)
# Error in library(`circumplex-master`) : there is no package called 'circumplex-master'
library("circumplex-master")
# Error in library("circumplex-master") : there is no package called 'circumplex-master'
library("circumplex")
# Error in library("circumplex") : there is no package called 'circumplex'
library(circumplex)
# Error in library(circumplex) : there is no package called 'circumplex'


text:
Q: Special characters in bib entries using biber/biblatex I'm having problems to get URLs with special characters in biber/biblatex to work
\usepackage[T1]{fontenc}
\usepackage[swedish]{babel}

\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[natbib=true,backend=biber]{biblatex}

This bib entry for example. biber cannot run with the URL, but if I take it away it works fine. I have other URLs set up in the same way and the work just fine, because there aren't any special characters in them.
@ONLINE{biodieselboard,
howpublished = "European Biodiesel Board",
title = " Statistics",
note = "Hämtad: 30/05/2012",
year = "2012"
url = "http://www.ebb-eu.org/stats.php#",
}

Does anyone know a solution to this?

A: If the bib entry is correctly input, there's no problem in compiling it:
@ONLINE{biodieselboard,
howpublished = "European Biodiesel Board",
title = " Statistics",
note = "Hämtad: 30/05/2012",
year = "2012",
url = "http://www.ebb-eu.org/stats.php#",
}

Notice the comma that was missing after the year field.


text:
Q: Placing The Section Header Above the Cell Contents of UITableView **You may want to go 'Edit 2' section directly (at below), there you can find the last and current situation.
I can't explain the problem just with the words properly, so I'll try to explain with pictures. Here is the situation I have:

As you can see in the picture, the allignment of the header titles doesn't match with the contents of the TableViewCell. I want section header to be at the top of the values. Like, "Alış" string to be at the beginning of the values. To be specific, I want something like that:
 Alış             Satış

 654.000          666.000

 313.757          321.921

 157.370          160.960

 ...              ...

And so on.
I was referring to this link to make section headers. Of course, it is a simple doc, so I moved myself using "auto layout" and "update frames" and "add the missing constraints" from the Resolve Auto Layout Issues segment that storyboard has. Well, clearly I failed. Here is the tableView that refers to this problem:

So here, the second cell is used for the header, as suggested in the link I gave.
I'm not familiar with using constraint, that is making the issue more complicated to me.
Any help / suggestion would be appreciated.
Waiting for your assistance.
EDIT:
Here is the code I have to write header.

EDIT 2: Now, I'm really close and just need a little assistance
I was trying 'til the morning on this, I know it is a bit much time. Anyway. So eventually I figured it out and tried in iPhone 4s to 6 plus, they give the correct result, with a minor mistake. The answer was simple: playing with the autolayout to understand with reference. I recommend Apple's doc and Ray's doc.
Back to last problem, as you can see in the first picture, my last row of tableVieWCell's alignment is right which I want it to be left. So the last situation is at below:

**I worht mentioning that I know that the alignment may not be what is my topic, but I didn't want to ask another question. If it is really unappropite, you can warn me, so I can ask in another topic.

A: Please make seperate xib file with class file .h & .m and it's superview is UIView for section header. And design the same view which you have design for table cell. You can use autolayout also in xib file. This will work :-)


text:
Q: Adding link to an image in sapui5 Showing the error when I am trying to add a link to an image: Cannot add direct child without default aggregation defined for control sap.m.Link in Sapui5
<Link href="http://www.sap.com">
     <Image src="image.png" />
</Link>

A: We can add a link to an image by using the press event present in the image control.
xml view
<Image src="image.png" press="click" />

controller
click : function(){
     var link= "www.sap.com"
     //open in same window
     window.location.href = link;
     //open in new window
     window.open(link);
     //Or we can use sap URLHelper control to redirect into a new page
    sap.m.URLHelper.redirect(link,true);
}


text:
Q: My Ajax Call Is Not working when i type in textbox

<form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>

-------------------------------------

<?php

$a[]="Anna";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
  {
  $hint="";
  for($i=0; $i<count($a); $i++)
    {
    if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))
      {
      if ($hint=="")
        {
        $hint=$a[$i];
        }
      else
        {
        $hint=$hint." , ".$a[$i];
        }
      }
    }
  }

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
echo $response;
?>

A: Try changing this line
if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))

to
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

A: if (xmlhttp == 4 && xmlhttp.status == 200) {
Should BE
if (xmlhttp.readyState==4 && xmlhttp.status==200)

---------------------------

if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))
Should BE
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

A: I think that the error will occur  on
strtolower(substr($a[$a],0,strlen($q))))

Here what is $a[$a] ..? Are like to executing for loop Then
  for($i=0; $i<count($a); $i++)
    {
     if (strtolower($q)==strtolower(substr($a[$a],0,strlen($q))))

please change like this
  for($i=0; $i<count($a); $i++)
    {
     if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))

$a replace with $i then only the $a[] is working

A: <form>
    FirstN<input type="text" onkeyup="return showHint(this.value);" size="20" />
</form>


text:
Q: Get list of lists without recursion I'm trying to get all lists with length 4 from alphabet [0..9] with unique elements.
allNumbers = [a | let list = [0..9], x1 <- list, x2 <- list, x3 <- list, x4 <- list, let a = [x1,x2,x3,x4], nub a == a]

How can I get some simplest and nicest version of that? What if I need all such lists with length 10 (I don't want to copypasting x# <- list 10 times)? Non-recursive answer is encouraged.

A: use sequence:
Prelude> let a = [0..9]
Prelude> sequence $ replicate 4 a

This relies on the monad instance for list.
Then you can add in the nub part with filter:
filter (\x -> nub x == x) $ sequence $ replicate 4 [0 .. 9]

Update:  as pointed out in a comment, you could also use replicateM (which I was not aware of):
Prelude> :m + Control.Monad
Prelude> filter (\x -> nub x == x) $ replicateM 4 [0 .. 9]


text:
Q: User authentication with Angular & PHP I am quite inexperienced when it comes to the topic of server-side user authentication.
I want to use as few PHP code as possible to achieve the following:
A user can log in to my app. If he does so, i will store all of that users information, including the status of being authenticated to an Angular service.
As a user navigates through my app, i need to check whether or not he is logged in. If he ain't, i need to redirect him immediately.
The question
Would it be enough to set up two session variables when the user has been logged in successfully and then doing something like this on every route change, updating my service and handle the result client-side?
public function getLogStatus(){
    return
      $_SESSION["isLoggedIn"] == "true" &&
      $_SESSION['useradr'] == $_SERVER['REMOTE_ADDR'] ?
        true : false;
}

A: Yes it IS enough.
But I suggest this :
public function checkAuth(){
   if(!$_SESSION["isLoggedIn"] || $_SESSION['useradr'] !=$_SERVER['REMOTE_ADDR'])
   header('location:"thePage.php"');
}

and call it in the first line of every method that you dont want to non-authed visitors can  gain .
public function method(){

$this->checkAuth();
...
}


text:
Q: Struggling with Proof Writing. Simple question for demostration. I am practicing writing proofs over regular expressions. Here is the question:
Show that $(r\cup \varepsilon)^*= r^*$, where $r$ is a string.
Intuitively, the left hand side is the concatenation of zero or more concatenation of $r$ or $\varepsilon$, but for concatenation: $r\varepsilon = r$. Which is essentially the same with the right hand side. Now, I am trying to formalized it.
Proof: Using double inclusion to show equality. First, we do  one direction: show that $(r \cup \varepsilon) \subseteq r^*$, let $w \in (r\cup \varepsilon)^*$, thus, $w$ is the concatenation of either $r$ or $\varepsilon$ for $n$ times, where $n \in \mathbb{Z}, n\geq 0$.
Now, I have a hard time to say that $w$ is the same with $r$, using subsets notations.  I'd appreciate if you can hint me so that I can formalize the word .

A: Using subset notation is not essential.  If you can give a clear proof using mainly words, that is often better than a highly technical algebraic proof.  To prove that ${\rm LHS}\subseteq{\rm RHS}$ I would suggest something like this.
Let $w$ be a word which matches $(r\cup \varepsilon)^*$.  Then by definition $w$ can be written
$$w=w_1w_2\cdots w_n\ ,$$
where $n\ge0$ and every $w_k$ is either $r$ or $\varepsilon$.  Suppose that $m$ of these words $w_k$ are $r$ (and the rest are $\varepsilon$).  Then
$$w=r^m$$
which matches $r^*$.  Therefore $w$ matches the ${\rm RHS}$, and this shows that ${\rm LHS}\subseteq{\rm RHS}$.
Comment.  I am more used to working with regular languages than regular expressions, though there is no great difference.  You might need to change some of my notation to fit the way you do it.


text:
Q: Milliseconds delay after unlocking phone causes unresponsiveness Does anyone realise a delay after unlocking the iPhone screen on iOS7 ? You cannot swipe left or right until the animation finishes at 100%, rendering the phone unresponsive till then.
This is kind of annoying, albeit a small issue, but it affects the whole snappy experience I'm having with iOS7.
Any fix for this ? I expected it to be fixed by iOS 7.0.3 update, but it isn't.

A: It looks like you have to just wait for the animation to finish.
By turning on 'Reduce Motion' you get another animation, which looks like it is a bit faster. But this function changes the whole feeling from iOS 7. You can find it at General - Accessibility -  Reduce Motion.


text:
Q: How to apply dynamic data in React Native share For my recipe app, I want to enable users to share recipes with their friends. For this, I'm using the official React Native share function. I'm trying to pass props to the message and title, without any success. Here's the code I'm using for sharing.
 onShare = async () => {
// const result = await
const { caption } = this.props.section;
Share.share(
  {
    message: caption,
    title: "{section.caption}"
  },
  {
    excludedActivityTypes: [
      // 'com.apple.UIKit.activity.PostToWeibo',
      // 'com.apple.UIKit.activity.Print',
      // 'com.apple.UIKit.activity.CopyToPasteboard',
      // 'com.apple.UIKit.activity.AssignToContact',
      // 'com.apple.UIKit.activity.SaveToCameraRoll',
      // 'com.apple.UIKit.activity.AddToReadingList',
      // 'com.apple.UIKit.activity.PostToFlickr',
      // 'com.apple.UIKit.activity.PostToVimeo',
      // 'com.apple.UIKit.activity.PostToTencentWeibo',
      "com.apple.UIKit.activity.AirDrop"
      // 'com.apple.UIKit.activity.OpenInIBooks',
      // 'com.apple.UIKit.activity.MarkupAsPDF',
      // 'com.apple.reminders.RemindersEditorExtension',
      // 'com.apple.mobilenotes.SharingExtension',
      // 'com.apple.mobileslideshow.StreamShareService',
      // 'com.linkedin.LinkedIn.ShareExtension',
      // 'pinterest.ShareExtension',
      // 'com.google.GooglePlus.ShareExtension',
      // 'com.tumblr.tumblr.Share-With-Tumblr',
      // 'net.whatsapp.WhatsApp.ShareExtension', //WhatsApp
    ]
  }
);

};
The way data is loaded into this page is via {section.XXX}. Example:
 <Caption style={styles.Caption}>{section.caption}</Caption>

This is how I trigger the 'onShare' func.
<Button title="Share recipe" onPress={this.onShare} />

I hope someone can help me with this challenge. Thanks in advance!!

A: I see two problems with your code, the first one is string interpolation which is unnecessary and wrongly executed and the second is that you're referencing an inexistant prop. You're saying in a comment that this.props.section is undefined, that's because the data seems to be passed via the special children prop.
onShare = () => {
    const { children } = this.props;

    if (typeof children !== "string") {
        return;
    }

    Share.share({
        message: children,
        title: children
    });
}