text:
Q: Android Horizontal determinate ProgressBar is not running I am trying to change from indeterminate to determinate horizontal progress bar but determinte progress bar doesn't work where indeterminate works so fine.
Determinate one appears but no motion.
please help me .
 <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/check"
android:layout_width="match_parent"
android:layout_height="match_parent">
   <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >
     <ProgressBar
     android:id="@+id/my_progressBar"
     style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:indeterminate="false"
    android:max="100"
    android:progress="10"/>
    </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>

And i added the following in MainActivity.java:
ProgressBar progressBar = (ProgressBar) findViewById(R.id.my_progressBar);
progressBar.setProgress(20);

A: I think the progressBar dont increse because you dont increment de progress. If you set setProgress to 20, the bar will remain at 20.
You have to progressively increase the setProgress if you want to see motion.
I hope its helps.

A:  private int progressStatus = 10;
 new Thread(new Runnable() {
           public void run() {

                   while (progressStatus < 100) {

                           progressStatus += 5;

                           // Update the progress bar and display the
                           //current value in the text view
                           handler.post(new Runnable() {
                               public void run() {
                                   progressBar.setProgress(progressStatus);
                        textView.setText(progressStatus+"/"+progressBar.getMax());

                               }
                           });
                           try {
                               // Sleep for 300 milliseconds.
                               //Just to display the progress slowly
                               Thread.sleep(300);
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }

               }

           }
       }).start();


text:
Q: Complex integral over closed path with points outside path (Cauchy Integral) I am just looking for solution verification of the following integral.
$$\int_{|z-1|=1}\frac{dz}{z^2-1}$$
The denominator can be factored into $(z+1)(z-1)$, but $z_0=-1$ is not inside the path $|z-1|=1$, so we can rewrite as
$$\int_{|z-1|=1}\frac{(z+1)^{-1}dz}{z-1}$$
By Cauchy's Integral Formula, then we know that
$$\int_{|z-1|=1}\frac{(z+1)^{-1}dz}{z-1}=\frac{2\pi i}{0!}f^{(0)}(1)=\frac{2\pi i}{1+1}=\pi i$$
Is this correct?

A: Yes, your solution is perfectly fine.  Another way to approach a problem such as this is to write
$$\begin{align}
\oint_{|z-1|=1}\frac{1}{z^2-1}\,dz&=\oint_{|z-1|=1}\left(\frac{1/2}{z-1}-\frac{1/2}{z+1}\right)\,dz\\\\
&=\frac12\oint_{|z-1|=1}\frac{1}{z-1}\,dz-\frac12\oint_{|z-1|=1}\frac{1}{z+1}\,dz\\\\
&=\pi i +0\\\\
&=\pi i
\end{align}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python set dictionary nested key with dot delineated string If I have a dictionary that is nested, and I pass in a string like "key1.key2.key3" which would translate to:
myDict["key1"]["key2"]["key3"]

What would be an elegant way to be able to have a method where I could pass on that string and it would translate to that key assignment? Something like
myDict.set_nested('key1.key2.key3', someValue)

A: Using only builtin stuff:
def set(my_dict, key_string, value):
    """Given `foo`, 'key1.key2.key3', 'something', set foo['key1']['key2']['key3'] = 'something'"""

    # Start off pointing at the original dictionary that was passed in.
    here = my_dict

    # Turn the string of key names into a list of strings.
    keys = key_string.split(".")

    # For every key *before* the last one, we concentrate on navigating through the dictionary.
    for key in keys[:-1]:
        # Try to find here[key]. If it doesn't exist, create it with an empty dictionary. Then,
        # update our `here` pointer to refer to the thing we just found (or created).
        here = here.setdefault(key, {})

    # Finally, set the final key to the given value
    here[keys[-1]] = value

myDict = {}
set(myDict, "key1.key2.key3", "some_value")
assert myDict == {"key1": {"key2": {"key3": "some_value"}}}

This traverses myDict one key at a time, ensuring that each sub-key refers to a nested dictionary.
You could also solve this recursively, but then you risk RecursionError exceptions without any real benefit.

A: There are a number of existing modules that will already do this, or something very much like it.  For example, the jmespath module will resolve jmespath expressions, so given:
>>> mydict={'key1': {'key2': {'key3': 'value'}}}

You can run:
>>> import jmespath
>>> jmespath.search('key1.key2.key3', mydict)
'value'

The jsonpointer module does something similar, although it likes / for a separator instead of ..
Given the number of pre-existing modules I would avoid trying to write your own code to do this.

A: EDIT: OP's clarification makes it clear that this answer isn't what he's looking for. I'm leaving it up here for people who find it by title.

I implemented a class that did this a while back... it should serve your purposes.
I achieved this by overriding the default getattr/setattr functions for an object.
Check it out! AndroxxTraxxon/cfgutils
This lets you do some code like the following...
from cfgutils import obj

a = obj({
    "b": 123,
    "c": "apple",
    "d": {
        "e": "nested dictionary value"
    }
})

print(a.d.e)
>>> nested dictionary value


text:
Q: SQLite DB structure with multiple elements in column I want to create a DB to store some information for an app/game that uses geo coordinates. I'm using java with SQLite for that purpose.
I need a table which stores information like the following:
USER_TABLE:
Username,
Password,
Points,
Areas (consisting of multiple points per area),
Achievements (can consist of multiple entries, for the ones unlocked)
Areas and achievements should also have unique ID's so I can check whether a certain achievement is unlocked by a player, or to see if a certain area(consisting of multiples points) belongs to a user, so they should look like:
AREAS_TABLE:
Area_ID,
Points (which consists of all latitude/longitude or X/Y points of that area),
(MAYBE) belonging User(attribute to relate to the user the area belongs to),
ACHIEVEMENTS_TABLE:
Achievement_ID,
Achievement_Name,
My question is now: How can I store the information of multiple points per single Area? Do I have to store them all in two Strings for X and Y so that the entries look like this:
X = x1, x2, x3, x4, ..,
Y = y1, y2, y3, y4, ...
or is it possible to somehow elegantly store them in a single area-construct  like a table:
Single_area:
Lantitude/X,
Longitude/Y,
Heres a pictures of the relations I need:
The circled attributes are attributes that multiple entries can exist of, like MULTIPLE users: one user has a name, a password, a score and MULTIPLE areas. Areas consist of MULTIPLE points..


text:
Q: R - Parameterized unzipping of file using system command I was disappointed by the slow speed of unzipping a large file in R using:
unzip("C:/My File.zip", exdir="C:/")

so I wrote a system command instead:
system('powershell -command "Expand-Archive -Path "C:/My File.zip" -DestinationPath "C:/" -Force"')

This command works beautifully but now that I want to parameterize the input file I have run into a problem with the backslash escape character when constructing the command:
in_file <- "C:/My File.zip"
command <- paste0("\'powershell -command \"Expand-Archive -Path \"", in_file, "\" -DestinationPath \"C:/\" -Force\"'")

Whilst cat(command) looks like the string I want:
cat(command)
> 'powershell -command "Expand-Archive -Path "C:/My File.zip" -DestinationPath "C:/" -Force"'

When I run system(command) I get an error:
Warning message:
running command ''powershell -command "Expand-Archive -Path "C:/My File.zip" -DestinationPath "C:/" -Force"'' had status 127

I put this down to the command not actually functioning like I want as the escape characters are still there:
print(command)
> "'powershell -command \"Expand-Archive -Path \"C:/My File.zip\" -DestinationPath \"C:/\" -Force\"'"

I have made all sorts of attempts to remove the backslashes e.g. gsub("\","",str, fixed=TRUE) but I just can't manage it.
How can I get my unzip command to work?

A: mt1022 got me on the right track. For the completion of this post, the answer is to use:
paste0('powershell -command "Expand-Archive -Path """', in_file, '""" -DestinationPath """', out_file, '""" -Force"')


text:
Q: How can we convert an arbitrary iterable of iterables into a nested list of lists of strings? Suppose obj has an __iter__() method.
We want to write a function which accepts obj as input and outputs a nested list of lists of lists .... of lists of strings.
If an object is iterable, and is not a string, we recur.
If an object is a string, we return the string.
If an object is non-iterable, we call the string-class constructor on that object, and return the resulting string.
Unfortunately, there may be self-loops. That is, an objects iter method might return an object we have seen previously.
root.__iter__().__next__().__next__().__iter__().__next__().__next__().__iter__().__next__() == root

Maybe we should use the id() function to check if the object has been seen previously?

A: Try this:
from collections.abc import Iterable

def collect(obj):
    if isinstance(obj, Iterable) and not isinstance(obj, str):
        return list(map(collect, obj))
    else:
        return str(obj)

obj = iter([iter([iter(['a', 2]), 'cd']), iter(['ef', 'gh'])])
print(collect(obj))  # => [[['a', '2'], 'cd'], ['ef', 'gh']]

I think that the id() check is unnecessary because once an iterator is iterated through, all the elements will be exhausted and there won't be anything else to iterate through. If you need to detect iterators that yield more iterators in an infinite pattern, then I think a foolproof way does not exist, as each new iterator will be a new object with a new ID.

A: This approach optimistically iterates any non-string t and recovers from errors using an exception handler -
def collect(t):
  try:
    if isinstance(t, str):
      return t
    else:
      return list(collect(v) for v in t)
  except TypeError:
    return t


text:
Q: Does the charger consume power after charged device is disconnected? Quite similar to this one. If I'm not mistaken any impulse mobile device charger is still consuming power, when plugged into socket, but when cable is disconnected from charged device. Correct?
Does the same rule goes for power sockets equipped with USB ports for charging mobile devices (link to Polish seller):

I was wondering, if this kind of construction means that my socket(s) will be continously draining power, 24 hours a day, no matter if anything is connected to it or not? Or do these have some kind of power-off "switch" (meaning stops draining power when everything is disconnected)?

A: These kind of AC to DC converter will always consumme a small amout of power to maintain the control IC alive. I do not see a way around that unless your USB port has some sort of mechanical switch to flip on the converter when you connect a device. I recommend you to look around as I found this wall plug (for US 120V unfortunatly for you) that only turn on the USB charger when you lift the small window above it (mechanical switch as I said). https://www.amazon.com/Newer-Technologies-NWTPWR2U15ATRW-Nwtpwr2u15atrw-15-amp/dp/B00BGF00TO
Usually, external ac to dc power supply must have an efficiency rating from level 1 to 6 now.
CUI Inc has a nice page that explains the regulation and this tells you how much "no load" power consumption you can expect for each efficiency level : http://www.cui.com/efficiency-standards
The problem I can see is that I am not sure if your AC to DC USB power supply count as an "external" power supply. Most USB charger from a wall plug doesn't specify an efficiency level... I do not know any regulations for internal power supply...

A: Yes,
any charger will consume some power, even if no charging device is connected to it. As @dim pointed out, if there is no physical switch which turns the charger off, there will always be some power consumption due to the charger converting the "raw" energy into a form the charging devices can use (from AC to DC and they adjust the volt count - usually to 5V).
However, how much power is drained is something else. This depends on how good/poorly the charger is made. You know definitely that a charger is not well made, if it makes high pitched noises or gets warm when plugged in without a charging device.
If you want to know how much power it drains exactly, or which of two chargers is more efficient, there are devices like this:

using it we can determine, how much energy a charger uses. It is of course not a very-high precision tool, but it should do the job for our case. Using it we can determine that the charger (I hadn't one like you showed in the image, so I used a normal microUSB charger) consumes 0.03A when charging a phone and 0.001A when plugged in without anything else (int this case, the charger did make the noise).
And this applys to basically any charger or device which does not have a physical switch or uses raw AC power. Some energy will always be lost, although it is not really enough to be something an average user should worry about (however, having a charger/similar that heats more and more up is).

A: In the past I randomly measured a few chargers and it appears like the power consumption is usually below 1W even for larger chargers like to one for a robot vacuum cleaner when no load is attached.
I live in the EU and this observation seems to be in line with an EU policy:

4 years after the regulation is in force (December 2012):

*

*Power consumption in off mode must be 0.5 Watts or less;

*Power consumption in stand by mode which allows reactivation must be 0.5 Watts or less;

*Power consumption in stand by mode which allows reactivation and displays information (such as a clock) must be 1 Watt or less.

A: Yes, the charger will use some standby current (unless there's a switch), but the current can vary widely depending on the charger.
I measured a dozen chargers a while ago and found the standby power usage varied from 19 milliwatts to 375 milliwatts depending on the charger. This works out to about 2 to 47 cents a year at average US power costs.
The switching power supply chip in the charger may be designed to minimize power when the charger isn't in use, for instance by skipping cycles when the load is low.

A: Yes, virtually all chargers and power supplies have a residual power drain when they are not supplying anything to their output.  Because there are hundreds of millions of these gadgets, the no-load residual power adds up quite substantially.
Government agencies are working to require much more efficient chargers and external power supplies ("wall-warts" and "line-lumps").  The USA Department of Energy estimates that more than 18 billion KWH annuallly have already been saved by the efficiency requirements already imposed by the states of California and Oregon. And estimate that savings approaching 30x more can be achieved by making much more efficient and "intelligent" chargers which don't waste power when there is no load, or stop pumping current into a battery after it is charged up.
Ref: https://www.nrdc.org/experts/pierre-delforge/new-federal-battery-charger-efficiency-standards-will-power-americas

A: Usually these devices have an internal transformer.
In a transformer, although the conversion efficiency is very high, there are ALWAYS losses, even in no-load conditions.
The equivalent circuit is like this:
(from Fitzgerald-Kingsley).
As you can see also if \$I_2=0\$ (secondary in open circuit condition, i.e. no load) there's a current that can flow in the primary.
You can verify this assertion easily; if you have a common smartphone charger (not too high  quality) you can feel it lukewarm if you leave it connected to the plug when not in use.
The passive elements represent the various kind of losses that there are in the transformer (Joule, Eddy current, flux leackage, etc) that in italian we usually call as "copper losses" and "iron losses" (translated in english, I don't know if there's a conventional english name).

A: As can be seen from the picture there are 3 outputs.

*

*The standard 230VAC output with earth contacts (SCHUKO).

*1 power port for tablets with USB connection

*1 power port for Phone and other devices.

As for 1. No power is used unless you plug in and switch on an appliance. It is a pass through connection, just copper.
For 2 and 3. These outputs supply 5 VDC up to a specific max current rate. (See documentation). Most probably with ONE so called buck converter. These units still use a very small amount of power as long as they are connected to the mains.

A: All electronics consumes some power when operating, so the short answer is "Yes" it will always consume some power if there is no physical switch to disconnect the input source.
If you look at the schematic for an Apple charger, you will find it is using this controller.
Looking at the datasheet we find that the quiescent current (the current required simply to drive the controller with no load) is as high as 3.5mA.

This is but one example; certainly there are many ways of doing this, but the technique in the above controller is very common and although we strive to minimise 'standby' power, there will always be some energy used while the charger is plugged in.

A: I believe there are only two ways of converting A/C mains to the low voltage D/C needed for charging phones.
Older devices used a transformer.  Theoretically there should be no drain on the mains when there's no current flowing through the low voltage side.  However, inefficiencies in transformers and the circuitry used to smooth/condition the low voltage could draw small currents (milliamps) hence the need to unplug chargers.
More modern devices use digital controllers to smooth short, high frequency pulses mains voltage to average out as low voltage.  These are sophisticated chips with current limiters and very high impedence components.  These supply current when the battery charging circuit in your phone calls for it.
Even if you leave your phone plugged in, it will only be drawing current while it needs to charge.  And without anything plugged in, ambient consumption will be negligable, less than microamps.

A: Yes, every always-on power supply consumes power when is not loaded or in standby mode. However, the real question is how much does it use relative to your overall household consumption. Of course, some people go around the house and unplug every wall adapter and laptop AC-DC bricks, and frequently you run into discharged dead device that you happen to need right now. So the question is whether the power savings from standby PS are worth the inconvenience to have non-functional devices, reach to AC outlets to plug-unplug, or pay $20 more for super-saving standby supplies as compared to $3 for cheap Chinese box?
I just did a quick and dirty experiment. I took five laptop AC-DC adapters (Dell, HP, Lenovo,..), five 5V-12V regular wall-warts, and five 5V 1-2A phone chargers (Apple, Samsung, ASUS...), and plugged all of them (via power strips) into the Kill-A-Watt power meter. I got 7W total. On average it is 0.5W per an idling power supply. Seven Watts over a year comes as 60kWh/year. With average household consumption of about 6,000 kWh/year (Canada and US uses 11,000 kW/yr), this 15 power supplies constitute about 1% of the entire household consumption.
Now consider that industrial production and consumption of electricity exceeds household consumption 20X, regulation of standby efficiency of external PS in households will affect 0.05% of overall energy consumption.
But of course it would be nice if manufacturers would be forced to state the idle power of their products on a label.

A: No brother. if you disconnect your cable then circuit is break , so electron can't pass and there is no any draining of power if device is disconnect.


text:
Q: How to add two different paths to the same endpoint in swagger? Using javaws we can have multiple endpoints leading to the same method. Example:
@Path("/menus")
public class MenuResource {
    @Path("/{menuId}/sections")
    @Timed @ExceptionMetered
    public MenuSectionResource getSections(@InjectParam MenuSectionResource resource) {
        return resource;
    }
}

@Path("/sections")
public class MenuSectionResource {
    @GET
    public Section get(@PathParam("menuId") String menuId, @QueryParam("id") String id) {
        /// method accessed by GET in /sections or GET in /menus/{menuid}/sections
    }
}

I'm trying to use swagger to document both endpoints, but i can only use one
@Api annotation in each class, so i can generate either /sections or /menus/{menuid}/sections. Is it possible to automatically generate both entries in the swagger.json output?


text:
Q: Partial keyword searching Can anyone give me an idea of how I can do partial keyword searching with php/mysql search engine?
For example, if a person search for "just can't get enough" i want it to return search result containing keywords "just can't get enough by black eyed peas" or from keywords " black eyed peas just can't get enough".
Another Example: If I entered "orange juice" i want it to return result with keywords "orange juice taste good"
Its pretty much like google and youtube search.
The code I'm using is: http://tinypaste.com/eac6cf

A: The search method you've used is the standard method of searching from within small amounts of records. For example, if you had just around a thousand records, it would be ok.
But if you've got to search from millions of records, this method is not to be used as it will be terribly slow.
Rather you have two options.

*

*Explode your search field and build your own index containing single words and a reference to the record position. Then only search your index and seek the corresponding record from the main table.

*Use MySQL's Full text search feature. This is easier to implement but has its own restrictions. This way you don't have to build the index yourself.

A: MySQL full-text search would help here, but would only work with myISAM tables and the performance tends to go through the drain when your data-sets becomes quite large.
At the company I work for, we push our search queries to Sphinx. Sites like Craigslist, The Pirate Bay, Slashdot all use this so it's pretty much proven for production use.

A: In MySQL, you can use a MyISAM type table and simply define a text field (CHAR, VARCHAR, or TEXT) and then create a FULLTEXT index. Just keep in mind the size of the text field, the more allowed characters, the larger the size of the index and the slower it's going to be to update.
Other large data-set options would include something like Solr but unless you already know your data is going to have a ton of data, you could certainly start with MySql and see how it goes.
Most MySQL editors, including phpmyadmin provide a gui for adding indexes, if you're doing it by hand the code would look something like:
CREATE TABLE IF NOT EXISTS `test2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`),
  FULLTEXT KEY `ft_name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


text:
Q: Long Figure Wrap May I ask how to auto-wrap a too-long figure as shown below(sleepy channel protocol), so that the overflow part of the figure can be shown in the next page automatically?  Thanks.
Note: The paper is already in double-column format.

This figure is from:https://eprint.iacr.org/2021/1445.pdf, page 17


text:
Q: Como aplicar funções recursivas? Criar um programa em  c# que permita mediante o uso de função recursiva, determinar a quantidade de vezes que aparece a letra B em uma palavra inserida pelo usuário.

A: Basicamente uma função recursiva é aquele que invoca assim mesma até que uma determinada condição satisfaça, no caso da sua pergunta parece que o exercício é varrer letra a letra até o seu fim, então um código abaixo para exemplificar como passar a ler letra a letra e retornar esse novo texto para que seja verificado novamente, até não ter mais texto, exemplo:
using System;

public class Program
{
    static int Count(string word, string letter)
    {
        if (word.Length > 0){
            if (letter == word.Substring(0,1))
            {
                return 1 + Count(word.Substring(1), letter);
            }
            else
            {
                return Count(word.Substring(1), letter);
            }
        }
        return 0;
    }
    public static void Main()
    {
        string palavra = "bcb0ç";
        System.Console.WriteLine(Count(palavra, "b"));
    }
}

Um outro código sugere um melhor desempenho utilizando indexOf, onde a ocorrência for maior que -1 o valor foi encontrado e pula para o próxima pesquisa se tem mais algum índice maior que -1 e assim por diante limitando a pesquisa na busca somente do valor procurado:
using System;

public class Program
{
    static int Count(string word, string letter)
    {
        if (word.Length > 0){
            int index = word.IndexOf(letter);
            if (index > -1)
            {
                return 1 + Count(word.Substring(index + 1), letter);
            }
        }
        return 0;
    }
    public static void Main()
    {
        string palavra = "bcc0b00bb";
        System.Console.WriteLine(Count(palavra, "b"));
    }
}


text:
Q: set two titles? I can setTitle("My Title"), but what I'm looking to do is set two titles... one on the left side and one on the right. How might I do that?
I currently have 2 textviews, aligned parent left and right... the textappearance is changed. But I'm hoping to get that into the titlebar using code so I don't have to use some background to simulate the titlebar.

A: I don't think you can...I think Android only allows one title...but what you could do is
setTitle("My Title left                       My title right");

It's more than a little bit of a hack but it might work.
Full disclosure: haven't tried it.

A: Look at this tutorial for skinning / theming your titlebar

A: I'm playing around with some files right now to try and create this dual title bar.
It looks like this post would be helpful: my_own_titlebar_backbutton_like_on_the_iphone.
The comment written on this post at Thu Jan 29, 2009 5:55 pm contains the sample files, title1.zip, a second source file, title2.zip is a few comments below that one as well.

A: You can define a custom view layout and tell the system to use it with:
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.text_title);

You can make your title view a RelativeLayout with two children positioned as you like. This should be done in onCreate() before calling setContentView(). See this thread for more discussion of using a custom view.

A: If you look at the Bluetooth Chat example on the Android Resources page, here, you'll see that it has exactly that sort of format. Details on how to access it are included there. It contains an XML edit and a few other simple modifications in your initialization code.


text:
Q: ajax - return and prevent deferred.then() execution I have a AJAX request like this:
$.ajax({
   type: 'GET',
   url: url,
   dataType: "json",
   success: function(data) {
      // ...
      callbak(true);
   },

  })
  .then(
    function( response ) {
        // ...
    });

I'd like to run that callback function and so exit from that ajax request in success function and prevent deferred.then() execution.
In my case the callback is fired but after that deferred.then()  is also executed and I don't want this to happen.
Any idea?
Thanks

A: Use a flag like so:
var executeThen = true;
$.ajax({
        type: 'GET',
        url: url,
        dataType: "json",
        success: function(data) {
            // ...
            executeThen = false;
            callbak(true);
        },

    })
    .then(function(response) {
        if(executeThen){
         // ...
        }
    });


text:
Q: OAuth Test Console signature doesn't agree with working request I'm having trouble using the LinkedIn API due to being returned a 401 with auth_problem=signature_invalid. I do however have a project which seems to be working with fine so I'm using this to identify the differences.
I read that I can debug with the OAuthTestConsole however this appears to be generating a different signature than the working project.
Since I'm this is only a hobby you can have both my keys:
API Key: gh69xphn2hcr
Secret Key: 0ld6NVvjmpvrmZqw

My working request is:
POST https://api.linkedin.com/uas/oauth/requestToken HTTP/1.1
Content-Type: application/x-www-form-urlencoded Host: api.linkedin.com
Content-Length: 175
Connection: Keep-Alive

oauth_consumer_key=gh69xphn2hcr&oauth_nonce=186481&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1325243837&oauth_version=1.0&oauth_signature=gTeEgzknW6DyI3aFTDcXduroIG4%3d

However the oAuthTestConsole returns an oauth_signature of WNcZFXAC5Y2hoK4srFiFc69zi0M= which is nothing alike (encoded or not).
I'm thinking I must be using the TestConsole wrong and this is preventing me from fixing my issue between the working / non working projects. Could you please point me in the right direction as to why this might occur?

A: To use the OAuth Test Console, you need to make sure that all of the parameters are exactly the same
- the timestamp (you'll need to set that manually, as it'll otherwise be created based on the current time)
- the nonce (check to see what your library is sending)
- the method (POST in this case)
You need to clear both fields for the access_token (since you don't have one for this initial request)
There is a working C# example posted by a community member here:
https://developer.linkedin.com/thread/1190
Many people have had a lot of luck starting with that, as using OAuth can be tricky without an example to start from.


text:
Q: How do I get the color of a pixel in a UIImage? So I'm trying to make a program where Im taking a photo and it tells the user what the color is. I'm having trouble implementing the portion of func getPixelColor. Could anyone give me some tips on how to fuse this program together?
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var cameraButton: UIButton!
@IBOutlet weak var cameraView: UIImageView!
@IBOutlet weak var photosButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func tappedCameraButton(_ sender: Any) {
    let picker = UIImagePickerController()
    picker.sourceType = .camera
    picker.allowsEditing = true
    picker.delegate = self
    present(picker, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    cameraView?.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
    picker.dismiss(animated: true, completion: nil)
}
extension UIImage {
    func getPixelColor(pos: CGPoint) -> UIColor {

        let pixelData = self.cgImage!.dataProvider!.data
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

        let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

        let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
        let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
        let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
        let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

        return UIColor(red: r, green: g, blue: b, alpha: a)
    }

}

}

}

A: You need to get the CGPoint of the user touch and then use getPixelColor(pos:) to get the color.
There are two ways to get CGPoint

*

*You can use any of the methods to get the location touchesBegan(_:with:), touchesMoved, touchesEnded

*Use tap gesture
Here is the StackOverlow code the get the CGPoint: How to get a CGPoint from a tapped location?

A: extension UIImage {
     func getPixelColor(pos: CGPoint) -> UIColor? {

        guard let cgImg = cgImage, let provider = cgImg.dataProvider else {
            return nil
        }
        let pixelData = provider.data

        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

        let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

        let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
        let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
        let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
        let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
        return UIColor(red: r, green: g, blue: b, alpha: a)
     }
 }


text:
Q: Why `memmove` function has significant difference in two different computers? I've tried to run the following C code from two different computers.
#include <string.h>

int a[100000];
int main(){
    for(int sz = 100000; sz > 1; sz --){
        memmove(a, a+1, 4*(sz - 1));
    }
}

Computer A uses 800ms, while computer B uses 6200ms. The running time of B is always far more than A.
Environment
compile command
Shell is bash.
And the -O gcc command doesn't influence runtime.
gcc myfile.c -o mybin
time ./mybin

Computer A
gcc 9.3.0
glibc: ldd (Ubuntu GLIBC 2.31-0ubuntu9) 2.31
uname_result(system='Linux', release='5.4.0-100-generic', machine='x86_64')
CPU: Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
Computer B
gcc 9.3.0
glibc: ldd (Ubuntu GLIBC 2.31-0ubuntu9.2) 2.31
uname_result(system='Linux', release='4.4.0-210-generic', machine='x86_64')
CPU: Intel(R) Xeon(R) Platinum 8369B CPU @ 2.70GHz
Question
Then I run the following file on same virtual machines, with different kernal version(4.4.210-0404210-generic x86_64 and 5.4.0-113-generic x86_64) with gcc 9.3.0. Two test cost less than 500ms.
#include <string.h>
#include <time.h>
#include <stdio.h>

#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)

int a[100000];
int main(){
    TICK(timer);
    for(int sz = 100000; sz > 100; sz --){
        memmove(a, a+1, 4*(sz - 1));
    }
    TOCK(timer);
}

How can I find the cause?


text:
Q: from excel to sql server I have some excel files that contains some information I need to convert it to a sql server database. The problem I face is that these information are not structures as my database model so I need to do some modifications.I am using .net and I'm thinking to use Open XML SDK to parse the excel files, is this a good choice or there is better ?

A: Your choices are

*

*Microsoft Excel Automation Model

*Open XML SDK

*SharePoint Excel automation services
The benefit of 1 is that it has a less learning curve , more samples on the net etc. But it needs Excel to be installed on the machine and is very resource intensive. Don't expect 100 simultaneous conversions easily.
The benefit of 2 is that its free and consumes very little system resources but is harder to master. If you need to do this automated on a server 2) makes sense
3 option is also good if you need it on a server box but you need a sharepoint installation

A: why not use an SSIS package if available?
http://www.mssqltips.com/sqlservertip/1393/import-excel-unicode-data-with-sql-server-integration-services/
You can then execute the SSIS package recursively, or...
if you need to do it just one time, I'd take a look at the SSMS import / export wizard... not sure if it does excel, but I know it does .csvs, which you can use excel to convert your spreadsheets to.  Not very fun if you need to do this a bunch of times though, but quicker than any other approach in regards to your time.


text:
Q: Converting decimal number to binary Objective-C Hi I have made an IOS app that converts binary, hexadecimal and decimal values. It all works fine except for my decimal to binary conversion. Here is what I have. It returns 0s and 1s but far too many. Can anyone tell me why this is or help me with a better method?
NSString *newDec = [display text]; //takes user input from display
NSString *string = @"";
NSUInteger x = newDec;
int i = 0;
while (x > 0) {
    string = [[NSString stringWithFormat:@"%u", x&1] stringByAppendingString:string];
    x = x>> 1;
    ++i;
}
display.text = string; //Displays result in ios text box

A: Try this:
NSUInteger x = [newDec integerValue];

And next time don't ignore the Compiler's "Incompatible pointer to Integer conversion" hint...
Explanation: Afaik, assigning an object to an int, actually assigns the address of the object to that integer, not the content of the string (which is what you want).


text:
Q: Get Value of Form Field I have several fields dynamically created on my page. I use the following function in order to align the ID field of that row with the correct "ntheme" field of that row.
$(document).on('change', 'select', function() {
  var checkbox = $(this),
    otherInput = $('nrowid' + this.id.replace('ntheme', ''));
    console.log(otherInput);
   console.log($(this).val());
 for(var i=0;i<rows1;i++){
  if($(this).val()==themes[i].Themes){
//set value of otherinput to themes[i].ID

  }
 }

  console.log(otherInput.val());
});

Is there a way I can set the value of the otherInput field and then return that value using console.log?

A: //Get
var otherInput2 = $('#nrowid').val();
//Set
var otherInput2 = $('#nrowid').val('your value');
console.log(otherInput2);


text:
Q: Failed resolution of: Lcom/google/devtools/build/android/desugar/runtime/ThrowableExtension; I'm using RxJava with Retrofit on the newest preview of AndroidStudio. My project has java 1.8 suport enabled like this:
compileOptions {
    targetCompatibility 1.8
    sourceCompatibility 1.8
}

But when the code is compiled and run I'm getting this error, as soon as the request is made, even if I have the onError handler:
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/devtools/build/android/desugar/runtime/ThrowableExtension;
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:281)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:58)
at io.reactivex.Observable.subscribe(Observable.java:10179)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:10179)
at io.reactivex.internal.operators.flowable.FlowableFromObservable.subscribeActual(FlowableFromObservable.java:31)
at io.reactivex.Flowable.subscribe(Flowable.java:12218)
at io.reactivex.internal.operators.flowable.FlowableOnBackpressureLatest.subscribeActual(FlowableOnBackpressureLatest.java:31)
at io.reactivex.Flowable.subscribe(Flowable.java:12218)

This happens even if I use Maybe, Single or Observable. How can this issue be resolved?

A: This is in fact not RxJava error neither Retrofit. It is Instant run error, i disabled it and my app launched.
As a temporary solution, you can disable Instant run, too.
To do it, go to Build, Execution, Development -> Instant Run in Settings.


text:
Q: Spring Boot Rest API How to get Client Information I am writing a Rest API using spring framework which multiple clients (Web/Mobile) will use. In my API I want to know the client's info (client name) who is accessing it. What is the best practice to get the client name in API. Should I get it in http header or body?

A: If you want to get information about the one accessing your endpoints, you must secure your endpoints and allow only authenticated users.
This way you can get all the information you need about the user.
You can check spring security project for more details.


text:
Q: How can I count the number of structures inside my file ? c++, files struct Product{
    int price;
};

int main()
{
    // I am dynamically allocating n structures
    int n; cin >> n;
    Product* p;
    p = new Product[n];

    // I give each one of them a price
    for(int i = 0; i < n; i++){
        cin >> p[i].price;
    }

    // Then, I store the structures in a file
    fstream file;
    file.open("file.bat", ios::app);
    if (file.is_open()) {
        file.write(reinterpret_cast<char*>(p), n * sizeof(Product));
        file.close();
    }
}

Assuming each time I reopen the program, I will append new products to the file, how can I know how many structures (products) I have stored inside the file in total?

A: I hope this helps (I'm beginner) ...
#include <iostream>
#include <fstream>

struct product { int price; };

inline auto& operator>>(std::istream& stream, product& object) { return stream >> object.price; }

template <typename _Type>
inline auto& write_file(std::ostream& stream, const _Type& object, const std::streamsize count = 1) {

    const auto raw = static_cast<const void*>(&object);

    return stream.write(static_cast<const char*>(raw), count * sizeof(_Type));

}
template <typename _Type>
inline auto& read_file(std::istream& stream,        _Type& object, const std::streamsize count = 1) {

    const auto raw = static_cast<void*>(&object);

    return stream.read(static_cast<char*>(raw), count * sizeof(_Type));

}

int main()
{

    /*

     1. Always initialize.
     2. Use "using namespace std;" carefully.
     3. Manage all your resources (memory included).
     4. Check more operations (including readings).

    */

    size_t values_size{};

    if ((std::cin >> values_size).fail() || values_size == 0) return 1;

    const auto values = std::make_unique<product[]>(values_size); // Personally, i prefer use vector<product>

    for (auto it = values.get(); it != values.get() + values_size; ++it) {

        auto& value = *it;
        std::cin >> value;

    }

    constexpr auto file_name = "file.bat";

    {

        std::ofstream file(file_name, std::ios_base::binary | std::ios_base::app);

        if (!file.is_open()) return 1;

        write_file(file, *values.get(), values_size);

    }

    size_t count{};

    {

        std::ifstream file(file_name, std::ios_base::binary);

        if (!file.is_open()) return 1;

        do {

            decltype(values)::element_type value{};
            if (read_file(file, value)) ++count;

        } while (file);

    }

    std::cout << "Number of products inside the file " << file_name << " : " << count << '\n';

}

Edit : (Vector version)
#include <iostream>
#include <fstream>
#include <vector>

struct product { int price; };

inline auto& operator>>(std::istream& stream, product& object) { return stream >> object.price; }

template <typename _Type>
inline auto& write_file(std::ostream& stream, const _Type& object, const std::streamsize count = 1) {

    const auto raw = static_cast<const void*>(&object);

    return stream.write(static_cast<const char*>(raw), count * sizeof(_Type));

}
template <typename _Type>
inline auto& read_file(std::istream& stream, _Type& object, const std::streamsize count = 1) {

    const auto raw = static_cast<void*>(&object);

    return stream.read(static_cast<char*>(raw), count * sizeof(_Type));

}

template <typename _Type>
auto fill_vector(std::istream& stream, std::vector<_Type>& vector) {

    do {

        _Type elem{};

        if (stream >> elem) vector.emplace_back(std::move(elem));

    } while (stream && vector.size() < vector.capacity());

}

int main()
{

    /*

     1. Always initialize.
     2. Use "using namespace std;" carefully.
     3. Manage all your resources (memory included).
     4. Check more operations (including readings).

    */

    std::vector<product> values;
    {

        size_t n{};

        if ((std::cin >> n).fail() || n == 0) return 1;

        values.reserve(n);

        fill_vector(std::cin, values);

    }

    constexpr auto file_name = "file.bin";

    {

        std::ofstream file(file_name, std::ios_base::binary | std::ios_base::app);

        if (!file.is_open()) return 1;

        write_file(file, *values.data(), values.size());

    }

    size_t count{};

    {

        std::ifstream file(file_name, std::ios_base::binary);

        if (!file.is_open()) return 1;

        do {

            decltype(values)::value_type value{};
            if (read_file(file, value)) ++count;

        } while (file);

    }

    std::cout << "Number of products inside the file " << file_name << " : " << count << '\n';

}

The write_file and read_file functions work in the same way as using naked reinterpret_cast, the difference is that they take care of the conversions for you and guarantee the writing/reading of 1 or n elements of a given type without specifying the dimension of the type, this allows you to avoid writing/reading of sliced objects or merged objects.
fill_vector creates and reads a new _Type element, if the reading was successful, the element will be added to the vector, otherwise the element will not be added. The loop will stop if a reading has not been successful or if the vector is full.
std::move serves to "activate" the move semantics, instead of creating a copy of elem within the vector, we move it, this can be useful and efficient for owner objects.
To count the amount of products within the file, I created a loop that reads objects that have the size of a product. If we can read a product, the count value will start to increase.


text:
Q: Detect Distance/Proximity Windows Phone I want to make an app using phone sensor, similar to something happen when you are on phone call and the sensor covered and the device screen turned off. Is there any API available to access that sensor? thx

A: You have the LightSensor class available as documented here.


text:
Q: How to use bootstrap styles on print page with Asp.net bundling I am trying to use bootstraps row/column grid on a print page, however when I go to the print preview all of the rows and columns are missing.  I've referenced this solution and have the link tag showing in my html correctly:
<link href="/Content/bootstrap.css" rel="stylesheet" type="text/css" media="all">

Still, this shows on the screen:

And this shows on the print preview:

How do I get my bootstrap styles to show on the print preview and printed page?

A: According to this, Bootstrap 3 considers the paper page to be less than 768px wide, so it displays the mobile version of the page. You should probably create a special print stylesheet for the printed view.
Alternately, you should be able to get around this by adding xs classes to your grid, like this:

First Name

Middle Initial

Last Name

This isn't a great idea though, because a printed view is different from a small viewport, so it's better practice to create a separate print stylesheet.


text:
Q: Error "Cannot find module 'react' or its corresponding type declarations." inside our sharePoint online SPFx project I am working on an 1.14 SPFX web part, but inside the .ts file we are getting reference errors on almost all the libraries as shown in this picture:-

For example, on the first reference error "Cannot find module 'react' or its corresponding type declarations... i tried those commands:-
npm install react

npm install --save-dev @types/react

npm i @microsoft/rush-stack-compiler-3.9

but did not fix anything.. any advice on this please?
Thanks


text:
Q: Syntax Error at line 1: Label can not be 'BRA' Getting the error below:
Syntax Error at line 1: Label can not be 'BRA'

when trying to compile:
BRA ND
ND LDAA #0

using sdk.

A: Assembly languages tend to view symbols at the start of the line as labels. Instructions needs to be indented:
; Note indentation here
;vv
   BRA ND
ND LDAA #0

A: The operation either needs to have whitespace or label in front of it in the right syntax. So replace:
BRA ND

with:
 BRA ND

to have:
 BRA ND
ND LDAA #0


text:
Q: SQL Server error "Procedure expects parameter" I'm writing a login script. But when I want to check if user already exist the error:

Additional information: Procedure or function 'checkIfUserExcist' expects parameter '@username', which was not supplied.

will show up.
When I execute the stored procedure with one parameter it will succeed. Sow there is something wrong with my code, but I can't find the mistake.
This is the stored procedure:
@username varchar(50)
as
begin
    SELECT count(*)
    FROM lars.userAcces
    WHERE username = @username
end

And this is my C# code:
public static bool checkIfUserExists(string username)
{
        int temp=0;

        SqlConnection conn = SqlConn.openSqlConnection();
        conn.Open();

        SqlCommand com = new SqlCommand("checkIfUserExists", conn);
        com.Parameters.AddWithValue("@username", username);

        temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        conn.Close();

        if (temp == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
}

A: You need to tell your SqlCommand that it uses a stored procedure - like this:
SqlCommand com = new SqlCommand("checkIfUserExcist", conn);
-- add this line here
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@username", username);


text:
Q: Access Controls from UserControls in ASPX page How to Access Controls from UserControls in ASPX page?
For example:
I want to access gridview which is in usercontrol on ASPX page.
Please help me.

A: The best way is to provide properties in your UserControl that you can access.
For example:
public GridView UserGrid
{
     get
     {
         return GridView1;
     }
}

But the question is why you need this.
Rule of thumb: Only expose as few as possible. On that way your code will be most robust and readable. So it would e.g. better to expose it's DataSource rather than the complete GridView.
On the other hand, if you want your page to react on events in your UserControl, it should provide custom events(e.g. UserDeleted) that your page then can handle.
Page-UserControl-Commmunication

A: Because the controls now nothing about eachother at the same level, you have to use the parent page to get it. Try this logic:

*

*Create a property referring to your parent page (the page your control usually is in (might be different because of layering of controls)

*Create a property on your page referring to the usercontrol the grid is in, or link to that grid directly.
page.aspx
public UserControl UserGridControl
{
     get;
     set;
}

userControl.ascx
public Page ParentPage
{
     get;
     set;
}

Example call:
Instantiate the properties first. After that, use the following statement to access anything from that control (as an example I used Foo() here, to use as a dummy method, but it seems it was unclear to someone):
otherControl.ascx:
this.ParentPage.UserGridControl.Foo();

EDIT: Want to have a direct code example to be able do it from the page only? See Tim Schmelters answer. If you need a way to call the grid from another user control as well. Use mine.

A: Try this :
GridView GridView1 = (GridView)WebUserControl1.FindControl("GridView1");

Where WebUserControl1 is ID of use control on .aspx page.
Hope this helps..


text:
Q: Interpretation of Odds Ratio (OR) in Fisher's exact test I've tried using R operating Fisher's exact test to test for independence of the 2 datasets below and struggling to interpret the Fisher report. Please have a look at the data and the Fisher's test below.
Dataset 1: is a 2x3 contingency table

Consider then an experiment where we have 2 categorical variables: Group (I and II) & Outcome (Worse, Same, and Improve). These results might follow the administration of a new drug. We collect data and find out the frequencies as shown in the table below.

You can reproduce Dataset 1, and run the Fisher's test using the codes:
obs <- rbind(c(33, 44, 25),
             c(11, 28, 30))
rownames(obs) <- c("Group I", "Group II")
colnames(obs) <- c("Worse", "Same", "Improve")
obs

##          Worse Same Improve
## Group I     33   44      25
## Group II    11   28      30

fisher.test(obs)

##   Fisher's Exact Test for Count Data

## data:  obs
## p-value = 0.01049
## alternative hypothesis: two.sided

Dataset 2: is a 2x2 contingency table

Consider then an experiment where we have 2 categorical variables: Group (I and II) & Outcome (Worse and Improve). These results might follow the administration of a new drug. We collect data and find out the frequencies as shown in the table below.

vals <- matrix(c(3, 1, 3, 2),
               nrow = 2,
               dimnames = list(Group = c("Group I", "Group II"),
                               Outcome = c("Worsened", "Improved")))
##  Outcome
##  Group          Worsened Improved
##  Group I             3        3
##  Group II            1        2

fisher.test(vals)

##
##  Fisher's Exact Test for Count Data
##
## data:  vals
## p-value = 1
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
##    0.06060903 156.52286969
## sample estimates:
## odds ratio
##   1.852496

As you can see that I receive 2 different report templates for the two contingency tables a (2x3) and a (2x2). I have 3 questions:

*

*Why the report of a 2x2 includes the Odds Ratio (OR) and the Confidence Interval, while the 2x3 doesn't have the OR or the Confidence Interval in there?
Does that mean testing for independence using the value of OR could be applied ONLY for 2x2 contingency tables??

*Could you help me interpret the Fisher's test report and point out the connection between the values of p-value, Odds ratio, and Confidence Interval?

*In what case will we be using "one-sided Fisher's exact test"? What is the purpose of pointing out a Fisher's test should be one-sided or two-sided?

*Can a table that's NOT 2x2 be tested using a "one-sided Fisher's exact test"?


text:
Q: How to get and display routes and directions in windows phone 8.1 app i want to get the routes on map and direction in windows phone 8.1 app in c#.I am using this code but it show "invalid credentials"
please reply
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    MapService.ServiceToken = "AgyhW8zBh1zs6Umd7H6CZwDUf7jc2YerR2t1dpxQzWLM3nPzZcR3d3jQNXXGg0xw";
    // Start at Microsoft in Redmond, Washington.
    BasicGeoposition startLocation = new BasicGeoposition();
    startLocation.Latitude = 47.643;
    startLocation.Longitude = -122.131;
    Geopoint startPoint = new Geopoint(startLocation);

    // End at the city of Seattle, Washington.
    BasicGeoposition endLocation = new BasicGeoposition();
    endLocation.Latitude = 47.604;
    endLocation.Longitude = -122.329;
    Geopoint endPoint = new Geopoint(endLocation);

    // Get the route between the points.
    MapRouteFinderResult routeResult =
        await MapRouteFinder.GetDrivingRouteAsync(
        startPoint,
        endPoint,
        MapRouteOptimization.Time,
        MapRouteRestrictions.None);

    if (routeResult.Status == MapRouteFinderStatus.Success)
    {
        // Display summary info about the route.
        tbOutputText.Inlines.Add(new Run()
        {
            Text = "Total estimated time (minutes) = " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString()
        });

        tbOutputText.Inlines.Add(new LineBreak());

        tbOutputText.Inlines.Add(new Run()
        {
            Text = "Total length (kilometers) = " + (routeResult.Route.LengthInMeters / 1000).ToString()
        });

        tbOutputText.Inlines.Add(new LineBreak());
        tbOutputText.Inlines.Add(new LineBreak());

        // Display the directions.
        tbOutputText.Inlines.Add(new Run()
        {
            Text = "DIRECTIONS"
        });

        tbOutputText.Inlines.Add(new LineBreak());

        foreach (MapRouteLeg leg in routeResult.Route.Legs)
        {
            foreach (MapRouteManeuver maneuver in leg.Maneuvers)
            {
                tbOutputText.Inlines.Add(new Run()
                {
                    Text = maneuver.InstructionText
                });

                tbOutputText.Inlines.Add(new LineBreak());
             }
        }
    }
    else
    {
        tbOutputText.Text = "A problem occurred: " + routeResult.Status.ToString();
    }
}


text:
Q: Eigenvalues of Householder matrix What would be the eigenvalues for a Householder matrix defined as: $H = I - 2 u u^T$? Can someone explain it  to me intuitively or with a simple proof?

A: The characteristic polynomial of $H$ is
$$
p(\lambda)=|\lambda I-H|=(\lambda-1)^n+Tr(2uu^T)(\lambda-1)^{n-1}
$$
for $uu^T$ is a Rank-$1$ matrix and all principal minors above $2$ are $0$.
Since $Tr(2uu^T)=2Tr(u^Tu)=2$
$$p(\lambda)=(\lambda+1)(\lambda-1)^{n-1}$$
Or eigenvalues of $H$ are $±1$.

A: Householder matrices are orthogonal and symmetric.  That is:
$$ (I - 2uu^T)^T = I - 2uu^T $$
$$ (I - 2uu^T)^2 = I - 4uu^T + 4u(u^Tu)u^T = I $$
Here $u^T u = 1$ since $u$ is a unit vector.
Eigenvalues of orthogonal matrices have absolute value $1$, since multiplication by an orthogonal matrix is an isometry (length preserving).
Since the Householder matrix $H = I - 2uu^T$ is real and symmetric, its eigenvalues are real.  The only real numbers with absolute value $1$ are $\pm 1$.
Since $Hu = u - 2u(u^T u) = -u$, there is at least one eigenvalue $-1$, and indeed the vectors $v$ perpendicular to $u$ will satisfy $Hv = v - 0u = v$.  So there is a complete basis of eigenvectors, one for the eigenvalue $-1$ and the rest for eigenvalue $1$.

A: Just compute $Hu$ and $Hv$ where $v$ is orthogonal to $u$. And remember that eigen spaces of different eigenvalues are orthogonal (for symmetric matrices).


text:
Q: How to pass address of C++ object to C I'm using Visual Studio 2013 and C++11. I want to pass the address of a C++ object back to C. The C code will treat it as a opaque handle; C will never reference it. The only use will be to pass it back to C++ where it will again be used as a pointer to object.
I'm finding that if I create the object in C++ and pass it back to C, the object will be destroyed because it goes out of scope. As a work around, I created a global variable to hold the object so it won't be destroyed upon returning to C. What is the best practice? Should I use a ref-counted pointer type such as shared_ptr? How? I don't like the idea of casting to size_t or such.
The following is an attempt to demonstrate the question. Code won't work.
extern "C" _declspec(dllexport) void __stdcall SwbHttpListenW(const wchar_t *route, SwbHttpListen **listener)
{
    *listener = &SwbHttpListen(route); // new will work but how about without new?
}

[Edited the code to re-ask for a solution not using new.]

A: How about heap allocating the C++ object using the new operator, and getting its address by using the ampersand (&) operator? By heap allocating the object, you ensure it will never be deleted until you actually use the delete operator on it, and the address could be stored/passed as an int.
A simple example:
int main() {

    Person *a = new Person("Paul");
    doSomething(a); //Passes the memory address of a to the function doSomething

    //...and once you're finished using the object, you have to:
    delete a;

    return 0;
}

A: It's always going to be messy when you do this sort of thing, how you handle it really depends upon what you want the lifetime of your c++ object to be and, to a lesser extent, how you are going to get rid of it in the end. But clearly the c++ has to do any destruction, you cannot get the c to do that.
This sort of thing is an example of when it is not necessarily A Bad Thing to have global objects - though of course that means you cannot get rid of it freely. Alternatively, you could create it dynamically using new but you then will need an arrangement between the c and the c++ so that it gets deleted at the right time - you might end up with a global object pointer or maybe the c could pass the pointer back to get it destroyed - that would be the nicest solution.

A: Some trouble may be if some automated Garbage Collector are in use (it may be in C++). std::declare_reachable , std::undeclare_reachable may help.
Else the trouble really doesn't concern passing a pointer to C. And you need to develop some way to achieve a proper pointers to valid objects at the places where necessary... :-)


text:
Q: How to load relations with tree entity with typeorm? I have a Role Entity and a Route Entity which is tree structure, and they're ManyToMany relation.
Now I want to retrive all the roles via RoleRepository.find({relations: ['routes']}), which will load all the roles data as expected, however the routes prop won't automaticlly load it's children data, which looks like:
[{
  id: 1,
  name: 'route1',
  routes: [{
    id: 1,
    path: '/home'
  }]
}]

I've checked all documentation and had no clue to make it.
@Entity()
export class Role {
  @PrimaryGeneratedColumn()
  public id: number

  ... some other columns

  @ManyToMany(type => Route, route => route.roles)
  public routes: Route[]
}

@Entity()
@Tree('materialized-path')
export class Route {
  @PrimaryGeneratedColumn()
  public id: number

  @TreeParent()
  public parent: Route

  @TreeChildren({ cascade: true })
  public children: Route[]

  @ManyToMany(type => Role, role => role.routes)
  @JoinTable()
  public roles: Role[]
}

A: I think the correct way to get the relations when is a tree entity is making:
await getManager().getTreeRepository(Route).findTrees({ relations: ["roles"] });

A: To load the children of a relation you can just add the property you want within the relations array like this:
RoleRepository.find({relations: ['routes', 'routes.roles']})

it should give you something like that:
"route": {
        "id": 1,
        "name": "route1",
        "roles": [{
                "id": 1,
                "name": "role1",
                "routes": [{
                        "id": 1,
                        "name": "route1"
                    }, {
                        "id": 2,
                        "name": "route2"
                    }
                ]
            }
        ]
    }


text:
Q: launch activity from service when notification is clicked I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;

import java.io.FileOutputStream;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;

public class contactBackup extends Service
{
    private NotificationManager nManager;
    private static final int NOTIFY_ID = 1100;

    @Override
    public void onCreate()
    {
        super.onCreate();

        String ns = Context.NOTIFICATION_SERVICE;
        nManager = (NotificationManager)getSystemService(ns);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        // inform user that service has started
        Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();

        String data = lookUpContacts();
        if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
        {
            Context context = getApplicationContext();

            // create the statusbar notification
            Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
            nIntent.setClass(context,contactViewer.class);
            //nIntent.putExtra("data",data);

            Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
            // start notification
            //PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
            PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
            msg.flags = Notification.FLAG_AUTO_CANCEL;
            msg.setLatestEventInfo(context,
                                   "success",
                                   "All contacts records have been written to the file.",
                                   pIntent);
            nManager.notify(NOTIFY_ID,msg);

        }

    }

    @Override
    public void onDestroy()
    {
        nManager.cancel(NOTIFY_ID);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    // function returns string containing information
    // from contacts
    public String lookUpContacts()
    {
        ...
    }

    public boolean saveToSDCard(String fileName, String data)
    {
        ...
    }

}

I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D

A: Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

This is because you're launching from outside your app (from the system notification bar).

A: This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by

A: Just add following in contactBackup(service class),
   Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
        nIntent.setClass(context,contactViewer.class);
         nIntent.putExtra("data",data);

  nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
        // start notification
        //PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
        PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
        msg.flags = Notification.FLAG_AUTO_CANCEL;
        msg.setLatestEventInfo(context,
                               "success",
                               "All contacts records have been written to the file.",
                               pIntent);
        nManager.notify(NOTIFY_ID,msg);

then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");


text:
Q: How to subquery Firebase Web App to Create a table I'm doing a basic e-commerce web platform, so the user can buy products, and in other page I want to show his product list, and the orders, what I mean is that a user can make one or more orders with 1 or more products.
the UID is the email.
this is my data structure
{
  "Orders" : {
    "-L-Nor4Ld1NNORxNToPI" : {
      "order" : [ {
        "cant" : "1",
        "product_id" : "1"
      }, {
        "cant" : "2",
        "product_id" : "5"
      }, {
        "cant" : "3",
        "product_id" : "8"
      } ],
      "status" : "pendiente",
      "total" : 795,
      "user_id" : "email@gmail.com"
    },
    "-L-UU03CNGSPd8o0UCHn" : {
      "order" : [ {
        "cant" : "2",
        "product_id" : "2"
      }, {
        "cant" : "1",
        "product_id" : "7"
      } ],
      "status" : "pendiente",
      "total" : 280,
      "user_id" : "email@gmail.com"
    },
    "any" : {
      "order" : {
        "product1" : {
          "cant" : 1,
          "product_id" : 1
        },
        "product2" : {
          "cant" : 1,
          "product_id" : 1
        }
      },
      "status" : "delivered",
      "total" : 100.01,
      "user_id" : "email@example.com"
    }
  },
  "Productos" : {
    "-L-JT-TaL5ctRQ-8u8NR" : {
      "price" : 35,
      "product_id" : 1,
      "product_name" : "Serie 100 luces (foco)",
      "stock" : 20
    },
    "-L-JTIcZ69uFkdUQbs8X" : {
      "price" : 75,
      "product_id" : 2,
      "product_name" : "Serie 100 luces (LED)",
      "stock" : 10
    },
    "-L-JTTi8VcLxkgT3RNuA" : {
      "price" : 70,
      "product_id" : 3,
      "product_name" : "Serie 140 luces musical (foco)",
      "stock" : 10
    },
    "-L-JTb0PwTyS8TiWS5W9" : {
      "price" : 96,
      "product_id" : 4,
      "product_name" : "Serie 140 luces musical (LED)",
      "stock" : 10
    },
    "-L-JUm5tF8fYBmR3BZCU" : {
      "price" : 110,
      "product_id" : 5,
      "product_name" : "Serie 300 luces color",
      "stock" : 10
    },
    "-L-JUzclafELx1xjpuQx" : {
      "price" : 135,
      "product_id" : 6,
      "product_name" : "Serie 300 luces blanca",
      "stock" : 10
    },
    "-L-JVB8diTZMmVS3ay1u" : {
      "price" : 130,
      "product_id" : 7,
      "product_name" : "Cascada 400 Luces",
      "stock" : 10
    },
    "-L-JVIgENEJRdcfLfKWT" : {
      "price" : 180,
      "product_id" : 8,
      "product_name" : "Manguera gel 10 metros",
      "stock" : 10
    }
  }
}

And you can see the project by yourself just login with google in  this link
Go To Project
once you have made your order, you can go to this link Order review Page
and you should see whats in your order, but that doesnt happens, I want to do something like this
Get logged user_id then get user_id orders(order_id), then show in (if) multiple tables with
|Product |Price| Quantity| sub(price*quant)
And its products
So as you can see in the code of cart.html im using
ref.orderBy(X).equalTo(uid).on("child_added",function(data){
    ref.orderBy(Y).equalTo(item).on("child_added",function(data2){
        //dothings create table content
    })
    //close table content
})
//embed table content created.

so I want to show a the table but .then() function doesnt work and the same with .done() , i hope you can help me to understand how should I subquery, to get the user orders in a table

A: My solution was not to get values by inner firebase functions, it was getting all the data, then create the table with the data
The next code suppose that productsObj, and ordersObj are the result objects of my firebase database products and orders.
so the next thing i did was to create dynamically the table with this function.
You cannot create subqueries or something like that on firebase functions like on child_added, child_removed, etc..
function productList(){

    if(ordersObj.length != 0 & productsObj.length == 8){
        //console.log("si termino");
        $.each(ordersObj,function(index, data){
            var table =('
');
            var tableHead = ("

Producto	Precio	Cantidad	Importe
");
            table+=tableHead;
            //console.log(table);
            var tableBody = ("");
            //console.log(tableBody)
            var total = 0;
            $.each(data.order,function(idx, ord){
                console.log(ord.product_id);
                //console.log("precio:"+productsObj[ord.product_id-1].price);
                var subtotal = ord.cant*productsObj[ord.product_id-1].price;
                //console.log("despues del subtotal")
                var row = ('
'+productsObj[ord.product_id-1].product_name+'	'+productsObj[ord.product_id-1].price+'	'+''+ord.cant+'	'+''+subtotal+'
');
                //console.log(row);
                total=data.total;
                tableBody+=(row);
            });
                //console.log(tableBody.html());
                //console.log(tableHead.html());
            tableBody+=("
Total	"+total+"

");
            table+=tableBody;
            //console.log(table);
            //table.append(tableHead.html());
            $('#content').append(table);
            $('#content').append("
");
        });

    }
    else{
        //productList();
    }

}


text:
Q: Django Inlines and DateTimeField I'm trying to create simple Event app, so I've decided to create event and some inline event occurances:
class EventOccurenceInline(admin.TabularInline):
    model = models.EventOccurance
    form = forms.EventOccuranceForm
    pass

class EventAdmin(TranslatableAdmin):
    list_display = [ "internal_name"]
    inlines = [
        EventOccurenceInline,
    ]
    pass

and here is forms.py:
class EventOccurenceForm(TranslatableModelForm):
    start_date = forms.DateTimeField()
    end_date = forms.DateTimeField()
    class Meta:
        model = models.EventOccurence

But, when I open my backend I see only simple inputs instead of DateTime pickers, and even labels for those fields say nothing:

Does anyone know how to use those widgets inside inlines? What am I doing wrong?
thanks in advance,
Michael

A: It looks like the problem is that you're declaring the start_date and end_date fields in the EventOccurenceForm class without any arguments.
Here is a quote from Django's "Creating forms from models" documentation in the Overriding the default field types or widgets section:

If you explicitly instantiate a form field like this, Django assumes
  that you want to completely define its behavior; therefore, default
  attributes (such as max_length or required) are not drawn from the
  corresponding model. If you want to maintain the behavior specified in
  the model, you must set the relevant arguments explicitly when
  declaring the form field.

Why are you declaring the start_date and end_date fields in the EventOccurenceForm class, anyway? Is it because you're trying to only have those two fields in the form? If that's the case, you should use the fields attribute of the inner Meta class instead.
I'm assuming the EventOccurence model's start_date and end_date fields are DateFields and, thus, within Django admin, they will have the AdminDateWidget widget by default. If, for some reason, that isn't the case and you can't change the model, you could always use the widgets attribute of the EventOccurenceForm class's inner Meta class, like this:
from django.contrib.admin.widgets import AdminDateWidget

class EventOccurenceForm(TranslatableModelForm):
    class Meta:
        model = models.EventOccurence
        widgets = {
            'start_date': AdminDateWidget,
            'end_date': AdminDateWidget,
        }


text:
Q: Can an ISO file damage—or infect—the machine it's being burned on? I'm wondering if an ISO file can do damage—or infect the system— that it's being burned on.
Something like the Zip Slip Vulnerability or similar.
I really want to burn an ISO to a disc, but I can't scan the file with my Anti-Virus since the file's too big.

A:
I'm wondering if an iso file can do damage to the main machine while it's burning, like the zip slip vulnerability or something.

It certainly is possible that there is a vulnerability that affects the ISO file format, but if it exists it certainly hasn't been discovered, even if it did exist it's even more unlikely it would affect the file format while the contents of the ISO was being written to the disk.

I really want to burn an ISO to a disc, but I can't scan the file with my Anti-Virus since the file's too big.

In my experience, most modern security software can actually scan the contents, of an ISO file.  If you cannot scan the contents of the ISO then I suggest using different security software.  If you are using Windows 8+, you can mount the disk from within Windows, and scan the read-only contents of the disk.
If you do not trust the source of the file you should delete it immediately.

A: Burning an ISO to a target device alone will not expose your system to damage or infection.
Never heard of the Zip Slip Vulnerability before, but reading up on it it describes the exploit—which has never existed in the real world beyond theoretical discovery—as follows:

Zip Slip is a form of directory traversal that can be exploited by extracting files from an archive. The premise of the directory traversal vulnerability is that an attacker can gain access to parts of the file system outside of the target folder in which they should reside.

On a basic level, it means that a malicious Zip file would need to be created to explicitly do some directory traversal into deeper parts of the system on the target machine. I would assume that such an exploit would also need admin privileges to be effective; meaning simple creating a Zip file that would target a restricted binary directory is not enough. Without admin rights, the effort would be inherently blocked.
But that is all dependent on a Zip file residing on a target system and then being executed with admin rights. Two massive "ifs" that most likely would never happen.
In the case of an ISO, all that is is a disc image—either compressed or not—that then gets written to a target device. I can't recall any disc burning software that requires admin access, so there is one safety net. Next, even if the ISO is compressed it would only be able to really "traverse" the target volume. Which is most cases is a blanked out device. So it's really a non issue if you ask me.
Of course the real risk is if you boot from that burned ISO and then all of the sudden it controls your system. But your question is about the burning process—and booting from an unknown device is a well known risk—and I cannot see burning an image to any device be a risky endeavor.


text:
Q: What does this statement in a English book mean?
"......This book is sold subject to the conditions that it shall not,
  by way of trade or otherwise, be lent, re-sold, hired out or otherwise
  circulated without the publisher's prior consent in any form of
  binding or cover other than that in which it is published."

I'm a Asian English student and It's too long for me to understand its meaning, please simplify it so that I can understand it, thanks!

A: It says that you can't remove or replace the cover of a book and then sell it.
This bit of "legalese" is explained by a feature of the publishing industry.
A book publisher needs to get his books into bookshops. To encourage bookshops to stock their books, the publisher sells them on a "sale or return" basis.
The publisher sends his books to the publisher. The bookshop pays for the books, but if any books remain unsold, the bookshop can return the books to the publisher for a refund.
Returned books will be destroyed. It is standard practice for the bookshop to save on postage by not returning the whole book, but only the cover. The bookshop will then destroy the remainder of the book.
The requirement not to sell under a different cover is to prevent a corrupt bookshop from removing the cover, returning the cover to the publisher for the refund, putting a new cover on the book and selling it.
This is directed at bookshops, not the final buyer of the book.

A: Well first I would say that this is "lawyer speak".  Some weirdly worded sentence changed over time and and meant to only be understood by lawyers.
Second, I am not a lawyer and this is not legal advice
Let's break it down.

"This book is sold subject to the conditions that it shall not"

here are some rules about the book.  You can't do this stuff.

"by way of trade or otherwise, be lent, re-sold, hired out or otherwise circulated"

You can't see this book or anything like that if...

"without the publisher's prior consent"

unless the people who made this book say otherwise

" any form of binding or cover other than that in which it is published"

If you change what it looks like.
So to summarise...
Don't sell this book changing what it looks like unless we give you permission

A: The main clause is a simple sentence plus an appositive clause, and the other components are all adverbial. Let us split this long sentence into several short sentences and explain their logical relationship.
This book can be sold only under these conditions ('that it shall not......' is the apposition of 'conditions'). The conditions are: if you did not get the permission of the publisher you can not sell, lent, .. (all kinds of trade and circulation).
'In any form of binding or cover......' is the adverbial of 'trade and circulation' to point out that even in different forms the 'trade and circulation' are still forbidden.
'That in which it is published......' is a noun phrase after 'other than' which has an adverbial clause after 'that'. The meaning is: the book in the form of being published can be traded and circulated to others ('subsequent purchaser'), but meanwhile you should have the permission (without this condition).


text:
Q: Using Marklogic 8 triggers for managed triples I have a use case where I want to send a notification every time triples are added or deleted from MarkLogic. The notification should contain those triples and should say whether they were added or deleted.
I didn't find any mention in the MarkLogic triggers guide regarding how it might work with (managed) triples. Is there a way to write a trigger module so that for a modified document (containing the managed triples), compare the new version with the old version to work out what's added and deleted and send a HTTP request containing these changes?
I understand that doc($trgr:uri) will give me the latest state of the document in question - but is there a way to retrieve the previous version, before the change? I'm fairly new to MarkLogic and Xquery so some guidance is much appreciated. Thanks!

A: I think you can only achieve this in one way:

*

*use pre-commit triggers

*use xdmp:eval with isolation for different-transaction to get the original document

Something like:
xquery version "1.0-ml";

import module namespace trgr = "http://marklogic.com/xdmp/triggers" at "/MarkLogic/triggers.xqy";

declare variable $trgr:uri as xs:string external;

xdmp:log("Triggered processing of " || $trgr:uri || ".."),

xdmp:log(xdmp:eval('doc("'||$trgr:uri||'")', (), <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)),
xdmp:log(doc($trgr:uri))

I ran a quick test with a trigger scoped for collection 'test'. I then inserted a doc at /test.xml with contents <test>a</test>, and did NOT add it to collection test yet. I then updated the document with <test>b</test>, and also added it to collection test to activate the trigger. It logged a and b..
This shows how you can get both original and updated document. Determining the difference is a challenge on its own..
HTH!

A: Many thanks to @grtjn for providing the way to access the pre-change document. For determining the difference between documents I found a way inspired by this blog post. The solution that I found to be working looks like this:
xquery version '1.0-ml';
import module namespace trgr='http://marklogic.com/xdmp/triggers' at '/MarkLogic/triggers.xqy';

declare function local:diff($seq1 as item()*, $seq2 as item()*) as item()* {
    let $map1 := map:new($seq1 ! map:entry(fn:string(.), .))
    let $map2 := map:new($seq2 ! map:entry(fn:string(.), .))
    return map:keys($map1 - $map2) ! map:get($map1,.)
};

declare variable $trgr:uri as xs:string external;
declare variable $after := doc($trgr:uri)/sem:triples/sem:triple;
declare variable $before := xdmp:eval('doc("'||$trgr:uri||'")', (),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>)/sem:triples/sem:triple;

declare variable $added_triples := local:diff($after, $before);
declare variable $added_graph := xdmp:document-get-collections($trgr:uri);

declare variable $deleted_triples := local:diff($before, $after);
declare variable $deleted_graph := xdmp:eval('xdmp:document-get-collections("'||$trgr:uri||'")', (),
    <options xmlns="xdmp:eval"><isolation>different-transaction</isolation></options>);

xdmp:log(fn:concat('***** Trigger processing:  ', $trgr:uri, '*****')),
xdmp:log('***** added triples *****'),
xdmp:log($added_graph),
xdmp:log($added_triples),
xdmp:log('***** deleted triples *****'),
xdmp:log($deleted_graph),
xdmp:log($deleted_triples)

I created 3 pre-commit triggers, one for each of the trgr:document-content options: create, modify and delete, all invoking the above module. A SPARQL Update query will cause the above module to trigger one or more times, printing the lists of triples which were added and deleted.
Couple of observations:

*

*A single SPARQL Update statement can create, modify and delete multiple documents, so will trigger the module multiple times.

*INSERT statements seem to always create new documents, so you'll will never get added triples and deleted triples in the same invocation.

*The code assumes there's only one collection for a document, which is the named graph for managed triples. It will need extra work if there are to be multiple collections per document.


text:
Q: Thunking - Windows 7 I am trying to write a very simple thunk that can be used from 16bit FoxPro to ultimately call a 64bit shiny WCF client.
I know I can't pass complex data types between them so I just want to pass a file name that data will be written to.
Problem is I can't even get the thunk to work. I am starting with
http://www.codeproject.com/Articles/29727/Generic-Thunk-of-Windows
but the call to
ghKernelDll = LoadLibrary("kernel.dll");

returns null. if i put kernel32 in there is it ok but that is to be expected - right? is it because I am running this application on my shiny 64 desktop? What do I need to be able to make this work?
Thank you!

A: Well, it might have something to do with the fact that 16-bit code doesn't run on 64-bit versions of Windows. In fact, to the best of my knowledge, kernel.dll doesn't even exist in 64-bit Windows.


text:
Q: How to detect if a MySql query was successful or not and output a message? I am making a library management system using C#. For example I have a form to add a book. Once you input all the details and run the query to add books to the database, I wish to know how you can detect if the query was successful or not and output a message.
Form Code:
private void btnSubmit_Click(object sender, EventArgs e)
    {
        string isbn = txtISBN.Text;
        string title = txtbkTitle.Text;
        string author = txtbkAuthor.Text;
        string publisher = txtbkPublisher.Text;
        string imgPath = txtimgPath.Text;
        string catalog = txtCatalog.Text;

        book bc = new book(isbn, title, author, publisher, imgPath, catalog);
        utility = new DBUtlitiesBook();

        utility.Insert(bc);
    }

This code takes all the details of user entries, store them in variables and send them to the a method which have the insert query.
This is the method:
public override void Insert(object ob)
    {

        book bk = (book)ob;
        string isbn = bk.Isbn;
        string title = bk.Title;
        string author = bk.Author;
        string publisher = bk.Publisher;
        string localPath = bk.Imgpath;
        string catalogid = bk.CatalogID;

        MySqlConnection connection = new MySqlConnection(conn);
        MySqlCommand cmd;

        try
        {
            connection.Open();
            cmd = connection.CreateCommand();
            cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES ('" + isbn + "','" + title + "','" + author + "','" + publisher + "','" + localPath + "','" + catalogid + "')";
            cmd.ExecuteNonQuery();
        }

        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();

            }
        }
    }

(This method overrides another method which is in the parent class)
Can you help me solve my problem?
Thanks

A: you can use below menioned code
try
        {
            connection.Open();
            cmd = connection.CreateCommand();
            cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES ('" + isbn + "','" + title + "','" + author + "','" + publisher + "','" + localPath + "','" + catalogid + "')";
            int a= cmd.ExecuteNonQuery();
             if(a>0)
               //updated.
             else
              //Not updated.
        }
catch (Exception)
        {
           //Not updated.
        }

A: If I understand correctly, for INSERT statement, ExecuteNonQuery returns the count of the row affected. That's why you can check it like;
int rowCount = cmd.ExecuteNonQuery();

if(rowCount == 1) //or you can use > 0
{
   //Successful
}
else
{
  //Unsuccessfull
}

By the way please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your MySqlConnection and MySqlCommand.
using(MySqlConnection connection = new MySqlConnection(conn))
using(MySqlCommand cmd = connection.CreateCommand())
{
    cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES (@isbn, @title, @author, @publisher, @path, @id)";
    ...
    //Add your parameter values one by one.
    connection.Open();
    int rowCount = cmd.ExecuteNonQuery();

    if(rowCount == 1) //or you can use > 0
    {
       //Successful
    }
    else
    {
      //Unsuccessfull
    }
}

A: ExecuteNonQuery retuns the an int indicating the number of rows affected. So, it will return zero if nothing was done. You can have a boolean condition on its return value and return a message or the value itself. You will have to probably modify the parent class so that re can have a return value.

A: Errors are indicated by Exceptions that are thrown when using the MySql connector library. You should not rethrow the Exception if you want to handle the failure.
You also don't want to catch all exceptions and handle them at once. Instead, just catch just the MySqlException. I'm not sure in which namespace the class lives, you'll have to locate this by yourself.
catch (MySqlException exception)
{
    // handle the error, show some message
}


text:
Q: Fixing arrow angle How can I set the small arrow straight?
\documentclass[border=7pt]{standalone}
\usepackage{forest}
\usetikzlibrary{arrows.meta,
    chains,
    fit,
    positioning}
\usepackage{siunitx}
\tikzset{
    node distance = 2mm and 0mm,
    start chain = A going below,
    wbox/.style = {draw, text width=8*1.3 em, inner sep=1mm,
        on chain, node contents={}},
    gbox/.style = {draw, fill=lightgray, text width=1em,
        inner xsep=0mm, inner ysep=1mm,
        node contents={}},
    every label/.append style = {font=\footnotesize}
}
\begin{document}
    \begin{forest}
        for tree = {
            draw,
            minimum height=4ex,
            text depth=0.5ex,
            anchor=north,
            inner sep=1mm,
            tw/.style = {text width=#1*1.3 em},
            text centered,
            %
            s sep=1em,
            l sep=8ex,
            edge={-{Triangle[angle=60:2pt 3]}},
            edge path={
                \noexpand\path[\forestoption{edge}]
                (!u.south) -- (.north);
            },
        }
        [$\mathcal{D}_{blblblblbl}$  \SI{100}{\%}, tw=10,
        [$\mathcal{D}_{blblblblbl}$   \SI{80}{\%}, tw=8, name=DS]
        [$\mathcal{D}_{blblblb}$ \SI{20}{\%},tw=5]
        ]
        \node [wbox, below=4.5mm of DS, label=left:1];    % A-1
        \foreach \i [count=\j from 2] in {2,3,4,k}
        {
            \ifnum\j=4
            \node [wbox, draw=none, label={[yshift=0.8ex]center:$\vdots$}]; % A-5
            \else
            \node [wbox, label=left:$\i$]; % A-2, ..., A-4
            \fi
        }
        \foreach \i [count=\j from 0]in {1,2,3,5}
        {
            \ifnum\i=5
            \node [gbox, left =of A-\i.east];
            \else
            \node [gbox, right=\j em of A-\i.west];
            \fi
        }
        \node (n6)  [draw=black, rounded corners, dashed,
        inner xsep=1em, xshift=-0.5em,
        fit=(A-1) (A-5),
        label=right: Blalalalalalallalalalal] {};
        \draw[-{Triangle[angle=60:2pt 3]}] (DS) -- (n6);
    \end{forest}
\end{document}

A: Just replace the last line before \end{forest} by
\draw[-{Triangle[angle=60:2pt 3]}] (DS.south) -- (DS.south|-n6.north);

Here, (DS.south|-n6.north) means the x component of DS.south, i.e. the starting point of the arrow, and the y component go n6.noerth.
\documentclass[border=7pt]{standalone}
\usepackage{forest}
\usetikzlibrary{arrows.meta,
    chains,
    fit,
    positioning}
\usepackage{siunitx}
\tikzset{
    node distance = 2mm and 0mm,
    start chain = A going below,
    wbox/.style = {draw, text width=8*1.3 em, inner sep=1mm,
        on chain, node contents={}},
    gbox/.style = {draw, fill=lightgray, text width=1em,
        inner xsep=0mm, inner ysep=1mm,
        node contents={}},
    every label/.append style = {font=\footnotesize}
}
\begin{document}
    \begin{forest}
        for tree = {
            draw,
            minimum height=4ex,
            text depth=0.5ex,
            anchor=north,
            inner sep=1mm,
            tw/.style = {text width=#1*1.3 em},
            text centered,
            %
            s sep=1em,
            l sep=8ex,
            edge={-{Triangle[angle=60:2pt 3]}},
            edge path={
                \noexpand\path[\forestoption{edge}]
                (!u.south) -- (.north);
            },
        }
        [$\mathcal{D}_{blblblblbl}$  \SI{100}{\%}, tw=10,
        [$\mathcal{D}_{blblblblbl}$   \SI{80}{\%}, tw=8, name=DS]
        [$\mathcal{D}_{blblblb}$ \SI{20}{\%},tw=5]
        ]
        \node [wbox, below=4.5mm of DS, label=left:1];    % A-1
        \foreach \i [count=\j from 2] in {2,3,4,k}
        {
            \ifnum\j=4
            \node [wbox, draw=none, label={[yshift=0.8ex]center:$\vdots$}]; % A-5
            \else
            \node [wbox, label=left:$\i$]; % A-2, ..., A-4
            \fi
        }
        \foreach \i [count=\j from 0]in {1,2,3,5}
        {
            \ifnum\i=5
            \node [gbox, left =of A-\i.east];
            \else
            \node [gbox, right=\j em of A-\i.west];
            \fi
        }
        \node (n6)  [draw=black, rounded corners, dashed,
        inner xsep=1em, xshift=-0.5em,
        fit=(A-1) (A-5),
        label=right: Blalalalalalallalalalal] {};
        \draw[-{Triangle[angle=60:2pt 3]}] (DS.south) -- (DS.south|-n6.north);
    \end{forest}
\end{document}

The reason why the arrow was not vertical in the first place is that you added the numbers left of the wbox nodes. Therefore the centers of the fit and DS do not coincide.


text:
Q: Image in ImageIcon does not show in Linux, but it does in Windows When I open it in windows, all the images are perfectly seen, but when I open it in Linux, only the blank window is seen. I think it's because of the paths. It should be noted that I am trying to access an image that is in a package called "img". what's the problem?. This happens when the project is already packaged.
JLabel label = new JLabel(new ImageIcon(getClass().getResource("/img/image.png")));

A: In order to make it work in both Linux and Windows, you need to do the following:
JLabel label = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/image.png"))));

actually what matters is this:
Toolkit.getDefaultToolkit (). getImage (getClass (). getResource ("/ img / image.png")).

It worked perfectly for me


text:
Q: How to pass in navigation props into a functional component screen through React Navigation? I have a functional component screen with a React Native FlatList of custom "Tasks". I want to be able to navigate from a task to another functional component, "TaskEditScreen" and pass some props to the screen as well.
<TouchableOpacity onPress={()=>{navigation.navigate('Task Edit')}}>
   <Feather
      name="edit"
      size={35}
      color="black"
      style={{
         margin: 5
      }}
   />
</TouchableOpacity>

The onPress function works and it navigates me to the correct screen, but how do I also pass in some kind of props or data to this screen?

A: Documentation: https://reactnavigation.org/docs/params
<TouchableOpacity onPress={() => { navigation.navigate('Task Edit', {someParam: "someValue"}) }}>
  <Feather
    name="edit"
    size={35}
    color="black"
    style={{
      margin: 5
    }}
  />
</TouchableOpacity>


text:
Q: Antichains and weighted sums Given an antichain $S_1,S_2,\dots,S_m$ of subsets of $\{1,2,\dots,n\},$ does there always exist positive integers $x, y_1,\dots,y_n$ so that for $i=1,\dots,m$ we have:
$$\sum_{k\in S_i} y_k =x\tag 1$$
(Antichain means that for for $i\neq j,$ we have $S_i\not\subseteq S_j.$)
Just a question that occurred to me while working on another problem.
Certainly, given $x,y_1,\dots,y_n,$ the set
$$\mathcal A =\left\{S\subseteq\{1,\dots,n\}\mid \sum_{k\in S} y_k =x\right\}$$ is an antichain, so this question asks if all antichains are a subset of an antichain of the form $\mathcal A.$

A: This is not true.
Counterexample
Let $n=5$ and $$\mathcal A=\{45,123,124,125,134,135,234,245\}
$$
By the symmetry of $\mathcal A,$ we can see that if there is a solution $x,y_1,\dots,y_5,$ there is a solution with $y_1=y_2=y_3$ and $y_4=y_5.$
But then $x=3y_1=2y_1+y_4=2y_4.$ The second equality means $y_1=y_4$ while the third equality means that $2y_1=y_4.$ This means $y_1=y_4=0,$ violating the requirement that the $y_i$ are positive.