text:
Q: how to find out which file contains a javascript function I've taken over a project which involves a lot of javascript (AJAX and whatnot).  In tracking down functions, is there a way to find out which included .js file contains a specific function?
I'm hunting through Firebug but can't find where it isolates the specific file which contains the javascript function.  What am I missing?

A: The Web Developer plugin (for FF and Chrome http://chrispederick.com/work/web-developer/) has a "View JavaScript" feature that shows all of the JS that a page is referencing on a single page.  CTRL-F from there to find the function.

A: Fiddler will let you search through all requests, so you could load the page in Fiddler, then search for your function.
http://www.fiddler2.com/fiddler2/

A: Certain text editors, including Notepad++, allow you to search all files in a directory. You can use that to search for "function foo(" and that should pull it up.
Of course, that assumes the function is declared like that. It could also be assigned, which would be a bit more difficult. You'd have to search for something like "foo\s*=" (using Regex search).


text:
Q: Lightgbm OSError, Library not loaded If I simply do:
import lightgbm as lgb

I'm getting
python script.py
Traceback (most recent call last):
File "script.py", line 4, in <module>
import lightgbm as lgb
File "/usr/local/lib/python2.7/site-packages/lightgbm/__init__.py", line 8, in <module>
from .basic import Booster, Dataset
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 31, in <module>
_LIB = _load_lib()
File "/usr/local/lib/python2.7/site-packages/lightgbm/basic.py", line 26, in _load_lib
lib = ctypes.cdll.LoadLibrary(lib_path[0])
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 440, in LoadLibrary
return self._dlltype(name)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 362, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(/usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib
Referenced from: /usr/local/lib/python2.7/site-packages/lightgbm/lib_lightgbm.so
Reason: image not found

I seem to have everything installed correct:
python -m pip install lightgbm
Requirement already satisfied: lightgbm in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: wheel in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scikit-learn in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: scipy in /usr/local/lib/python2.7/site-packages (from lightgbm)
Requirement already satisfied: numpy in /usr/local/lib/python2.7/site-packages (from lightgbm)

I do have a 6 folder in my GCC folder.  Should I need to install another version of GCC for this to work?

A: All the above answers didn't work for me.
On Mac, if I installed the libomp using brew fixed the problem: Refer: link
brew install libomp

A: On MAC you need to install open-mpi:
brew install open-mpi

A: Same error, different source: seems like I had the gcc 8 version installed, and it needs gcc 7.
It worked by switching it back to last gcc 7 version:
brew switch gcc 7.3.0_1

A: I find a similar problem here LightGBM
The answer and comment may help you.
Build LightGBM in Mac:
brew install cmake
brew install gcc --without-multilib
git clone --recursive https://github.com/Microsoft/LightGBM ; cd LightGBM
mkdir build ; cd build
cmake ..
make -j

Then install:
cd ../python-packages
sudo python setup.py install --precompile

As stated by @ecodan, you might need to force Mac to use GCC and G++ instead of the default compiler. So instead of building with cmake .., try:
cmake -DCMAKE_C_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/gcc-6 -DCMAKE_CXX_COMPILER=/usr/local/Cellar/gcc/6.1.0/bin/g++-6 ..

ajusting the versions to match yours.

A: I had the same exact problem on M1 MAC. I have tried to import it through Jupiter notebook. This command solved the problem:
conda install lightgbm

A: For users with macports, replace the beginning of the brew solution with:

*

*port install gcc7 cmake

*export CXX=g++-mp-7 CC=gcc-mp-7

A: On MacOS High Sierra with MacPorts installed, I did the following:

*

*Install clang-5.0 using MacPorts

*Inside the /build directory, run
cmake -DCMAKE_CXX_COMPILER=clang++-mp-5.0 -DCMAKE_C_COMPILER=clang-mp-5.0 ..

*To build the python package, go to /python_package directory and modify the setup.py script.
You need to modify the function compile_cpp() at the very end that checks the case for other OS (including Mac). Before the silent_call(...), add the following two lines:

cmake_cmd.append("-DCMAKE_CXX_COMPILER=clang++-mp-5.0")
cmake_cmd.append("-DCMAKE_C_COMPILER=clang-mp-5.0")

*Run sudo python setup.py install. Enjoy

A: I used this command generated from PyCharm and it worked for me.
conda install -p { < =replace with USER_HOME_DIR>}/anaconda3 lightgbm -y
Note : i tried Brew and pip install but they didn't work for me as Azure ML studio already downloaded other versions of LightGBM that were causing conflict in upgrading to correct packages.

A: conda install -c conda-forge lightgbm

redpajama_set_name: RedPajamaStackExchange


text:
Q: Owl-Carousel Free Slide Move I'm trying to put the Owl-Carousel to work with free items pushing, with total controller of the user, but the items is moving to the border when the user slide it..
Example:
Item 1 - Item 2 - Item 3 - Item 4(only half is showing)...

So i want to push only a little, and it's happening:
Item 2 - Item 3 - Item 5(only half is showing)...

I want to total control of carousel, to if i push just a little, show like this:
Item 1(only half) - item 2 - item 3 - item 4

I tried to clear my question most possible, i just want to the items don't go to the border even if the user push just a little of the carousel..
My config is that:
      <script>
            $('.owl-carousel').owlCarousel({
                margin:12,
                checkVisible: false,
                loop: true,
                responsive:{
                    0:{
                        items:3,
                        margin:4,
                        autoWidth:false,
                    },
                    426:{
                        items:3,
                        margin:8,
                    },
                    600:{
                        items:2,
                        margin:8,
                    },
                    700:{
                        items:4,
                        margin:12,
                        autoWidth:true,
                    },
                }
            });
        </script>

I tried freeDrag and pullDrag options but doesn't work as expected..


text:
Q: Assign values from file 1 to file 2 in python I have two text files.
Text file 1:  0=0.345,1=34.5,2=54.6,3=235.67
Text file 2 : (0+2)*(3+2)
Is there a python operation that will assign the corresponding numbers from text file 1 to text file 2? I am doing my computations in text file 2
Thanks!

A: Assuming data in both files is similar to the one you provided, you can store assignments from the first file in the dictionary and then map them into the equation from the second file.
with open("file1.txt", "r") as f:
    file1 = f.read() # file1 = "0=0.345,1=34.5,2=54.6,3=235.67"
with open("file2.txt", "r") as f:
    file2 = f.read() # file2 = "(0+2)*(3+2)"

variables = {}
for equation in file1.split(","):
    var, value = equation.split("=")
    variables[var] = value
# variables = {'0': '0.345', '1': '34.5', '2': '54.6', '3': '235.67'}

operation = [variables.get(letter, letter) for letter in file2]
exec("result = " + "".join(operation)) # result = (0.345+54.6)*(235.67+54.6)
print(result) # 15948.885149999998


text:
Q: Kubuntu - bluetooth device disappeared My bluetooth device stopped being detected (maybe because of an update). When I want to access the Bluetooth settings it says that no device is available.
It is the same with hcitool scan in the terminal:
Device is not available: No such device

and I don't see it with lsusb:
Bus 004 Device 002: ID 8087:8000 Intel Corp.
Bus 004 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 002: ID 8087:8008 Intel Corp.
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 006: ID 045e:0084 Microsoft Corp. Basic Optical Mouse
Bus 001 Device 009: ID 04f2:b35a Chicony Electronics Co., Ltd
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

How can I fix it? I am running Kubuntu 15.10.

A: Before posting this issue I tried several reboots without any improvements. However, my Bluetooth device strangely reappeared in the bottom panel this morning and works properly again. This is very strange since I don't think I have changed anything in the settings, but the problem is finally solved anyway.
The problem left the way he came.


text:
Q: ARC not freeing original asset after CGCreateWithImageInRect? High level summary:
I would like to replace the rather low resolution ALAsset Group images [group posterImage] with a higher quality version so that they can be shown larger on the screen.  Normally I would load them as needed by the interface, but [ALAssetsGroup enumerateAssetsAtIndexes] is very slow.  (I COULD preload wider than visible by x amount and may still do that, but that seemed like more hassle than it was worth and still suffers from the slow response, especially in iOS5)
What I figured I could do was request the first asset in each group and then scale it, storing the result.  However, even accounting for the larger size of the images, I am surprised by the memory allocations that are taking place.  Using VM Tracker, I see a LARGE number of CGImage allocations as well as the 'mapped file' thumbnails I am creating.  I am using ARC, so I expected the original large images to drop out, but my VM Tracker results don't bare that out.
If I use the default posterImage implementation, my Resident Mem ~= 30mb, Dirty Mem ~= 80mb and Virtual tops ~240mb (large in themselves).  'Live' < 10mb per the Allocation profiler.
If I use the following code instead, I crash loading the ~80th image out of 150.  At that point my Resident Mem > 480mb, Dirty Mem > 420mb and Virtual was a whopping 750mb.  Clearly this is untenable.
Here is the code I am using inside of an NSOperationQueue to grab the first image of each group to use as a hi-res poster image.
NSIndexSet* i = [NSIndexSet indexSetWithIndex:0];
ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger i, BOOL *stop) {

  if (result) {
     // pull the full resolution image and then scale it to fit our desired area
     ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];
     CGImageRef ref = [assetRepresentation fullScreenImage];
     CGFloat imgWidth = CGImageGetWidth(ref);
     CGFloat imgHeight = CGImageGetHeight(ref);
     CGFloat minDimension = MIN(imgWidth,imgHeight);

     // grab a square subset of the image, centered, to use
     CGRect subRect = CGRectMake(0, 0, minDimension, minDimension);
     subRect.origin = CGPointMake(imgWidth / 2 - minDimension / 2, imgHeight / 2 - minDimension / 2);
     CGImageRef squareRef = CGImageCreateWithImageInRect(ref,subRect);
     // now scale it down to fit
     CGFloat heightScale = dimension / minDimension;
     UIImage* coverImage = [UIImage imageWithCGImage:squareRef scale:1/heightScale orientation:UIImageOrientationUp];

     if (coverImage) {
        [mainViewController performSelectorOnMainThread:@selector(imageDidLoad:)
                                             withObject:[NSArray arrayWithObjects:coverImage, [NSNumber numberWithInt:photoIndex], nil]
                                          waitUntilDone:NO];
     }
     CGImageRelease(squareRef);
     // DO NOT RELEASE 'ref' it will be 'zombied' as it is already handled by the system
     //CGImageRelease(ref);

     *stop = YES;
   }
   else {
      // default image grab....
   }
};
[group enumerateAssetsAtIndexes:i options:NSEnumerationConcurrent usingBlock:assetsEnumerationBlock];

Am I doing something wrong with the above or am I just not being smart by loading all of the images?  The more I think about it, the more I think loading a window of visible images plus a buffer around it is the way to go, but I would like to learn more about what I may have done wrong with the above code.
Thanks!

A: I did the exact same thing as you but thanks to this answer: Fetching the last image captured through iPhone camera , I managed to make it a lot faster and not draining as much memory.
This of course makes the images a lot smaller since you don't fetch the fullScreenImage and just a thumbnail of it..
My final code:
   ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

    // Within the group enumeration block, filter to enumerate just photos.
    [group setAssetsFilter:[ALAssetsFilter allPhotos]];
    int nrOfPhotos = 200;
    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, nrOfPhotos)]
                            options:0
                         usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {

                             // The end of the enumeration is signaled by asset == nil.
                             if (alAsset) {
                                 NSLog(@"Index: %i", index);

                                 CGImageRef imageRef = [alAsset thumbnail];
                                 UIImage *latestPhoto = [UIImage imageWithCGImage:imageRef scale:1.f orientation:UIImageOrientationUp];

                                 //Do something with images

                         }
                         }];
}
                     failureBlock: ^(NSError *error) {
                         // Typically you should handle an error more gracefully than this.
                         NSLog(@"No groups");
                     }];


text:
Q: LostFocus does'nt work TextBox when selecting a TreeviewItem Hi I need to solve a problem between the TextBox and the treeview. When I select the TreeView after the TextBox I don't receive the LostFocus Event (for the TextBox) why?
I have tried to play a lot with Focusable and the focusableManager but .... it didn't helped me.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Visibility="{Binding VariableA, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BoolToHiddenConverter}}

<TextBox Width="78" FocusManager.IsFocusScope="True"
    PreviewTextInput="HatchingDistanceBox_PreviewTextInput"
    Name="TextBoxAWhoShouldLostFocus" BorderThickness="0.5"
    BorderBrush="White" MinHeight="30" Height="30" Text="{Binding SelectedFamille.VariableA}"
    utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text">
</TextBox>

<TreeView  Name="TreeView_After" ItemsSource="{Binding FirstGeneration}" Focusable="True"   Grid.ColumnSpan="3" Grid.Row="2" Grid.Column="0" AllowDrop="True" Background="#282828" Margin="15, 0,0,0" >
    <TreeView.Style>
        <Style TargetType="{x:Type TreeView}">
            <EventSetter Event="GotFocus" Handler="TreeViewItem_GotFocus"></EventSetter>
        </Style>
    </TreeView.Style>

    <i:Interaction.Behaviors>
        <utilities:TreeViewSelectionBehavior SelectedItem="{Binding SelectedFamille}"/>
    </i:Interaction.Behaviors>
    <TreeView.Resources>
        <DataTemplate x:Key="NormalTemplate">
            <StackPanel Orientation="Horizontal" Name="StrategyNamePanel" Mouse.PreviewMouseDown="StrategyNamePanel_MouseDown"   Width="200" Background="#282828" Focusable="True" FocusManager.IsFocusScope="True">
                <TextBox  Name="StrategyNameBox" FontWeight="Normal"  FocusManager.IsFocusScope="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=Explicit}"  MinHeight="30" Height="30" BorderThickness="0"  utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"></TextBox>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="EditTemplate">
            <StackPanel  Orientation="Horizontal" Name="NamePanel" Focusable="True" Mouse.PreviewMouseDown="NamePanel_MouseDown"  Width="200" Background="{StaticResource DarkGrey}" FocusManager.IsFocusScope="True">
                <TextBox Name="NameBox" FontWeight="Normal" BorderBrush="{StaticResource DarkOrange}"  FocusManager.IsFocusScope="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=Explicit}" MinHeight="30" Height="30"  utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text" ></TextBox>
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <EventSetter Event="GotFocus" Handler="TreeViewItem_GotFocus"></EventSetter>
            <EventSetter Event="TreeViewItem.DragOver" Handler="TreeView_After_DragOver"/>
            <EventSetter Event="TreeViewItem.Drop" Handler="TreeView_After_Drop"/>
            <EventSetter Event="TreeViewItem.MouseMove" Handler="TreeView_After_MouseMove"/>
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

*

*The LostFocus from the textbox work when I click everywhere except in the TreeView

2) The lostFocus work if I first select  a parent in the treeView and then a Treeview Item.
3)When I first select a treeViewItem and Then an Another treeViewItem there is no more LostFocus Event.
Why????


text:
Q: Using history.js come to the same scroll position when we click back button I want to implement a functionality wherein on clicking the back button, i come back to the same position. A good example may be any ecommerce site.When we scroll down and hit on a product, and click back from the product page, we should reach the same position of the page where that product is.
We use history.js to look up for hashchange and pushstate to save the entries.
But when I click on back button , it loads to the top of the page rather than the item scroll position. Also, we are laoding the data using AJAX mostly
Im fairly new to jquery, ajax and so do not know how to set the scroll position, save and load during back button click.
Any help would be great!
Thanks

A: I recently implemented something like this using $(document).scrollTop() and storing that figure in a cookie when leaving the page. My usecase was non-ajaxy but the same idea could easily be adapted with History.js's events replacing page load events, and no need to bother with the cookie for persistence; as @Kyle above mentioned in his comments, History.js lets you store data with pushState that is returned when you return back to that state.
See jQuery's docs: http://api.jquery.com/scrolltop/


text:
Q: I can't to set the Customer parameter correctly in Entity of JournalEntryLineDetail in quickbooks/v3-php-sdk? I sent next object:
{
    "TxnDate": "2020-05-05",
    "DocNumber": "Test123",
    "Line": [{
        "Description": "Test FBA Fees",
        "Amount": 100,
        "DetailType": "JournalEntryLineDetail",
        "JournalEntryLineDetail": {
            "PostingType": "Credit",
            "Entity": {
                "Type": "Customer",
                "EntityRef": {
                    "value": 1
                }
            },
            "AccountRef": {
                "value": 128
            }
        }
    }, {
        "Description": "Test",
        "Amount": 100,
        "DetailType": "JournalEntryLineDetail",
        "JournalEntryLineDetail": {
            "PostingType": "Debit",
            "AccountRef": {
                "value": 52
            }
        }
    }]
}

but received error message:
Passed array has no key for 'Value' when contructing an ReferenceType.
Please, tell me what is wrong with my request?

A: You need to use JournalEntryEntity instead of Entity under JournalEntryLineDetail, like so:
{
    "TxnDate": "2020-05-05",
    "DocNumber": "Test123",
    "Line": [{
        "Description": "Test FBA Fees",
        "Amount": 100,
        "DetailType": "JournalEntryLineDetail",
        "JournalEntryLineDetail": {
            "PostingType": "Credit",
            "JournalEntryEntity": {
                "Type": "Customer",
                "EntityRef": {
                    "value": 1
                }
            },
            "AccountRef": {
                "value": 128
            }
        }
    }, {
        "Description": "Test",
        "Amount": 100,
        "DetailType": "JournalEntryLineDetail",
        "JournalEntryLineDetail": {
            "PostingType": "Debit",
            "AccountRef": {
                "value": 52
            }
        }
    }]
}


text:
Q: NSMutableArray returning nil after adding a UIImage to the array I want to fetch the last photo taken in the photoLibrary and add it to an array which will be used in the UIActivivtyViewController. When the UIActivityViewController is presented, the image is not shown and it appears that the UIImage was never added to the array.
Here is what I have,
NSMutableArray *items = [[NSMutableArray alloc]init];
[items addObject:@"someText"];

PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];

__block UIImage *shareImage;

PHImageRequestOptions* options = [[PHImageRequestOptions alloc]init];
options.resizeMode = PHImageRequestOptionsResizeModeExact;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
options.version = PHImageRequestOptionsVersionUnadjusted;
options.synchronous = YES;

[[PHImageManager defaultManager] requestImageForAsset:lastAsset

    targetSize:PHImageManagerMaximumSize
    contentMode:PHImageContentModeDefault
    options:PHImageRequestOptionsVersionCurrent
    resultHandler:^(UIImage *result, NSDictionary *info) {

    dispatch_async(dispatch_get_main_queue(), ^{

    shareImage = result;
    [items addObject:shareImage];  });

}];

NSMutableArray *activityItems = [NSMutableArray arrayWithArray:items];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:nil];

Any help will be appreciated. I am new to to iOS dev and programming all together and I have been having a very hard time with this one.
Thanks

A: the UIImage is actually added to your items array. at the time you create the activityItems array and present the UIActivityViewController the block that adds the UIImage might not be finished though. if you added the presenting logic into the block (after adding the image to the array) it should work!
- (void)yourMethod {
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:@"someText"];

    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
    PHAsset *lastAsset = [fetchResult lastObject];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.version = PHImageRequestOptionsVersionUnadjusted;
    options.synchronous = YES;

    [[PHImageManager defaultManager] requestImageForAsset:lastAsset
                                               targetSize:PHImageManagerMaximumSize
                                              contentMode:PHImageContentModeDefault
                                                  options:PHImageRequestOptionsVersionCurrent
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [items addObject:result];

                                                    [self presentActivityControllerWithItems:items];
                                                });
                                            }];
}

- (void)presentActivityControllerWithItems:(NSArray *)items {
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    [self presentViewController:activityViewController animated:YES completion:nil];
}


text:
Q: Algorithm for drawing generalised circles A generalised circle is either a circle in the plane or a line. The general equation of one is:
$$A(x^2 + y^2) + Bx + Cy + D=0,$$
where $4AD - B^2 - C^2 \leq 0$. This can be checked by completing the square on $x$ and $y$, and checking that the minimum value of the LHS is $4AD - B^2 - C^2$.
My question is: What algorithm would you use to draw it?
Seems there are different approaches:

*

*Break it into the circle case and line case. Draw each using a dedicated routine. This way, you can use pre-existing drawing routines. There is a problem here, which is that out of many possible floating point values, only one of them is exactly $0$. So the line case happens in one case out of $2^{64}$ (if you use $64$-bit floats). And on top of that, thanks to rounding errors, what should be a line can become a circle. The circle case requires finding the centre and radius, but these can both be large values, subject to floating-point rounding errors. You can use a threshold instead of checking whether $A = 0$, but which threshold should get used?

*Traverse each value of $x$ in the viewport, and compute the (at most) $2$ different values of $y$, and draw those points. Then do the same again, but traversing each value of $y$ and finding $x$.

*A generalised circle determines a constant-speed motion along it. Use this somehow.

*A generalised circle determines an inversion through it. Use this fact somehow.

Approach 2 explicitly uses the viewport. Approaches 3 and 4 are vague, but depend on knowing it as well.
What approaches are there?

A: I am assuming you want to generate a raster image of the circle, since you are considering the viewport.
Given that, I think you're focusing on the wrong thing: If you have the viewport, you can just check if each coordinate satisfies the equation. The point is, if your A goes to zero, the 'other end' of the circle might not even be in the viewport(you don't have to 'treat' it differently). The main problem is, the pixels in the viewport might not even have a few floating point coordinates that satisfy the equation(that's where you'd need a threshold):
Increasing the margin of error would give you this:

I've made a small shader toy for this: https://www.shadertoy.com/view/7tVBDV
You can change it/tell me if you're looking for something else.

A: *

*For each pixel in the image:

*

*For each corner $(x,y)$ of the pixel (imagining the image as a small square tiling), compute the sign of $A(x^2+y^2)+Bx+Cy+D$.

*If all the signs are the same, plot the background colour.

*If any of the signs differ, plot the foreground colour.

See https://www.shadertoy.com/view/NlGBWt for a live WebGL-based example.  There is a slight thickening artifact for certain parameters, when the curve gives a sign of exactly $0$ for many pixel corner coordinates.


text:
Q: What are some simple and fast data visualization-tools? I'm buying an apartment. Being me I started by scarping all sales prices from the last 2 years.
Now I'm looking for a tool to quickly play around with and get a feel for the data. Its about 90000 lines so it has to be able to do some heavy lifting, I want to be able to do stuff like, price/square meter over time, grouped by streetname. I keep the data in a csv right now but can shuffle it around and also massage the data programatically.
Thanks!

A: Consider that Public Tableau is a free solution for you because u can go with programming and non-programming background.
Also in python you can use Matplotlib that is really easy to use.
In R you can go for ggplot that is quite easy to satisfy your needs.
Matlab is also another handy solution.
I believe you can search youtube for some videos that can give you some insight the above tools.


text:
Q: I want to calculate overlap area from semicircle draw in map using python I'm trying calculate overlap area created by semicircle which created by folium.after that i want to assign x,y,z value to the each semi semicircle by reduce same value overlap ex:- to reduce two x value semicircles
here is the image for better understand
How do I calculate the overlap area using python?

A: 1. Pure Math:
First, check if they intersect:
Since the overlaps are not uniform (orthogonal, perpendicular or symmetrical) you are going to need to use the help of something called FUNCTIONS (like f(x)) and since your sectors (they are not a semi-circle) look to be the same size and have a internal area, you can use INEQUALITIES to check if they are intersecting.
Say for example you have a two sectors that are intercepting like this, with their respective functions:
f(x) = x^2 + y^2 <= 5 | {0 <= x <= 5} {0 <= y} (RED)
g(x) = ((x - 4)^2) + y^2 <= 5 | {0 <= x <= 5} {0 <= y} (BLUE)

Assuming the unanimous cartesian system (x, y), all the sectors are drawing to the same coordinates (in the same 'space'; if you understand me here...):
Just equate the 2 functions together:
Rule: If f(x) intersects g(x) and vice-versa:

*

*f(x) = g(x) at some point

*g(x) is in / passes through the shaded area of f(x)

*f(x) is in / passes through the shaded area of g(x)

*The radius of f(x) + the radius of g(x) ≥ the distance between the 2 sectors

Note: 2 & 3 might need calculus to check, if your functions are not inequalities but lines.

Since you are coding a program, you can do an early out, that if one of the top 4 conditions are not met, the sectors do not intersect.
Second, if the sectors do intersect:
Use intergral calculus to find the area of intersection:
∫f(x) - ∫g(x) = the magnitude (size) of the area (make sure the upper and lower limits are specified correctly)
2. Using a 3D graphics method:
Now, I know this is not a really good method for this, but you could implement collision detection, if you do not like heavy maths.
Obviously, at first reading this may sound completely absurd (because collision detection is something used in game programming far more often), but have read at this:
circle-circle collision
and see if you can possibly implement a sort of sector hit-box on your quadrants (create circle hit-boxes, restrict them to sectors, and see if they intersect.)
Honestly, though, the first method would be the most optimum, assuming if you have some form of 3D or 2D cartesian system, where your quadrants are mapped on.
Although a little math heavy, it's up to you to how you would like to implement it in python (I would highly recommend creating multiple functions and optimising where you can (like the 4 rules to check intersection above)).
If you do not know any of the math concepts, google them to find out more, cause knowing how they work would help you a lot...


text:
Q: How to obtain if a CodeTypeRef is nullable or not In a T4 template file I wrote some codes to generate a class based on the passed CodeTypeRef type. The generated class would have all the properties of the passed type with a minor difference : All properties should be nullable. For example assume I passed the following type :
public class MyClass
{
     int x {get;set;}
     string y {get;set;}
     Guid z {get;set;}
     byte[] m{get;set;}
     float? n{get;set;}
}

Now the generated class would be something like this :
public class MyClass
{
     int? x {get;set;}
     string y {get;set;}
     Guid? z {get;set;}
     byte[] m{get;set;}
     float? n{get;set;}
}

As you see just the int x and Guid z properties changed to nullable types.
What I have in T4 is :
  <# foreach(var prop in modelType.VisibleMembers().OfType<CodeProperty>()) { #>
  public  <#= prop.Type.AsString  #>  <#= prop.Name #>{ get; set; }
  <# } #>

I don't know how to obtain if prop.Type can be nullable or not.
 NOTE : using prop.Type.TypeKind is helpful but not in all types.


text:
Q: Multiple threads waiting on one event? What (I think) I want is the equivelant of an AutoResetEvent that multiple threads can wait on, all to be resumed when it's set.
I know this can be achieved by having one AutoResetEvent per thread and setting each of them - but is there an easier way? A way that doesn't depend on arrays of eventhandles?
Effectively what (I think) I'd like is to be able to do this:
private volatile string state;
private MultiEventHandle stateChanged = new MultiEventHandle();

public void WaitForBlob()
{
  while (true)
  {
    object saved = stateChanged.Current;  // some sentinel value
    if (state == "Blob") break;
    stateChanged.WaitTilNot(saved);  // wait til sentinel value != "current"
  }
}

public void SetBlob()
{
  state = "Blob";
  stateChanged.Change();  // stateChanged.Current becomes a new sentinel object
}

ie, any number of threads can call WaitForBlob, and at any time (no race conditions) SetBlob can be called by yet another thread, and all waiting threads will detect the change immediately - and importantly, with no spin locks or Threading.Sleeps.
Now I think I can implement a "MultiEventHandle" relatively easily. But my question is... is there a better way? Surely I'm going about this wrong as it must be a pretty common use case, but I can't seem to find an in-built tool for the job. I'm afraid I may be going about inventing a square wheel here..

A: I've wrapped up a possible solution into a "WatchedVariable" class using Monitor.PulseAll/Wait behind the scenes (learning a bit about the Monitor class in the process). Posting here in case anyone else ever runs into the same problem - may be of some use with immutable data structures. Thanks to Jon Skeet for assistance.
Usage:
private WatchedVariable<string> state;

public void WaitForBlob()
{
  string value = state.Value;
  while (value != "Blob")
  {
    value = state.WaitForChange(value);
  }
}

Implementation:
public class WatchedVariable<T>
    where T : class
{
    private volatile T value;
    private object valueLock = new object();

    public T Value
    {
        get { return value; }
        set
        {
            lock (valueLock)
            {
                this.value = value;
                Monitor.PulseAll(valueLock);  // all waiting threads will resume once we release valueLock
            }
        }
    }

    public T WaitForChange(T fromValue)
    {
        lock (valueLock)
        {
            while (true)
            {
                T nextValue = value;
                if (nextValue != fromValue) return nextValue;  // no race condition here: PulseAll can only be reached once we hit Wait()
                Monitor.Wait(valueLock);  // wait for a changed pulse
            }
        }
    }

    public WatchedVariable(T initValue)
    {
        value = initValue;
    }
}

Whilst it's passed my test cases, use at your own risk.
Now to consult meta to figure out which answer I'm supposed to accept..

A: Any reason not to use a ManualResetEvent? That won't reset itself when one waiting thread has passed, so they'll all be released.
Of course, it means that if you need to Reset the event after all the waiting threads have gone through, you'd need some way of detecting that. You could possibly use a Semaphore instead, but I suspect it would be complicated.
Do you need to reset the event immediatley after you've set it, in your case?

A: I came up with a different solution to this problem.
It assumes the threads waiting for the event are not tight loops on the WaitOne() calls, and there's some work between the wait calls.
It uses one AutoResetEvent, calls WaitOne(0) and Set() continuously until no other threads waits for the event.
// the only event we'll use:
AutoResetEvent are = new AutoResetEvent(false);
// starting threads:
for (int i = 0; i < 10; i++)
{
    string name = "T" + i;
    new Thread(() => { while (true) { are.WaitOne(); WriteLine(name); } }).Start();
}

// release all threads and continue:
while (!are.WaitOne(0))
    are.Set();

The above code is tested for 1000 threads, it did released them all (though there's an overhead of too many iteration on the while loop, which can be easily limited to zero when there's a bit more work between the wait calls in the threads.
Something that is not clear to me from the documentation is whether it is possible for Set() to release a WaitOne() that was called later on the same thread - if this  situation is possible then this solution is not safe to use since it might not release all the threads before exiting the while loop.
It would be nice if someone could shed some light on it.


text:
Q: How to include image in html email In our WCF app, there is a method to send an html formatted email. I am using StringBuilder to build the html.
I am including an image in the email. When the app sends the email, the email is formatted correctly. However, the image doesn't display unless the user right clicks and selects "Download the Image".
Is there a way to have the image automatically display in the html email without the user having to select download image?
Here is my image tag:
<img src='http://www.MySite.com/Images/Mylogo.png' border='0' />

A: This is intentional behavior of the email client, there's no way to guarantee that the image will automatically show for all clients. You're going to have to live with that. In fact, some people prefer to read email in plain text.
If the image is relatively small, you might consider attaching it to the email instead. You'd have a better chance of having it displayed by default, though there are obviously other costs.


text:
Q: MySQL query to get only friends lists base on follow and followed back How can I get the list of my friends when logged in. I have a follow table and user table as shown in the picture. I want to query only people who followed me and I follow back list excluding the current logged in username from the lists.
mysql> select * from follows;
| id | sender_username |receiver_username|
|:---|:------:|         -----:|
| 1  |  kate  |         james | me
| 2  |   john |         kate  |
| 3  |   james|         kate  |
| 4  |   niner|         manb  |
| 5  |   james|         manb  |
| 6  |   manb |         james |
| 7  |   bert |         oken  |
| 8  |   kate |         alex  |

mysql> select * from users;
| id | fullname   | user_Name   |
|:---|:------:    |         -----:|
|  1 | Phill Ja   | kate |
|  2 | Another H  | james| me
|  3 | Some Crazy | manb |
|  4 | Nameless   | nede |

my friend username list follow and follow back
exclude the current logged username james(me).
kate
manb
SELECT users.fullname, users.user_Name,
follows.receiver_username,follows.sender_username
from users
inner join
follows on users.user_Name=follows.sender_username
where
users.user_Name ='name';


text:
Q: Basic SQL Feature I'm use to doing Django queries through the ORM but the code I'm being given uses all SQL.
I need to be able to get the total amount of all the transactions summed together for a particular agent defined within the date range.
cursor = connection.cursor()
    cursor.execute(
             """
             SELECT a.*, COUNT(t.*) as transactions
             FROM agent a
             JOIN transaction t ON t.agent_id = a.id
             WHERE t.date_created >= %s AND t.date_created < %s and t.status in %s AND a.state = %s
             GROUP BY a.id
             """, [startdate, enddate, config.TX_STATUSES, selectedstate])
    context['agents'] = util.raw_query_dict(cursor)

If I was using the Django ORM, I'd use .aggregate(Sum(...)) and combine that aggregated transaction value to each agent.
Can I do this within the SQL code in anyway?

Update
I need to actually aggregate the sum of a certain field of the Transaction model.
class Transaction(models.Model):
  source_amount = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')

Right now, this SQL query that @C14L suggested gives me the total number of transactions that apply to a certain agent between a time frame. I need the total amount of the source_amount fields added together which are in the Transaction model as illustrated above. How can I achieve this?

A: Select from your result and sum together all the transaction values.
SELECT SUM(transactions) AS total FROM (
    SELECT a.*, COUNT(t.*) AS transactions
    FROM agent a
    JOIN transaction t ON t.agent_id = a.id
    WHERE t.date_created >= %s
      AND t.date_created < %s
      AND t.status in %s
      AND a.state = %s
    GROUP BY a.id
);

Edit: Not sure if I understood correctly the question you added, but if you just want to sum up the selected t.source_amount values, then SUM() should be able to do that.
SELECT SUM(t.source_amount) AS amount
FROM agent a
JOIN transaction t ON t.agent_id = a.id
WHERE t.date_created >= %s
  AND t.date_created < %s
  AND t.status in %s
  AND a.state = %s
GROUP BY a.id


text:
Q: error al cargar imagen almacenada en sql server tengo una imagen almacenada en mi tabla tipo varbinarymax, la mayoria de imagenes si las puedo mostrar en mi picturebox pero las que son tomadas con camara digital y subidas a  la base de datos me marca el error:
parameter is not valid

Este es mi codigo que funciona con las demas imagenes descragadas de internet por ejemplo pero con las tomadas con camara digital no las puedo mostrar:
byte[] imagebyte = new byte[0];

 imagebyte = (byte[])readercoti[14];//aqui paso mis datos varbinarymax

 MemoryStream ms = new MemoryStream(imagebyte, 0, imagebyte.Length);

ImgPic.Image = Image.FromStream(ms, true);//aqui me sale el error

Asi es como mando la imagen a la base de datos:

 Bitmap bmp = new Bitmap(rutaImagen);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, bmp.RawFormat);
                            byteimage = ms.GetBuffer();

SqlParameter imgparameter = comsem.Parameters.Add("@img", SqlDbType.Binary);
                        imgparameter.Value = byteimage;


text:
Q: Facing crash when Posting the data to MVC WEB API Controller from Class Library project Facing issue while posting the data to MVC Web API controller through Class Library project.
MVC Web API is hosted on Localhost at Port 84.
Class Library Code that sends request
public String Put(OM_ServicesType obj)
{
    string URI = "http://localhost:84/WebAPIServiceType/Put");
    String myParameters = "ServiceType=qa&description=qa&Sid=1";

    using (WebClient wc = new WebClient())
    {
        wc.Headers[HttpRequestHeader.ContentType] =
                                                  "application/x-www-form-urlencoded";
        string HtmlResult = wc.UploadString(URI, myParameters);
        return JsonConvert.DeserializeObject<String>(HtmlResult);
    }
}

Below is the crash

The remote server returned an error: (404) Not Found.

MVC Web API Code
[HttpPost]
public HttpResponseMessage Put(int Sid, string ServiceType, string description)
{
    var obj = new Dal_ServiceType { ServicesTypeID = Sid, Name = ServiceType,
                                              Description = description};
    var re = obj.Put();
    return Request.CreateResponse(HttpStatusCode.OK, new { ErrorMessage = re });
}

A: Ok, I found the solution.
Code in WEB API Controller Action Method
[HttpPost]
public HttpResponseMessage Action_Method_Name([FromBody] ClassName obj)
{
    var objUpdated = new Dal_Provider
    {
        ProviderID = obj.ProviderID,
        ZipCode = obj.ZipCode
    };
    var re = objUpdated.Post();
    return Request.CreateResponse(HttpStatusCode.OK, new { ErrorMessage = re });
}

Code to call the Web API
public String Post(ClassName obj)
{
    String url = string.Format("{0}{1}", "DomainName comes here",
                    "Controller Name/Action Method Name");
    var httpClient = new HttpClient();
    var responseMessage = httpClient.PostAsync(url,
            new ObjectContent<ClassName>(obj, new JsonMediaTypeFormatter())).Result;
    return responseMessage.ReasonPhrase;
}


text:
Q: CSS: Anchor In List Item Doesn't Stay 100% Height So, here's the skinny...
I have a page that has a list as display:table-cell.  As the width of the browser resizes, the contents (anchors) of the lists may wrap to 2 lines.  The problem is the anchors that don't wrap to 2 lines aren't staying 100% height.
CSS...
.home .pushes ul {display:table;}
.home .pushes ul li {display:table-cell; vertical-align:middle; width:25%; background-color:#e5a015; color:#ffffff;}
.home .pushes ul li a {display:block; padding:4em 0; padding:4rem 0;}

So, the height of
 should be determined by the height and padding of .  But, since it's <display:table-cell>, the height is determined by the tallest .
Ok, so just set a {height:100%;}.  But, then, the anchor doesn't keep the padding.  So, just set li {height:160px;} or something.  But, then the anchor isn't vertically-centered.  So, just set li {line-height:160px;}.  But, then the anchor is huge when it wraps to 2 lines.
So, what is a guy to do?
I could do li {display:inline-block;}.  But I want all the boxes to be the same height.
JJ
Edit...
HTML included for posterity...

bleh

bleh

JJ
Edit 2...
The anchor background color is what isn't growing the full height of its parent.

I didn't realize that I could upload an image.  Thanks for the tip.
JJ

A: The best way of fixing this problem would be to use position: relative and position: absolute.
Example:
li {
  position: relative;
}

li a {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

However, the above does not work because your li is using "display: table-cell;" and position: relative is not defined for table cells (See: Using Position Relative/Absolute within a TD?).
Therefore, your only choice is to use Javascript to get this done.  There are many solutions but here is one:
Use the jQuery resize method (http://api.jquery.com/resize/) to keep track of when the window resizes.  When the window resizes modify the anchor tag's padding so that it continues to cover the entire space.


text:
Q: How do you remove white space between title and table? I tried asking this somewhere else as well, but I am having trouble removing the white space between the title of my table and the actual table.  This doesn't happen when in my regular rmarkdown article, but when I knit to beamer for my presentation it produces these bizarre white spaces. Anyone know why?
mean.party.class <- dat3 %>%
  group_by(party2, class2) %>%
   filter (party2 !="Indep" & class != "IDK")%>%
  summarise_at(vars(DL, DU, RL, RU, L, U, D, R), funs(mean(., na.rm=TRUE)))

knitr::kable(mean.party.class, col.names=c("Party ID", "Class", "DL", "DU", "RL",   "RU",   "L", "U", "D" , "R"), digits=2,  caption = "Mean Trust Per Group (Party and Social Class Identity)", "latex", booktabs = T) %>%
 kable_styling( full_width = F, position = "left",  latex_options = "scale_down", bootstrap_options = c("striped", "hover")) %>% footnote(
   general = c("1. D= Democrat, R=Republican, L=Lower Class, U = Upper Class; ", "2. Independents dropped")) %>% row_spec(0,bold=TRUE)

Here is an example
---
title: "Example"
author: "Its me"
date: "6/12/2020"
always_allow_html: true
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{adjustbox}
- \usepackage{caption} \captionsetup[table]{skip=0pt}
- \usepackage[font=small,skip=0pt]{caption}
- \usepackage{tikz}
- \usepackage{float}
- \usetikzlibrary{arrows,shapes,positioning}

output:
  beamer_presentation:
    theme: "Berkeley"
    colortheme: "dolphin"
    fonttheme: "structurebold"
    slide_level: 2
    #incremental: true
---

```{r}
setwd("~/Google Drive/UC Davis /R stuff")
```

```{r, include=FALSE}
library(rticles)
library(kableExtra)
library(knitr)
library(plyr)
library(dplyr)
library(gdata)
library(ggplot2)
library(MASS)
library(corrplot)
library(haven)
library(factoextra)
library(ggplot2)
library(ggrepel)
library(viridis)
library(lattice)
library(optiscale)
library(acepack)
library(psych)
library(smacof)
library(MCMCpack)
library(basicspace)
library(boot)
library(pscl)
library(wnominate)
library(RColorBrewer)
library(sjPlot)
```

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r, include= FALSE}
#load cars
data("mtcars")
head(mtcars, 2)
```

```{r, include= FALSE}
mean.mpg <- mtcars %>%
  summarise_at(vars(mpg), funs(mean(., na.rm=TRUE)))
```

## there it is
```{r}
knitr::kable(mean.mpg, col.names=c("mpg"), digits=2,  caption = "This is a table", "latex", booktabs = T, escape=F) %>%
 kable_styling(full_width = T, position = "left", latex_options = "scale_down", bootstrap_options = c("striped", "hover")) %>% footnote(
   general = c("1. test 1", "2. test 2"))%>%
  row_spec(0,bold=TRUE)
```

A: If you add keep_tex: true to your header you can edit the resulting .tex file to remove the multiple causes of the additional space:

*

*remove the unnecessary and often harmful \resizebox{\linewidth}{!}{...} around the table

*remove the caption package (which is unnecessarily loaded multiple times)

*remove the parskip package

\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[ignorenonframetext,]{beamer}
\usepackage{pgfpages}
\setbeamertemplate{caption}[numbered]
\setbeamertemplate{caption label separator}{: }
\setbeamercolor{caption name}{fg=normal text.fg}
\beamertemplatenavigationsymbolsempty
% Prevent slide breaks in the middle of a paragraph:
\widowpenalties 1 10000
\raggedbottom
\setbeamertemplate{part page}{
\centering
\begin{beamercolorbox}[sep=16pt,center]{part title}
  \usebeamerfont{part title}\insertpart\par
\end{beamercolorbox}
}
\setbeamertemplate{section page}{
\centering
\begin{beamercolorbox}[sep=12pt,center]{part title}
  \usebeamerfont{section title}\insertsection\par
\end{beamercolorbox}
}
\setbeamertemplate{subsection page}{
\centering
\begin{beamercolorbox}[sep=8pt,center]{part title}
  \usebeamerfont{subsection title}\insertsubsection\par
\end{beamercolorbox}
}
\AtBeginPart{
  \frame{\partpage}
}
\AtBeginSection{
  \ifbibliography
  \else
    \frame{\sectionpage}
  \fi
}
\AtBeginSubsection{
  \frame{\subsectionpage}
}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
  \usepackage{unicode-math}
  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
\usetheme[]{Berkeley}
\usecolortheme{dolphin}
\usefonttheme{structurebold}
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
%\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{hyperref}
\hypersetup{
            pdftitle={Example},
            pdfauthor={Its me},
            pdfborder={0 0 0},
            breaklinks=true}
\urlstyle{same}  % don't use monospace font for urls
\newif\ifbibliography
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{0}

% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

\usepackage{booktabs}
\usepackage{longtable}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{adjustbox}
%\usepackage{caption}

%\captionsetup[table]{skip=0pt}
%\usepackage[font=small,skip=0pt]{caption}
\usepackage{tikz}
\usepackage{float}
\usetikzlibrary{arrows,shapes,positioning}

\title{Example}
\author{Its me}
\date{6/12/2020}

\begin{document}
\frame{\titlepage}

\begin{frame}{there it is}
\protect\hypertarget{there-it-is}{}

\begin{table}

\caption{\label{tab:unnamed-chunk-4}This is a table}
%\resizebox{\linewidth}{!}{
\begin{tabu} to \linewidth {>{\raggedleft}X}
\toprule
\textbf{mpg}\\
\midrule
20.09\\
\bottomrule
\multicolumn{1}{l}{\textit{Note: }}\\
\multicolumn{1}{l}{1. test 1}\\
\multicolumn{1}{l}{2. test 2}\\
\end{tabu}
%}
\end{table}

\end{frame}

\end{document}

(I would stay away from tabu and use a normal table instead)


text:
Q: The callback inside Task is automatically called on the main thread Once upon the time, before Async/Await came, we use to make a simple request to the server with URLSession dataTask. The callback being not automatically called on the main thread and we had to dispatch manually to the main thread in order to perform some UI work. Example:
DispatchQueue.main.async {
    // UI work
}

Omitting this will lead to the app to crash since we try to update the UI on different queue than the main one.
Now with Async/Await things got easier. We still have to dispatch to the main queue using MainActor.
await MainActor.run {
 // UI work
}

The weird thing is that even when I don't use the MainActor the code inside my Task seems to run on the main thread and updating the UI seems to be safe.
Task {
       let api = API(apiConfig: apiConfig)

       do {
              let posts = try await api.getPosts() // Checked this and the code of getPosts is running on another thread.
              self.posts = posts
              self.tableView.reloadData()
              print(Thread.current.description)
          } catch {
              // Handle error
          }
}

I was expecting my code to lead to crash since I am trying to update the table view theorically not from the main thread but the log says I am on the main thread. The print logs the following:
<_NSMainThread: 0x600003bb02c0>{number = 1, name = main}

Does this mean there is no need to check which queue we are in before performing UI stuff?

A: Regarding Task {…}, that will "create an unstructured task that runs on the current actor" (see Swift Concurrency: Unstructured Concurrency). That is a great way to launch an asynchronous task from a synchronous context. And, if called from the main actor, this Task will also be on the main actor.
In your case, I would move the model update and UI refresh to a function that is marked as running on the main actor:
@MainActor
func update(with posts: [Post]) async {
    self.posts = posts
    tableView.reloadData()
}

Then you can do:
Task {
    let api = API(apiConfig: apiConfig)

    do {
        let posts = try await api.getPosts() // Checked this and the code of getPosts is running on another thread.
        self.update(with: posts)
    } catch {
        // Handle error
    }
}

And the beauty of it is that if you're not already on the main actor, the compiler will tell you that you have to await the update method. The compiler will tell you whether you need to await or not.
If you haven't seen it, I might suggest watching WWDC 2021 video Swift concurrency: Update a sample app. It offers lots of practical tips about converting code to Swift concurrency, but specifically at 24:16 they walk through the evolution from DispatchQueue.main.async {…} to Swift concurrency (e.g., initially suggesting the intuitive MainActor.run {…} step, but over the next few minutes, show why even that is unnecessary, but also discuss the rare scenario where you might want to use this function).

As an aside, in Swift concurrency, looking at Thread.current is not reliable. Because of this, this practice is likely going to be prohibited in a future compiler release.
If you watch WWDC 2021 Swift concurrency: Behind the scenes, you will get a glimpse of the sorts of mechanisms underpinning Swift concurrency and you will better understand why looking at Thread.current might lead to all sorts of incorrect conclusions.


text:
Q: How to add a row in a certain observation and then print the first 5 rows? I am trying to add the a row of data to a data frame in the third observation spot but the data frame has 10 variables and I am only adding 7. I was instructed R would automatically make the others NA but that wasn't the case - it repeated the info so now the 11th observation says "Pike."
I've tried:
COVID %>%
  add_row(COVID, county = "Pike", confirmed = 1392, confirmed_delta = 10, deaths = 30, recovered = 103, recovered_delta = 2, active_delta = 1, .before = 4) %>%
  head(5)

and
head(add_row(COVID, county = "Pike", confirmed = 1392, confirmed_delta = 10, deaths = 30, recovered = 103, recovered_delta = 2, active_delta = 1, .before = 4), 5)

Add a row to the COVID data set with the following information and place it as the 3rd observation. Print the first 5 rows with the newly added row:
county = Pike
confirmed = 1392
confirmed_delta = 10
deaths = 30
recovered = 103
recovered_delta = 2
active_delta = 1
Is there a way to place it in the third index with only the 7 variables and the others be NA?

A: You can use base R , let's build demo data.frame
covid <- data.frame(
  country = c("usa" , "fr" , "en" , "eg" , "ua"),
  confirmed = c(130 , 231 , 432 , 233, 323),
  confirmed_delta =  c(4, 3, 2, 4, 3),
  deaths = c(4, 3, 2, 4, 2),
  recovered = c(12, 32, 2, 3, 2),
  recovered_delta = 1:5,
  active_delta = 5:1
)

covid3 <- data.frame(country = "Pike", confirmed = 1392, confirmed_delta = 10, deaths = 30, recovered = 103, recovered_delta = 2, active_delta = 1)

covid <- rbind(covid[1:2 ,] , covid3 , covid[3:(ncol(covid)-2),] , make.row.names = F )

head(covid)
#>   country confirmed confirmed_delta deaths recovered recovered_delta
#> 1     usa       130               4      4        12               1
#> 2      fr       231               3      3        32               2
#> 3    Pike      1392              10     30       103               2
#> 4      en       432               2      2         2               3
#> 5      eg       233               4      4         3               4
#> 6      ua       323               3      2         2               5
#>   active_delta
#> 1            5
#> 2            4
#> 3            1
#> 4            3
#> 5            2
#> 6            1

Created on 2022-05-29 by the reprex package (v2.0.1)


text:
Q: Solve this system of equations with modulus in $\mathbb{C}$ I tried to solve this exercise but failed after some calculations, tough I've extracted some important piece of information from it. The system is:
$$ \left\{\begin{array}{c} x|y| = z^2 \\ y|z| = x^2 \\ z|x| = y^2 \end{array}\right. $$
where $x,y,z \in \mathbb C$.
First I tried substituting $z^2$ with $\left(\frac{y^2}{|x|}\right)^2 = \frac{y^4}{x\cdot \overline{x}}$ but I soon gave this idea up as it caused much harder equations to appear. But the I thought of multiplying them all together and I found the following:
$$ xyz|x||y||z| = x^2y^2z^2 \\ xyz|xyz| = (xyz)^2 \\ |xyz| = xyz \\ Im(xyz) = 0 \leftrightarrow xyz \in \mathbb R $$
After this I am stuck. What can I do next to solve the system?

A: First note that if $x, y, z$ are solutions to your system, then you must have $|x| = |y| = |z|$; you can see this by taking the absolute value of each of your equations, and considering the equation where the largest of the three has its square on the right hand side.
In particular -- setting aside the solution $x = y = z = 0$ -- note that for any solution $x, y, z$, and any positive $\alpha$, also $\alpha x, \alpha y, \alpha z$ is a solution. Thus we can take $\alpha = 1/|x|$ and reduce to the case where $|x| = |y| = |z|$, which considerably simplifies your equations to
$$
x = z^2,\\
y = x^2,\\
z = y^2.
$$
Now we can do repeated substitution, and obtain that $x^7 = y^7 = z^7 = 1$. Each of $x, y, z$ is a 7th root of unity. And now you can simply check: if $x$ is any seventh root of unity, and we set $y = x^2$, and $z = y^2$, then the latter two equations are clearly satisfied, and $z^2 = y^4 = x^8 = x$, so therefore so is the first.
Hence the solutions to the equation are $\alpha \times \exp(2\pi i \tfrac k7)$, for $k \in \{0,1,2,3,4,5,6\}$, and $\alpha$ non-negative real.

A: Things to try:

*

*$x|y| = z^2 \implies  |x| |y| = |z|^2$, which implies $|xyz|=|x|^3=|y|^3=|z|^3$.

*$x|y| = z^2 , y|z| = x^2 \implies x^3 = y z^2$


text:
Q: java.util.logging Using ConsoleHandler & not seeing system.err output in IntelliJ IDEA 9 or Mac Terminal window I've been trying to run an integration test based on GroovyTestCase.
It's got a built in log property according to API docs.
I was initially trying to log an info message as a test was running, using this site as a reference.
I was surprised my logging messages were never displaying in the Console in IntelliJ9, so I tried running my integration test on my Mac from the Terminal window.
Still I didn't see any output, even though my code had set the logging level to ALL and I was using the ConsoleHandler.
I'd almost given up on this, but noticed a message in the terminal window, that said my failed tests were in the target/test-reports folder.
Oddly I can't even see the target folder in the the Project Explorer window of IntelliJ9, irrespective of the view as option I take. So I guess that's one question I'd like to solve.
Anyway I tracked down the error report, and when I drill down into the failed test of the HTML report, there's a link to system.err and voila. There's my output I'd been expecting to see all along! So the second part of this is, is there some sort of UNIX system.err redirect  to system.out I need to do in order to see this output in my IDE?
Any ideas?
I figured out how to display the target folder...
Project Structure -> Modules -> Excluded folders click x against target under excluded section (to left of folders)
You can remove it again by Project Structure -> Modules -> click on 'target' folder then the Excluded button above folders list

A: See GRAILS-7012. log in the GroovyTestCase is java.util.logging, not log4j. You should define your own logger and use it instead. Built-in GroovyTestCase logger has hardcoded configuration to produce files for stderr and stdout in HTML, XML and plain text formats (it runs tests intercepting all the output and generating files in different formats using custom XSL -- junit-frames.xsl).


text:
Q: Boot springboot app even if mongodb is down I am using SpringBoot v2.7.0
I have following springboot config
spring:
  data:
    mongodb:
      uri: ${MONGO_DB_URL}
      database: ${MONGO_DB_DATABASE}

There is not explicit beans configurations. I have repositories for respective documents which extends MongoRepository<ModelNameClass, IDType>
This is all working fine. But now I want to handle the situation where i want to make sure that app still boots up if MongoDB is down. MongoDB is not our primary database.
How can i do so?

A: MongoDB not being available wouldn't stop the app from starting successfully. Just tested this pointing the app to a local DB that didn't exist. There is below exception in the logs, but the app starts up and the test controller endpoint I added is accessible and responds correctly:
2022-08-13 07:08:10.093  INFO 14471 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.6.0.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:180) ~[mongodb-driver-core-4.6.0.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:193) ~[mongodb-driver-core-4.6.0.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:157) ~[mongodb-driver-core-4.6.0.jar:na]
        at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
        at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
        at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) ~[na:na]
        at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) ~[na:na]
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) ~[na:na]
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
        at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
        at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.6.0.jar:na]
        at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.6.0.jar:na]
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.6.0.jar:na]
        ... 4 common frames omitted

2022-08-13 07:08:10.204  INFO 14471 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-08-13 07:08:10.230  INFO 14471 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-08-13 07:08:10.250  INFO 14471 --- [           main] io.github.devatherock.Application        : Started Application in 1.799 seconds (JVM running for 2.045)
2022-08-13 07:08:17.510  INFO 14471 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-08-13 07:08:17.510  INFO 14471 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-08-13 07:08:17.512  INFO 14471 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

If what you mean is that the app's actuator health check is failing when mongodb is down, then the MongoHealthIndicator can be disabled by setting the below config:
management:
  health:
    mongo:
      enabled: false

The test application can be found on github

A: There is an option to ignore the initializing of datasource when your application fails to start by setting this property:
spring.sql.init.continue-on-error=true

You can read more about this fail-fast-feature on Spring Boot documentation which is Spring Boot 2.7.0 Initialize a Database Using Basic SQL Scripts which says:

By default, Spring Boot enables the fail-fast feature of its script-based database initializer. This means that, if the scripts cause exceptions, the application fails to start. You can tune that behavior by setting spring.sql.init.continue-on-error.

Also if you want to handle when your database is down or up, you can create a bean for datasource and handle any exception which mean your database is down. In order to do this, create a class @Configuration which has datasource as bean like this:
@Configuration
public class DataSourceConfiguration {

    @Bean
    public DataSource dataSource() {
        try {
            // create datasource to your database
        } catch (Exception) {
            // create a fake/dummy datasource to your database
        }
    }
}


text:
Q: compare a list to a set efficiently Is there a more efficient way to make sure that a list contains all and only the elements of a set other then constructing another set from the list?
E.g. something that avoids copying and sorting the list a la
s = set([ 1, 2, 3, 4 ])
l = [ 1, 2, 3, 5 ]
if s!=set(l):
    print "bad list"

A: You can avoid constructing another set from the list by calling the symmetric_difference method of the set with the list:
if s.symmetric_difference(l):
    print "bad list"

A: If you wish to allow duplicates, you would need some kind of extra space to keep track of things. The choice now however, can be simplified to either repeating the space for the list, or for the set. Incase the list is bigger than the set usually, the first function can save on some space. But caution: it would take more space incase the set is bigger than the list.
s = set([ 1, 2, 3, 4 ])
l = [ 1, 2, 3, 5 ]

Approach 1: creates a Counter in order of the set
def low_space_compare(some_set, some_list):
    from collections import Counter
    state = Counter(some_set)
    for item in some_list:
        if item not in state:
            print("bad")
            return "bad"
        state[item] -= 1
    if any(val > 0 for val in state.values()): #change to val != 0 if duplicates not allowed
        print("bad")
        return "bad"
    return "good"

On the other hand, if dupes were not allowed either, you could simply iterate through the list and remove from the set, requiring no extra space at all. But it mutates the set!!!
Approach 2: no extra space, cannot handle dupes
def low_space_compare_no_dupes(some_set, some_list):
    #need to create a copy of some_set if you (hopefully) take offense to mutating the original set
    for item in some_list:
        if item not in some_set:
            print("bad")
            return "bad"
        else:
            some_set.remove(item) #this makes a dupe value fail when you see it again
    if some_set:
        print("bad, set had extra stuff")
        return "bad"
    return "good"

low_space_compare(s, l) #bad
low_space_compare_no_dupes(s, l) #bad
print(s) #{4} uh oh.

Edit: Approach 3: worst case same as creating a new set from list n in the case where its a valid match, but short circuits:
def low_space_compare_no_counters(some_set, some_list):
    new_set = set()
    #need to create a copy of some_set if you (hopefully) take offense to mutating the original set
    for item in some_list:
        if item not in some_set:
            if item not in new_set:
                print("bad")
                return "bad"
            else:
                pass #ah, a dupe, keep going
        else:
            some_set.remove(item)
            new_set.add(item)

    if some_set:
        print("bad, set had extra stuff")
        return "bad"
    return "good"

low_space_compare_no_counters(s, l)


text:
Q: using npm request to fetch a blob of files I have some files on a CDN that I want to bring into a local project. I was trying to automate this in my gulpfile by using npm's request module.
But I'm having a difficult time getting it to work with the blob of files;
var core = request({
     url: `${cdn}/core/**/*.scss`,
     headers: requestHeaders})
   .pipe(gulp.dest(`${local}`));

Is it just not possible to do this with request? It's not a mandatory requirement, but it sure would be convenient.

A: Using gulp-remote-src
var gulp = require('gulp');
var request = require('request');
var remoteSrc = require('gulp-remote-src');

gulp.task('download', function() {
  remoteSrc(['file.scss'], {
    base: 'http://domain.com/path/'
  })
  .pipe(gulp.dest('.'));
});

Downloads http://domain.com/path/file.scss into current directory.
Using fs
var gulp = require('gulp');
var request = require('request');
var fs = require('fs');

gulp.task('download', function() {
  request
    .get('http://domain.com/file.scss')
    .on('error', function (error) {
      console.log("Error: ", error);
    })
    .pipe(fs.createWriteStream('f.scss'));
});

Downloads http://domain.com/path/file.scss into ./f.scss.
Using vinyl-source-stream
var gulp = require('gulp');
var request = require('request');
var source = require('vinyl-source-stream');

gulp.task('download', function() {
  request
  .get('http://domain.com/path/file.scss')
  .on('error', function (error) {
    console.log("Error: ", error);
  })
  .pipe(source('.'))
  .pipe(gulp.dest('f.scss'));
});

Downloads http://domain.com/path/file.scss into ./f.scss.


text:
Q: Remove index.php keep parameter only I have this url http://subdomain.domain.com/index.php?page=print-items and I want to remove index.php?page= and only keep what comes after it.
I tried this but it didn't work. it only removes index.php and keeps ?page=print-items
RewriteEngine On
RewriteRule ^([a-z0-9]+) index.php?page=$1

A: Could you please try following, written and tested as per shown samples.
RewriteEngine ON
RewriteCond %{THE_REQUEST} index\.html\s [NC]
RewriteRule ^(.*/?)/?$ index.html?page=$1 [NC,L]

OR if you are hitting usre friendly URL and you want to redirect in backend into index.html URL with query string then try following.
RewriteEngine ON
RewriteCond %{THE_REQUEST} !index\.html\s [NC]
RewriteRule ^(.*/?)/?$ index.html?page=$1 [NC,L]


text:
Q: Nginx returns 404 not found when access file on server I have a server(Ubuntu 16.04) and a user called coxier.
I configure Nginx to Proxy Requests. I create a file etc/nginx/sites-available/myproject.
server {
    listen 80;
    server_name 101.200.36.xx;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/coxier/iemoji/server/iemoji.sock;
    }
}

In this flask project, server receive request and then generate a .gif file for this request.
At first I directly I use flask#send_file to send gif file about 1MB, however speed is very slow.
So I decide to optimize the request.

*

*Receive http request and generate gif file.

*Return url of the generated gif file to user.

*User access gif file by url.

I have a question. How can I generate url of the generated gif?
I have tried like below.
server {
    listen 80;
    server_name 101.200.36.xx;

    root /home/coxier/iemoji/server/output;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/coxier/iemoji/server/iemoji.sock;
    }
}

For example, I want to access /home/coxier/iemoji/server/output/a3dfa3eb21daffc7085f71630cbd169e/output.gif.
Then I return http://101.200.36.xx/a3dfa3eb21daffc7085f71630cbd169e/output.gif to user.
However nginx returns 404 Not Found.

A: From https://docs.nginx.com/nginx/admin-guide/web-server/serving-static-content/ , I find solution.
server {
    listen 80;
    server_name 101.200.36.xx;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/coxier/iemoji/server/iemoji.sock;
    }

    location ~ \.(gif) {
        root /home/coxier/iemoji/server/output;
        sendfile           on;
        sendfile_max_chunk 1m;
    }
}

You should redefine root in location block.
Then you can generate url like this:
http://101.200.36.xx/a3dfa3eb21daffc7085f71630cbd169e/output.gif.


text:
Q: IdentityServer4 returning 404 Status Code for Every Endpoint I've been evaluating IdentityServer as we are looking to use it at work. Whilst it is easy to get running using Visual Studio in a Dev environment, I've never been able to get it running as a deployment on my home server (Windows 2019 Server).
I've got other simple ASP.NET sites running on that server, so I've demonstrated that IIS is working and sites can be served.
When I try to load the MVC UI Quickstart (deployed), I just get a 404 response. I get this for any end-point e.g. .well-known/openid-configuration
I've been having a lot of trouble figuring out what's wrong, as the IIS logs have not revealed anything instructive.
I'm just using a self-signed certificate for SSL for the site.
I created a pfx for the Signing Credential using OpenSSL. This works fine in a dev environment. I'm loading it from a specific directory (to which IIS_IUSRS have permission).
Here's my Configuration methods:
public void ConfigureServices(IServiceCollection services)
{

    services.AddIdentityServer()
        //.AddDeveloperSigningCredential()
        .AddSigningCredential(new X509Certificate2(Path.Combine(@"E:\Certs\id4.pfx"), "opensesame"))
        .AddTestUsers(InMemoryConfiguration.Users().ToList())
        .AddInMemoryClients(InMemoryConfiguration.Clients())
        .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

and:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    }

    app.UseIdentityServer();

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}

Other Info
The Windows Hosting bundle is installed (I've got other Core 2.2 apps running on it).
The App Pool is running with No Managed Code as the .NET CLR Version. Enable 32-bit Applications is set to False.
The Site itself has default settings. Anonymous and Basic Authentication are enabled.
It has both a http binding for port 80 and an https binding for port 443.
The Web.config, generated by the publish, is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\SimpleIdp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 6418350e-fa8e-4ac9-9201-f4ba2a4a6abf-->

I've had a couple of chops at this over the last few months and always end up in the same place. So it would be great if someone is able to help.
Thanks


text:
Q: What's it called when you make an adjective post-positive?
Possible Duplicate:
Why do some adjectives follow the nouns they modify?

In English, adjectives usually precede the nouns they describe, as in "organic carrots".
However, in some cases "normal" adjectives are reversed - possibly for emphasis or to add an exotic flair.
For example, Curtis Mayfield's album "A Love Supreme"; this would normally flow "a supreme love", but is reversed for some reason.
Whatever the case may be, is there a word for this switcharound?

A: This is called hyperbaton, which means to use the words out of their normal order. This can be used as an impact strategy. The writing guide Bang: Writing with Impact explains it this way:

Any time you place words out of their normal order, you create impact.
  You force the reader to pay attention to them, reflect on them, and
  remember them. In this strategy, you immediately follow the name of a
  thing with an adjective or descriptive phrase. In this way, the
  description becomes part of the name of the thing; they are
  inseparable. When your reader thinks of the thing, he or she will also
  think of the description because the description becomes part of the
  name.
Your reader will notice this immediately, which means this strategy
  can be used to emphasize a key characteristic. However, because this
  change in word order is so obvious and so prone to sounding contrived,
  it must be used carefully and infrequently. In the right place, it can
  be a highly effective technique for emphasizing a point. Use it at the
  end of a sentence for greatest impact.
"This is a plan impossible."


text:
Q: How do I store orders to my cart and firesebase database I am doing an ordering app in android studio.
I want to show the list of orders when the "cart" button is clicked
Here is what I have when "order" button is clicked
btnCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Database(getBaseContext()).addToCart(new Order(
                foodId,
                    currentFood.getName(),
                    numberButton.getNumber(),
                    currentFood.getPrice()
            ));
            Toast.makeText(FoodDetail.this, "Added To Cart", Toast.LENGTH_SHORT).show();
        }
    });

my add to cart IS STILL EMPTY and this is what i only have
public void addToCart(Order order)
{
            order.getProductId(),
            order.getProductName(),
            order.getQuantity(),
            order.getPrice());

}

please help me :( thank you! :)

A: Here are a sample code to store data in the firebase key-value system with the key "message" and the value "Hello, World"
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

myRef.setValue("Hello, World!");

here are some links that will help you
Setup dependences to android
Get started
Read and write data

A: This is definitely NOT how to store data in Firebase Database. You didn't create a FirebaseDatabase object to begin with. I'll assume you're using android studio to write this app (since that's one of the tags). To store data in Firebase database, follow the following steps:

*

*Connect your app to Firebase: Just go to the path below and follow the guidelines on completing the process.

Tools > Firebase > Firebase Database

*In your class, create a FirebaseDatabase object and set the value to FirebaseDatabase.getInstance().getReference(). This reference points directly into your Firebase database and anything you store into this reference would be stored direectly. If you want to store data inside an inner folder inside this reference, use the child() method to nest.

*To store data, use the setValue() method of the FirebaseDatabase reference using the data to be stored as a parameter.
Example:
DatabaseReference someData = FirebaseDatabase.getInstance().getReference();

someData.setValue("Little file");

You can also refer to the Official Firebase guide.
I hope this helps.. Merry coding!

A: Try this out, im assuming you already include Firebase in your project.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("RefName");

myRef.setValue(new Order(
            foodId,
                currentFood.getName(),
                numberButton.getNumber(),
                currentFood.getPrice()
        ));


text:
Q: Swift how can I partially change UILabel's colour
I am designing an option bar on the navigation bar of my app, I want to achieve the same UI of that of the Music App, as you can see when the slider is sliding, the UILabel is partially changing its color, how does this be archived? Should I work on CALayer?
This is what I did so far, it's just not correct
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {

            self.optionBarSlider.frame = self.selectedButton.frame
        }) { _ in
            self.selectedButton.setTitleColor(.black, for: .normal)
        }

A: You can do this with setting attributedText to change the color of the portion that you need
How do you set an Attributed Title Color for State in Swift


text:
Q: Silverlight - Exception when trying to POST to webservice I'm using the "Post" method so I can send a custom object. But I keep getting the following exception on the request.BeginGetResponse():
{System.Net.ProtocolViolationException: Operation is not valid due to the current state of the object.
   at System.Net.Browser.BrowserHttpWebRequest.BeginGetResponseImplementation()}
public void Send()
    {
        HttpWebRequest client = WebRequest.Create(new Uri(BaseUrl)) as HttpWebRequest;
        client.Method = "POST";
        client.ContentLength = MaxSerializationSize;
        client.BeginGetRequestStream(new AsyncCallback(RequestProceed), client);
    }

    private void RequestProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;

        StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
        MemoryStream ms = new MemoryStream();
        DataContractJsonSerializer ser = new     DataContractJsonSerializer(typeof(MyCustomClass));
        ser.WriteObject(ms, MyCustomClassObject);
        postDataWriter.Write(ms);
        postDataWriter.Close();

        request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);

    }

    private void ResponceProceed(IAsyncResult asuncResult)
    {
        var request = (HttpWebRequest) asuncResult.AsyncState;

        using (var resp = (HttpWebResponse) request.EndGetResponse(asuncResult))
        {
            using (var stream = resp.GetResponseStream())
            {
            }
        }
    }

I have tried so many ways to get this to work. Hoping someone can tell me where i'm going wrong. Thanks.

A: You need to close the request stream.  You are just closing the StreamWriter and not the underlying request stream.  While you are at it eliminate the superflous MemoryStream and have the DataContractJsonSerializer write directly to the Request stream.
 HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;

 using (Stream outStream = request.EndGetRequestStream(asyncResult));
 {
      DataContractJsonSerializer ser = new     DataContractJsonSerializer(typeof(MyCustomClass));
      ser.WriteObject(outStream, MyCustomClassObject);
      outStream.Flush();
      outStream.Close();
 }

 request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);

Also get rid of this line:-
 client.ContentLength = MaxSerializationSize;

Without also turning off AllowWriteStreamBuffering (which is only possible on the ClientHTTP implementation anyway) there is no need to set the ContentLength, that is done for you.


text:
Q: R Using paste inside of dyplyr functions to build a local function I am trying to use paste inside of a dplyr's summarize or rename to name a variable when building a local function. I'm getting an Error: unexpected '=' in: "    mutate(some.text= x) %>%     rename(paste('hp', x, sep= '')="
Here is an example:
data(mtcars)

get.information <- function(df, x) {
  df %>%
    group_by(hp) %>%
    summarize(paste('hp', x, sep= "")= n()) %>%
    mutate(some.text= x)
}

or
get.information <- function(df, x) {
  df %>%
    group_by(hp) %>%
    summarize(Frequency= n()) %>%
    mutate(some.text= x) %>%
    rename(paste('hp', x, sep= "")= Frequency)
}

get.information(mtcars, 2)

I'd appreciate any help, thanks in advance!

A: Try this:
get.information <- function(df, x) {
    var.name = paste0('hp', x)
    var.val = lazyeval::interp('Frequency')
    df %>%
        group_by(hp) %>%
        summarize(Frequency= n()) %>%
        mutate(some.text= x) %>%
        mutate_(.dots = setNames(list(var.val), var.name))

}


text:
Q: I'm having hard time understanding this solution to a direct proof of a algebraic statement, can someone explain why the following happens. For any positive real numbers, x and y, $x+y \geq \sqrt{xy} $
Assume that for real numbers, $x$ and $y$, $x > 0$ and $y > 0$ . We will show that $x+y \geq \sqrt{xy}$ .
Since $x > 0$ and $y > 0$ , then $xy > 0$. Also, $ x^2 > 0$ and $ y^2>0$ . Therefore,
$ x^2+xy+y^2>0 \quad$ (how did xy get here and remained positive)
Add $xy$  to both sides to get: $\quad$ (why add xy to both sides and where does it come from?)
$ x^2+2xy+y^2>xy$
Since $ (x+y)^2=x^2+2xy+y^2$
$(x+y)^2>xy$
Taking the square root of both sides gives:
$(x+y)>\sqrt{xy}$
Since $(x+y)>\sqrt{xy}$ , it is also true that $(x+y)\geq\sqrt{xy}$ $ \quad \square$


text:
Q: How to generate table schema from persistence.xml of jpa 2.1? I try to generate table schema with script file with eclipse and wildfly 8.1
This is my persistence.xml file.
<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
 version="2.1">

<persistence-unit name="MyFamily">
  <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>

  <properties>
   <property name="hibernate.show_sql" value="true"/>
   <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
   <property name="javax.persistence.schema-generation.create-source" value="script-then-metadata"/>
   <property name="javax.persistence.schema-generation.create-database-schemas" value="true"/>
   <property name="javax.persistence.schema-generation.scripts.drop-script-source" value="META-INF/drop-script.jdbc"/>
   <property name="javax.persistence.schema-generation.scripts.create-script-source" value="META-INF/create-script.jdbc"/>
   <property name="javax.persistence.sql-load-script-source" value="META-INF/load-script.jdbc"/>
   <property name="org.hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
  </properties>
 </persistence-unit>
</persistence>

And these are entity source and script files.
=== Entity
@Entity
@EntityListeners(Alarm.class)
@Table(name="family", indexes={@Index(columnList="EMP_ID"), @Index(columnList="EMP_NAME")})
public class Members implements Serializable {

 @Id
 @Column(name = "EMP_ID")
 private String ID;

 @Column(name = "EMP_Passwd")
 private String Passwd;

 @Column(name = "EMP_Age")
 private int Age;

 @Column(name = "EMP_Name")
 private String Name;

=== create-script.jdbc
CREATE TABLE family (
   EMP_ID VARCHAR(255) NOT NULL,
   EMP_PASSWD VARCHAR(255) NOT NULL,
   EMP_AGE INT NOT NULL,
   EMP_NAME VARCHAR(255) NOT NULL,

   PRIMARY KEY(EMP_ID)
)

But deployment throws the following exception:
15:05:58,728 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 55) MSC000001: Failed to start service jboss.persistenceunit."EJBLoginEAR.ear/EJBLoginModule.jar#MyFamily": org.jboss.msc.service.StartException in service jboss.persistenceunit."EJBLoginEAR.ear/EJBLoginModule.jar#MyFamily": javax.persistence.PersistenceException: Schema generation configuration indicated to include CREATE scripts, but no script was specified
 at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:172) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
 at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
 at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.7.0_60]
 at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:474)
 at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_60]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_60]
 at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_60]
 at org.jboss.threads.JBossThread.run(JBossThread.java:122)
Caused by: javax.persistence.PersistenceException: Schema generation configuration indicated to include CREATE scripts, but no script was specified
 at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$Generation.buildCreateSourceList(JpaSchemaGenerator.java:284) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$Generation.execute(JpaSchemaGenerator.java:133) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:76) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
 at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842) [hibernate-entitymanager-4.3.5.Final.jar:4.3.5.Final]
 at org.jboss.as.jpa.hibernate4.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44) [jipijapa-hibernate4-3-1.0.1.Final.jar:]
 at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
 ... 8 more

15:05:58,731 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) JBAS014613: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"JBAS014671: Failed services" => {"jboss.persistenceunit.\"EJBLoginEAR.ear/EJBLoginModule.jar#MyFamily\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"EJBLoginEAR.ear/EJBLoginModule.jar#MyFamily\": javax.persistence.PersistenceException: Schema generation configuration indicated to include CREATE scripts, but no script was specified
    Caused by: javax.persistence.PersistenceException: Schema generation configuration indicated to include CREATE scripts, but no script was specified"}}

How can I generate database schema with script files of persistence.xml in Wildfly 8?


text:
Q: Нет установленного модуля в PyCharm Понадобился модуль keyboard. Этот модуль я установил через pip, в pip freeze он есть. Захожу в проект, который уже был создан в IDE PyCharm, и мне выдает ошибку:

No module named 'keyboard'.

В это же время Visual Studio Code дает мне возможность использовать этот модуль.
Не знаете с чем это может быть связано? PyCharm перезапускал - не помогло.
И каким IDE Вы пользуетесь?

A: Если я правильно понял то, как ты написал, ты:

*

*В командной строке Windows делаешь py -m pip install keyboard или типа того?

*Заходишь в PyCharm и там не находишь этот Keyboard?

Если да, то:
PyCharm использует venv, это такая штука которая задает отдельную среду python, в которую можно устанавливать модули отдельно от общей установки.
Т.е. те модули, что у тебя в python через консоль винды и те модули что у тебя в проекте это два разных набора. Это позволяет тебе держать каждому проекту свои модули, и не заполнять общую установку модулями.
Тебе нужно открыть твой проект, и снизу PyCharm'а сделать вот так (вместо моей команды можешь использовать ту которую использовал в обычной консоли):

Использую PyCharm, это реально удобно.


text:
Q: Is it possible call a properties file to instance a user and password in Apache CXF Blueprint for a Web Service? I'm relative new with Fuse and WebServices.
I did a SOAP WebService with a BasicAuthAuthorizationInterceptor, this is the actual context and it's working:
<cxf:cxfEndpoint address="/SampleEp" id="insertSomethingToDB" serviceClass="com.example.sample_ep.SampleEp" wsdlURL="wsdl/SampleEP.wsdl">
    <cxf:inInterceptors>
        <ref component-id="securityInterceptor"/>
    </cxf:inInterceptors>
</cxf:cxfEndpoint>

<bean
    class="com.example.middleware.BasicAuthAuthorizationInterceptor" id="securityInterceptor">
    <property name="users">
        <map>
            <entry key="user" value="password"/>
        </map>
    </property>
</bean>

So, to add more security, I'll tried to put the users in a properties file outside the project, this is the idea:
<cxf:cxfEndpoint address="/SampleEp" id="insertSomethingToDB" serviceClass="com.example.sample_ep.SampleEp" wsdlURL="wsdl/SampleEP.wsdl">
    <cxf:inInterceptors>
        <ref component-id="securityInterceptor"/>
    </cxf:inInterceptors>
</cxf:cxfEndpoint>

<bean
    class="com.example.middleware.BasicAuthAuthorizationInterceptor" id="securityInterceptor">
    <property name="users">
        <map>
            <entry key="${cxf.user}" value="${cxf.password}"/>
        </map>
    </property>
</bean>

<bean> add some code to add a *.properties file outside the project </bean>

It is that possible?
Or I'm really bad with this?

A: Ok, I tried a few of things with Jasypt, JAAS and get the solution:
<ext:property-placeholder>
    <ext:location>file:/this/is/your/path/to/your/propertie/file/cxf.properties
    </ext:location>
</ext:property-placeholder>

<cxf:cxfEndpoint address="/SampleEp" id="insertSomethingToDB"
    serviceClass="com.example.sample_ep.SampleEp" wsdlURL="wsdl/SampleEP.wsdl">
    <cxf:inInterceptors>
        <ref component-id="securityInterceptor" />
    </cxf:inInterceptors>
</cxf:cxfEndpoint>

<bean class="com.example.middleware.BasicAuthAuthorizationInterceptor"
    id="securityInterceptor">
    <property name="users">
        <map>
            <entry key="${cxf.user}" value="${cxf.password}" />
        </map>
    </property>
</bean>

Just only add to your Blueprint header:
xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0"

And voilà, it's working with a secure user/pass validation outside your project :D
And the most important thing, the properties file needs this format:
#cxf.properties
cxf.user=administrator
cxf.password=password


text:
Q: Qt: SIGNAL, SLOT Macro declaration
Possible Duplicate:
Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros? (Qt)

I couldn't find on Google, the declaration of the macros, SIGNAL and SLOT, in Qt.
When we say, connect(button1, SIGNAL(clicked()), this, SLOT(slotButton1()));
I would like to understand, which all kinds of parameters does the highlighted macros accept?
Any link to doc would be appreciated.
The link I got through Neil's comment below says: #define     SLOT(a)   "1"#a and what does a represent here? It is not shown in that link.

A: As Neil said, the SLOT and SIGNAL macros are defined as
#define SLOT(a) "1"#a
#define SIGNAL(a) "2"#a

The #a (with # a stringizing operator) will simply turn whatever is put within the parentheses into a string literal, to create names from the signatures provided to the macros. The "1" and "2" are merely there to distinguish between slots and signals.
This earlier post should provide you some more insight.
If you wonder about the "why?" of all this macro stuff and preprocessing, I would suggest you read up on the "Meta-Object-Compiler" or MOC. And just for fun you could have a look at what MOC does to the code you provide it with. Look through its output and see what it contains. That should be quite informative.
In short, this preprocessing through MOC allows Qt to implement some features (like the signals and slots) which C++ does not provide as standard. (Although there are arguably some implementations of this concept, not related to Qt, which don't require a Meta Object Compiler)