text:
Q: Swap one TypeScript type with another inside an object I have the following types:
type Target = number | undefined;

type MyObject = {
    some: string;
    properties: string;
    id: Target;
}

I want to come up with a generic way to replace Target with number, like:
type MyObjectTransformed = TargetToNumber<MyObject>;

/**
 * MyObjectTransformed is now:
 *
 * {
 *     some: string;
 *     properties: string;
 *     id: number;
 * }
 */

It's easy if you know Target is always in the id field, I don't need help with that.
But what if Target could be anywhere? Like this should also work:
TargetToNumber<{
    some: string;
    other: Target;
    properties: string;
}>

And even worse... it also needs to work when it's nested! Like this should still replace Target with number:
TargetToNumber<{
    some: string;
    properties: string;
    nested: {
        arbitrarily: {
            deep: Target;
        };
    };
}>

If you're curious why I want to do such a strange thing, this is why I'm asking.

A: Using a conditional type: if the arbitrary type T is A or a subtype of A, we replace it with B, otherwise if it's an object type we map the properties recursively, otherwise we leave the type as T.
type TargetToNumber<T> = SubstituteType<T, Target, number>;

type SubstituteType<T, A, B> =
    T extends A
    ? B
    : T extends {}
    ? { [K in keyof T]: SubstituteType<T[K], A, B> }
    : T;

If you only want to substitute exactly A and leave subtypes of A alone (e.g. never is always a subtype...) you can replace T extends A with [A, T] extends [T, A] to test that they are the same type.
Playground Link


text:
Q: Trying to random several links youtube videos in iframe inside div trying to make a iframe with a random youtube links at page upload without any onclick

var glink = 0;
var games = new Array();

games[glink++] = "http://www.youtube.com/pRpvdcjkT3k";
games[glink++] = "http://www.youtube.com/Te4wx4jtiEA";

function randomglink() {
    var random = rand(glink) - 1;
    location.src = games[random];
}

A: The src attribute is not like an event (e.g. onclick ) that executes a javascript function to get its location/URL. But you can dynamically change the src attribute.
To have a script triggered on page load (without jQuery etc.)

In order to manipulate your iframe element, give it an id (has to be unique). In this example I named it videoFrame:

Then from your script, set the src attribute:
function randomglink() {
    var random = rand(glink) - 1;
    document.getElementById('videoFrame').src = games[random];
}

A: this help you :

redpajama_set_name: RedPajamaStackExchange


text:
Q: display data from sqlite to label using FMDB How to display data from SQLite to label using FMDB like this:

I would like to display whatever the output is in this format for the user to see. No Interaction. Only display for the select query.

A: You can accomplish the above by using a UITableView and custom UITableViewCells.
And you can maintain an array which will act as a data source to your view controller.
Considering that you want to have the same layout as you have shared (which has four labels per row), you will be fetching the data from a database.
Since, the data fetched from a database may keep on increasing, UITableView is your best bet when displaying long list of data as memory management and cell creation is handled automatically.
If you plan to have only labels then things can get tricky for you. Because if the number of rows that you fetch using select query is too much then you will end up creating a lot of views which will cause memory issues.
And, if you don't want you user to interact with any of the rows, then implement the following method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Here is a link for creating custom cells:
http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Here is a link for using table view:
http://www.appcoda.com/ios-programming-tutorial-create-a-simple-table-view-app/
Good Luck!!

A: If you want to add UILabel objects, just iterate through your result set, adding labels to your view. Something like:
NSInteger rowNum = 0;
NSArray *columnWidths = @[@(50), @(120), @(75), @(75)];
CGFloat rowHeight = 24.0;

FMResultSet *rs = [db executeQuery:sql];

while ([rs next])
{
    CGFloat x = 0.0;
    NSInteger colNum = 0;
    for (NSNumber *columnWidth in columnWidths)
    {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x,
                                                                    rowHeight * rowNum,
                                                                    [columnWidth floatValue],
                                                                    rowHeight)];
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.borderColor = [UIColor blackColor].CGColor;
        label.layer.borderWidth = 1.0;
        label.text = rs[colNum++];
        [self.view addSubview:label];
        x += [columnWidth floatValue];
    }
    rowNum++;
}

[rs close];

I just typed that in, so I'm sure there are typos in there, but hopefully it's enough to give you an idea of what it could look like. If there are too many rows to fit on a screen, you would add a scrollview to your view, and then add the labels as a subview to that.
I also think the tableview is a wonderful approach. Or dynamically built a HTML string that you show in a UIWebView. Tons of options here. It depends a little upon what your ultimate goal is here, the nature of the data, what sort of user interaction you want.


text:
Q: Can't make the ADC of stm32f4-discovery work I have a stm32f4-discovery with the stm32f407vg uC on it and I'm trying to program the ADC1 and measure some signals on the port PC5 with it. According to the documentation PC5 hangs on the ADC12_IN15 which I'm interpreting as ADC1 and ADC2 channel 15. I want to use the ADC_DMA example projects from the STD library STM32F4xx_DSP_StdPeriph_Lib_V1.6.1. The signal to the PC5 is provided by a signal generator and it's a square signal with frequency of 10 Hz, Vpp of 900 mV and offset of 2 V. Then I'm running the following code, which is successfully compiled and uploaded:
#define ADCx                     ADC1
#define ADC_CHANNEL              ADC_Channel_15
#define ADCx_CLK                 RCC_APB2Periph_ADC1
#define ADCx_CHANNEL_GPIO_CLK    RCC_AHB1Periph_GPIOC
#define GPIO_PIN                 GPIO_Pin_5
#define GPIO_PORT                GPIOC
#define DMA_CHANNELx             DMA_Channel_0
#define DMA_STREAMx              DMA2_Stream0
#define ADCx_DR_ADDRESS          ((uint32_t)0x4001224C)
static void ADC_Config(void);
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* ADC configuration */
  ADC_Config();

  /* Start ADC Software Conversion */
  ADC_SoftwareStartConv(ADCx);

  while (1)
  {
    uwADCxConvertedVoltage = uhADCxConvertedValue *3300/0xFFF;
  }
}

/**
  * @brief  ADC3 channel07 with DMA configuration
  * @note   This function Configure the ADC peripheral
            1) Enable peripheral clocks
            2) DMA2_Stream0 channel2 configuration
            3) Configure ADC Channel7 pin as analog input
            4) Configure ADC3 Channel7
  * @param  None
  * @retval None
  */
static void ADC_Config(void)
{
  ADC_InitTypeDef       ADC_InitStructure;
  ADC_CommonInitTypeDef ADC_CommonInitStructure;
  DMA_InitTypeDef       DMA_InitStructure;
  GPIO_InitTypeDef      GPIO_InitStructure;

  /* Enable ADCx, DMA and GPIO clocks ****************************************/
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
  RCC_AHB1PeriphClockCmd(ADCx_CHANNEL_GPIO_CLK, ENABLE);
  RCC_APB2PeriphClockCmd(ADCx_CLK, ENABLE);

  /* DMA2 Stream0 channel15 configuration **************************************/
  DMA_InitStructure.DMA_Channel = DMA_CHANNELx;
  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADCx_DR_ADDRESS;
  DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&uhADCxConvertedValue;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
  DMA_InitStructure.DMA_BufferSize = 1;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
  DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
  DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
  DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
  DMA_Init(DMA_STREAMx, &DMA_InitStructure);
  DMA_Cmd(DMA_STREAMx, ENABLE);

  /* Configure ADC1 Channel15 pin as analog input ******************************/
  GPIO_InitStructure.GPIO_Pin = GPIO_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIO_PORT, &GPIO_InitStructure);

  /* ADC Common Init **********************************************************/
  ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
  ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
  ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
  ADC_CommonInit(&ADC_CommonInitStructure);

  /* ADC1 Init ****************************************************************/
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfConversion = 1;
  ADC_Init(ADCx, &ADC_InitStructure);

  /* ADC1 regular channel15 configuration **************************************/
  ADC_RegularChannelConfig(ADCx, ADC_CHANNEL, 1, ADC_SampleTime_3Cycles);

 /* Enable DMA request after last transfer (Single-ADC mode) */
  ADC_DMARequestAfterLastTransferCmd(ADCx, ENABLE);

  /* Enable ADC1 DMA */
  ADC_DMACmd(ADCx, ENABLE);

  /* Enable ADC1 */
  ADC_Cmd(ADCx, ENABLE);
}

When I set a break point at the line
uwADCxConvertedVoltage = uhADCxConvertedValue *3300/0xFFF;

the variable is always zero. In addition I see no changes in the ADC1 registers or DMA2 registers during the operation and the SWSTART flag of the ADC_CR2 register is never set. The ADC_DR register is always 0 too. It seems like the function
ADC_SoftwareStartConv(ADCx);

fails to set the SWSTART flag and the conversion is never performed.
What could be wrong?

A: It looks like you're configuring the wrong DMA stream/channel. You select ADC1 but configure DMA_Channel_1. You'll need to configure DMA_Channel_0 using DMA_Stream_0. The following tables shows the DMA stream/channel configuration.

A: You have selected to have an external trigger, ADC_ExternalTrigConv_T1_CC1, but I can not see Timer1 configured and running. Select no external trigger instead, and call ADC_SoftwareStartInjectedConvCmd I believe.


text:
Q: How to Import Javafx8 in a bundle in OSGI I'm working on an OSGI application with Felix. Now I want to use some JavaFx8 classes in a bundle but I have the following error :
Unable to resolve 1.0: missing requirement [1.0] osgi.wiring.package; (osgi.wiring.package=javafx.geometry

How can I import JavaFx8 SDK packages in my bundle.
Thanks in advance,

A: You can add the library to the felix classpath and append the necesary package(s) to the org.osgi.framework.system.packages.extra option.
http://felix.apache.org/site/apache-felix-framework-configuration-properties.html
If you do so, the bundle no. 0 will export the required packages. I can provide more detailed instructions later my pc, right now i am on mobile.

A:
I'm working on an OSGI application with Felix. Now I want to use some
  JavaFx8 classes in a bundle
I need to create a complete GUI and I'll need an important number of
  imports.

I've released some Early Access versions of Drombler FX, a new Rich Client Platform for JavaFX based on OSGi (Apache Felix) and Maven.
As an application framework it makes sure JavaFX and OSGi will get started properly and it provides the main window.
You can read more about Drombler FX here: http://puces-blog.blogspot.ch/search/label/Drombler
There's a Getting Started page which explains how to create, build and run a Drombler FX sample application with a few simple steps.

A: After several researches, I finally fixed the problem by adding the packages I need in the pom.xml of the project :
<configuration><provision>
        <param>--platform=felix</param>
        <param>--noConsole</param>
        <param>--systemPackages=javafx.animation,javafx.application,javafx.collections,javafx.embed.swing,javafx.geometry,javafx.scene,javafx.scene.layout,javafx.scene.transform,javax.swing,javax.swing.border,org.osgi.framework</param>
      </provision></configuration>

or by adding the following properties to the same file ( pom of the project ):
<properties>
<org.osgi.framework.system.packages.extra>javafx.animation,javafx.application,javafx.collections,javafx.embed.swing,javafx.geometry,javafx.scene,javafx.scene.layout,javafx.scene.transform,javax.swing,javax.swing.border,org.osgi.framework
</org.osgi.framework.system.packages.extra>
<org.osgi.service.http.port>8080</org.osgi.service.http.port>
<org.osgi.service.http.port.secure>8443</org.osgi.service.http.port.secure>

For More information check the link.


text:
Q: ArcGIS Desktop cannot display TIFF image manipulated with GIMP (graphic software)? I used the graphic software program GIMP to manipulate a geoTIFF image (GIMP cannot handle geoTIFFs, so after manipulating the image in GIMP the geospatial information is lost).
When I now try to import the manipulated TIFF into ArcGIS 10.3.1, for some strange reason Arc displays the original TIFF image without any of the alterations I made in GIMP (outside ArcGIS, I see the manipulated version though)

A: ArcGIS displays raster images from Pyramids if they are present, and these are not automatically updated if you modify the image in a separate application (like your GIMP program).
To make your edited image visible in ArcMap again you need to remove all existing pyramids and then load the image into ArcMap.  You can then generate your pyramids again if you require them, based on the updated image.
See Checking if pyramids have been created and Raster pyramids for more info.


text:
Q: Bring element on top of modal backdrop I am trying to build a guide functionality for my application. As a part of this functionality, it is expected that a tooltip is shown next to the target HTML element and this target element is brought on top of modal backdrop that appears together with the tooltip.
The problem is that after significant effort I still cannot make HTML element show on top of the modal backdrop. Simple tricks like z-index: 10000 !important; position: relative do not help. Also changing parent elements' z-index by disabling it in Firefox Developer Tools (and leaving z-index: 10000 !important; position: relative for the target element that is supposed to be on top of the modal backdrop)  does not help.
HTML of the application is quite complex with many elements. But I want to be able to "highlight" any given element by bringing it on top of the modal overlay knowing only its id. Is there an easy way to do that with JavaScript/React?
Hopefully there is a way to do this without modifying the DOM, which would be highly preferable.
UPD: Code demo - press hat button to show guide/tooltips

A: Remove the z-index from .form-wrapper and apply relative position with z-index for the targetted elements.
I did this by  adding
d.classList.add("tooltip-active-element");

to App.js@77
Also added the class to the css file:
.tooltip-active-element {
  position: relative;
  z-index: 2;
  background: red;
}

and removed the z-index value from other classes, the key one being the .form-wrapper class.
Working demo:  https://codesandbox.io/s/tooltip-z-index-forked-fg9pt


text:
Q: How to show Messagebox from MVC Controller can anyone please tell about showing message box from MVC controller?
The scenario is -
I want to show a message box with Yes/No buttons. On clicking Yes i want to show a confirmation message box.
I want to do this using MVC controller?
How can I do this?
Thanks in advance,
Kaps

A: if (confirm('Are you sure?'))
{
$.post("Confirmation", {myresponse: 'yes'}, function(data)
{
$.("#mymodal").html(data);
}
}

That way it hits the actionmethod and lets it know that a yes confirmation was made and the actionmethod can send back the html markup.

A: Are you talking about the client message box? If so, try to use JavaScript's confirm dialog.

if (confirm('Are you sure?')){}

A: The Controller's action method generally does not control what the View renders, rather it simply states which view to display (ie. return this.View("MyView")) and the data the view should use to rendering itself if necessary.
You can use JavaScriptResult however you are breaking separation of concerns somewhat, the Controller should dictate which view to render, not what the view contains.
Here's a good write up on JavaScriptResult and why it's a bad idea: http://devlicio.us/blogs/billy_mccafferty/archive/2009/02/07/beware-of-asp-net-mvc-javascriptresult.aspx

A: I think you want to do something like this:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
On the controller side you want the method to return json.


text:
Q: CSS arrow positioning different in different browsers The position of the arrow line changes in different browsers. Can we solve this. I have used position:relative on the parent so this is not a duplicate question.
This works perfectly in Chrome but in Firefox it's an another story, the line following the arrow(: before) changes its position slightly to left. Can we solve this.?

span{
    font-size: 13px;
    margin-top: 5px;
    font-weight: 600;
    vertical-align: top;
    position: relative;
    padding-left: 12px;
    color:#00C16D;
}
span.up:after {
    content: '';
    position: absolute;
    border-left: 4.5px solid rgba(181, 41, 41, 0);
    border-bottom: 8px solid #00C16D;
    border-right: 4.5px solid rgba(221, 221, 221, 0);
    top: 0px;
    left: 0;
}
span.up:before {
    content: '';
    position: absolute;
    border-left: 3px solid #00C16D;
    bottom: 3px;
    left: 11%;
    height: 8px;
}
Up

A: I suspect this is due to pixel-rounding due to the use of fractional pixel values
span.up:after {
    content: '';
    position: absolute;
    border-left: 4.5px solid rgba(181, 41, 41, 0);
    border-bottom: 8px solid #00C16D;
    border-right: 4.5px solid rgba(221, 221, 221, 0);
    top: 0px;
    left: 0;
}

Try using whole pixel values.


text:
Q: How to access data/data folder in Android device? I am developing an app and I know my database *.db will appear in data/data/com.****.***
I can access this file from AVD in Eclipse with help of sqlite manager
But I can't access this file in my Android phone.
I googled it and it says I need to root my phone to do it, but I don't want to do that.
How can I access my data/data/..... directory in my Android phone "without rooting it"?
Can I change user permissions for the directory data/data..... without rooting it?

A: To backup from Android to Desktop
Open command line cmd and run this:
adb backup -f C:\Intel\xxx.ab -noapk your.app.package.
Do not enter password and click on Backup my data.
Make sure not to save on drive C root. You may be denied.
This is why I saved on C:\Intel.
To extract the *.ab file

*

*Go here and download: https://sourceforge.net/projects/adbextractor/

*Extract the downloaded file and navigate to folder where you extracted.

*run this with your own file names: java -jar abe.jar unpack c:\Intel\xxx.ab c:\Intel\xxx.tar

A: You could also try fetching the db using root explorer app. And if that does not work then you can try this:

*

*Open cmd

*Change your directory and go into 'Platform tools'

*Type 'adb shell'

*su

*Press 'Allow' on device

*chmod 777 /data /data/data /data/data/com.application.package /data/data/com.application.package/*

*Open DDMS view in Eclipse and from there open 'FileExplorer' to get your desired file

After this you should be able to browse the files on the rooted device.

A: Accessing the files directly on your phone is difficult, but you may be able to copy them to your computer where you can do anything you want with it.
Without rooting you have 2 options:

*

*If the application is debuggable you can use the run-as command in adb shell
adb shell
run-as com.your.packagename
cp /data/data/com.your.packagename/

*Alternatively you can use Android's backup function.
adb backup -noapk com.your.packagename

You will now be prompted to 'unlock your device and confirm the backup operation'. It's best NOT to provide a password, otherwise it becomes more difficult to read the data. Just click on 'backup my data'. The resulting 'backup.ab' file on your computer contains all application data in android backup format. Basically it's a compressed tar file. This page explains how you can use OpenSSL's zlib command to uncompress it.
You can use the  adb restore backup.db command to restore the backup.

A: may be to access this folder you need administrative rights.
so you have two options:-

*

*root your device and than try to access this folder

*use emulator

p.s. : if you are using any of above two options you can access this folder by following these       steps

open DDMS perspective -> your device ->(Select File Explorer from
  right window options)  select package -> data -> data -> package name
  ->files

and from there you can pull up your file

A: I had also the same problem once. There is no way to access directly the file within android devices except adb shell or rooting device.
Beside here are 02 alternatives:
1)
 public void exportDatabse(String databaseName)
   {
     try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
            String backupDBPath = "backupname.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {

    }
}

2) Try this: https://github.com/sanathp/DatabaseManager_For_Android

A: On a rooted device, the correct solution is this:
Open cmd
Change your directory and go into 'Platform tools'
Type 'adb shell'
su
Press 'Allow' on device
chmod 777 /data /data/data /data/data/*
Open DDMS view in Eclipse/IntelliJ and from there open 'FileExplorer' to get your desired file

The original solution worked, but the chmod would return unknown directory. Changing the chmod command to /data/data/* gave access to all subfolders in the data directory from DDMS in Intellij. I assume the same solution is true for Eclipse DDMS.
UPDATE
So, what I've found is strange. I'm running a Nexus 6 using DDMS in IntelliJ (Android Device Monitor). I have built a little starter app. Said app saves data to a .csv file in data/data/com.example.myapp/files
When I first started to try to access this file on my Nexus 6, I found that I have to root the device.. I could see the data folder, but trying to open it would not work. As mentioned online in other places, the expand + would vanish then reappear shortly thereafter (note, there are solutions on the web that claim to allow access to these folders without rooting, I didn't find them till too late, and I'm not sure if I prefer not to root anyway ((I'd rather be able to do it manually than rely on an app or command prompt to give me my solutions))). I rooted my 6 and tried DDMS again.
At this point, it showed me the data folder and I could expand the folder and see the com. directories, but I could not open any of them. That is when I discovered the above solution. The initial instructions would not work on this part:
chmod 777 /data /data/data /data/data/com.application.pacakage /data/data/com.application.pacakage/*

That is when I tried the solution I posted:
chmod 777 /data /data/data /data/data/*

That solution seemed to work, but only on certain folders. I now could expand my myapp folder, but could not expand the files directory in it.
At this point, I played around for a while then figured why not just try it on the directory I need rather than trying these wildcard entries.
chmod 777 /data /data/data /data/data/com.example.myapp/*

Followed by:
chmod 777 /data /data/data /data/data/com.example.myapp/files

These commands allowed me to expand and view the files in my app's directory to confirm that the .csv was being saved correctly.
Hope this helps someone. I struggled with this for hours!
(to compound on this a tad further, oddly enough, the permissions did not pass to the .csv file that passed to the files directory. my files directory permissions read drwxrwxrwx and my log.csv file permissions read -rw-rw---- .. just fyi)

A: You can download a sigle file like that:
adb exec-out run-as debuggable.app.package.name cat files/file.mp4 > file.mp4
Before you download you might wan't to have a look at the file structure in your App-Directory. For this do the following steps THelper noticed above:
adb shell
run-as com.your.packagename
cd files
ls -als .

The Android-Studio way Shahidul mentioned (https://stackoverflow.com/a/44089388/1256697) also work. For those who don't see the DeviceFile Explorer Option in the Menu: Be sure, to open the /android-Directory in Android Studio.
E.g. react-native users have this inside of their Project-Folder right on the same Level as the /ios-Directory.

A: adb backup didn't work for me, so here's what I did (Xiaomi Redmi Note 4X, Android 6.0):
1. Go to Settings > Additional Settings > Backup & reset > Local backups.
2. Tap 'Back up' on the bottom of the screen.
3. Uncheck 'System' and 'Apps' checkmarks.
4. Tap detail disclosure button on the right of the 'Apps' cell to navigate to app selection screen.
5. Select the desired app and tap OK.
6. After the backup was completed, the actual file need to be located somehow. Mine could be found at /MIUI/backup/AllBackup/_FOLDER_NAMED_AFTER_BACKUP_CREATION_DATE_.
7. Then I followed the steps from this answer by RonTLV to actually convert the backup file (.bak in my case) to tar (duplicating from the original answer):
"
a) Go here and download: https://sourceforge.net/projects/adbextractor/
b) Extract the downloaded file and navigate to folder where you extracted.
c) run this with your own file names: java -jar abe.jar unpack c:\Intel\xxx.ab c:\Intel\xxx.tar
"

A: To do any of the above (i.e. access protected folders from within your phone itself), you still need root.  (That includes changing mount-permissions on the /data folder and accessing it)
Without root, accessing the /data directly to read except from within your application via code isn't possible. So you could try copying that file to sdcard or somewhere accessible, and then, you should be able to access it normally.
Rooting won't void your warranty if you have a developer device. I'm sorry, there isn't any other way AFAIK.

A: Simple answer is NO. On upcoming Android 13, you can't access anything in
/storage/emulated/0/Android/*
directory without Rooting your device or hooking up to a PC, certainly not in Pixel devices.
Read Android Source page for such App data access using ADB here:
https://developer.android.com/training/data-storage/manage-all-files

A: If you are using Android Studio 3.0 or later version then follow these steps.

*

*Click View > Tool Windows > Device File Explorer.

*Expand /data/data/[package-name] nodes.

You can only expand packages which runs in debug mode on non-rooted device.

A: *

*Open your command prompt

*Change directory to E:\Android\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\sdk\platform-tools

*Enter below commands

*adb -d shell

*run-as com.your.packagename cat databases/database.db > /sdcard/database.db

*Change directory to cd /sdcard to make sure database.db is there.

*adb pull /sdcard/database.db or simply you can copy database.db from device .

A: The easiest way (just one simple step) to pull a file from your debuggable application folder (let's say /data/data/package.name/databases/file) on an unrooted Android 5.0+ device is by using this command:
adb exec-out run-as package.name cat databases/file > file

A: Use File Explorer in eclipse. Select Windows => Show View => Other ... => File Explorer.
An another way is pull the file via adb:
adb pull /system/data/data/<yourpackagename>/databases/<databasename> /sdcard

A: One of the simple way is to create your database on SD-Card. Because you cannot get access to your phone's data folder in internal memory, unless you root your phone. So why not simply create your database on SD-Card.
Moreover, if you want, you may write some file copying-code to copy your existing database file (from internal memory) to external memory without requiring any root.

A: you can copy this db file to somewhere in eclipse explorer (eg:sdcard or PC),and you can use sqlite to access and update this db file .

A: You can also try copying the file to the SD Card folder, which is a public folder, then you can copy the file to your PC where you can use sqlite to access it.
Here is some code you can use to copy the file from data/data to a public storage folder:
private void copyFile(final Context context) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath =
                    context.getDatabasePath(DATABASE_NAME).getAbsolutePath();

            String backupDBPath = "data.db";

            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

A: SQLlite database is store on user's Phone and it's hidding under path:
/Data/Data/com.companyname.AppName/File/

you have 2 options here:

*

*you can root your phone so that you get access to view your hidding
db3 file

*this is not a solution but a work around. Why not just create test
page that display your database table in it using 'select' statment.


text:
Q: Passing WebResponse Byte Array to function to extract image There are many suggestions for using the Image.FromStream(stream) on the Internet and look like they should do what I want. However, there is just one piece I don't fully understand.
I am making a GET request to a URL that returns a Byte Array which is an image. I make the request and get the response like this:
Public Function getPic(ByRef stu As String) As Image

    Dim url As String = "myurl" & stu 'identifying number I am adding to the url
    Dim hwrequest As HttpWebRequest = Net.WebRequest.Create(url)
    hwrequest.Method = "Get"

    Dim hwresponse = hwrequest.GetResponse().GetResponseStream()
    Dim ms As New MemoryStream()
    hwresponse.CopyTo(ms)
    Dim img As Image
    img = Image.FromStream(ms)

    PictureBox1.Image = img

End Function

I have found two different code suggestions:
Public Function byteArrayToImage(ByVal byteArrayIn As Byte()) As Image
    Using mStream As New MemoryStream(byteArrayIn)
        Return Image.FromStream(mStream)
End Function

Here I understand I need to pass the Byte Array from my response to the function but that is where my understanding is lacking. When I pass in
 Public Function byteArrayToImage(ByVal hwresponse As Byte()) As Image
    Using mStream As New MemoryStream(hwresponse)
        Return Image.FromStream(mStream)

I get "Value of Stream cannot be converted to Byte"
When I try this code:
Private Function BytesToImage(hwresponse AS Stream) As Image
Dim imgNew As Image
Dim memImage As New System.IO.MemoryStream(hwresponse)
imgNew = Image.FromStream(memImage)
Return imgNew

End Function
I get "Parameter not valid" on Image.fromStream.
I am not understanding how to take my WebResponse and pass it to the function correctly to extract the image


text:
Q: Taking two streams and combining them in OCaml I want to take two streams of integers in increasing order and combine them into one stream that contains no duplicates and should be in increasing order. I have defined the functionality for streams in the following manner:
type 'a susp = Susp of (unit -> 'a)
let force (Susp f) = f()

type 'a str =  {hd : 'a ; tl : ('a str) susp }

let merge s1 s2 = (* must implement *)

The first function suspends computation by wrapping a computation within a function, and the second function evaluates the function and provides me with the result of the computation.
I want to emulate the logic of how you go about combining lists, i.e. match on both lists and check which elements are greater, lesser, or equal and then append (cons) the integers such that the resulting list is sorted.
However, I know I cannot just do this with streams of course as I cannot traverse it like a list, so I think I would need to go integer by integer, compare, and then suspend the computation and keep doing this to build the resulting stream.
I am at a bit of a loss how to implement such logic however, assuming it is how I should be going about this, so if somebody could point me in the right direction that would be great.
Thank you!

A: If the the input sequences are sorted, there is not much difference between merging lists and sequences. Consider the following merge function on lists:

let rec merge s t =
  match s, t with
  | x :: s , [] | [], x :: s -> x :: s
  | [], [] -> s
  | x :: s', y :: t' ->
    if x < y then
      x :: (merge s' t)
    else if x = y then
      x :: (merge s' t')
    else
       y :: (merge s t')

This function is only using two properties of lists:

*

*the ability to split the potential first element from the rest of the list

*the ability to add an element to the front of the list

This suggests that we could rewrite this function as a functor over the signature
module type seq = sig
  type 'a t

  (* if the seq is non-empty we split the seq into head and tail *)
  val next: 'a t -> ('a * 'a t) option

  (* add back to the front *)
  val cons: 'a -> 'a t -> 'a t
end

Then if we replace the pattern matching on the list with a call to next, and the cons operation with a call to cons, the previous function is transformed into:
module Merge(Any_seq: seq ) = struct

  open Any_seq

  let rec merge s t =
    match next s, next t with
    | Some(x,s), None | None, Some (x,s) ->
      cons x s
    | None, None -> s
    | Some (x,s'), Some (y,t') ->
      if x < y then
        cons x (merge s' t)
      else if x = y then
        cons x (merge s' t')
      else
        cons y (merge s t')

end

Then, with list, our implementation was:
module List_core = struct
  type 'a t = 'a list
  let cons = List.cons
  let next = function
  | [] -> None
  | a :: q -> Some(a,q)
end
module List_implem = Merge(List_core)

which can be tested with
let test = List_implem.merge [1;5;6] [2;4;9]

Implementing the same function for your stream type is then just a matter of writing a similar Stream_core module for stream.


text:
Q: How to check for cancel button in custom action without doing anything else I know when I put something in the log using ::MsiProcessMessage(hModule, INSTALLMESSAGE(INSTALLMESSAGE_INFO), ...); that I can check if the return value is IDCANCEL and return ERROR_INSTALL_USEREXIT to Windows installer.
How do I check for that return value without having to put something in the log or alter the progress bar?

A: I believe the call you describe will place the info message in the log. But other than that, why would you have to put something in the log or alter the progress bar? If your action takes a long time, it should report progress. If it is short and you never call MsiProcessMesssage, Windows Installer will handle cancel immediately afterward. The only problem case is if you call MsiProcessMessage and swallow a cancel without reporting it.


text:
Q: C# illegal characters in the path I am getting illegal characters in the path by using the below codes:
string fileNameExisting = Application.StartupPath + "\\CodesLocation\\Template.pdf";
PdfReader templateFile = new PdfReader(fileNameExisting);

I tested a few variations:
string fileNameExisting = @Application.StartupPath + "\CodesLocation\Template.pdf";
PdfReader templateFile = new PdfReader(fileNameExisting);

But it is still getting the same illegal error.
Can anyone help me see if my code if wrong?
Thanks.

A: An at in front of a string literal turns off \ escaping (in front of a variable it explicitly marks a variable as not a keyword):
Path.Combine(Application.StartupPath, @"CodesLocation\Template.pdf");

And Path.Combine is the state of the art way to concatenate paths (platform independent, takes care of additional slashed).

A: You should best use
Path.Combine(Application.StartupPath, "CodesLocation\\Template.pdf").
Other than that check if Application.StartupPath ends with \.

A: I suggest using the appropriate way to join paths in .net:
Path.Combine
So
Path.Combine(Application.StartupPath, "CodesLocation","Template.pdf");


text:
Q: Check for duplicates in a text form field I am a VBA noob and I'm trying to compare the numbers entered in a text form field in ms word, then if a duplicate is found I display a msg box.
The problem I'm having is... I have to compare 33 fields and look for a duplicate of anywhere from 1 to 33. I'm receiving a message that the procedure is too large. I'm sure there must be an easier way to do this. It's a protected document which I unprotect once the user hits the command button. I've even tried breaking it up and assigning macros to some of the fields.
Here is a sample of what I have. There are 33 bookmarks and I'm comparing each field.
If (ActiveDocument.FormFields("s1").Result = "1" And _
ActiveDocument.FormFields("s2").Result = "1") Then
MsgBox ("Your preferences cannot be duplicated.")
 Validate = True
    If True Then Exit Sub
  Else
    Validate = False
End If

A: Perhaps:
Sub CompareFormfields()
Dim i As Long, j As Long
With ActiveDocument
  For i = 1 To .FormFields.Count - 1
    For j = i + 1 To .FormFields.Count
      If (.FormFields(i).Type = wdFieldFormTextInput) And (.FormFields(i).Type = wdFieldFormTextInput) Then
        If .FormFields(i).Result = .FormFields(j).Result Then
          MsgBox "The data in FormField " & i & " is duplicated in FormField " & j
        End If
      End If
    Next
  Next
End With
MsgBox "Done checking"
End Sub


text:
Q: for a compact manifold $M$, is the dual space of $H^1(M)$ equal to $H^{-1}(M)$? Let $M$ be a compact Riemannian manifold. Is it true that
$$(H^1(M))^* = H^{-1}(M)?$$
is there some intuitive explanation why? Or some reference? Thanks
Here $H^1$ is the usual Sobolev space of $u \in L^2(M)$ with $\nabla u \in L^2(M)$.

A: No, we only define the dual of $(H_0^1(M))$ is $H^{-1}(M)$, but not $H^1(M)$. Although the dual of $H^1(M)$ does exist, and it is smaller then $H^{-1}(M)$.
If you want an intuitive explanation, I recommend you to read the definition by Fourior transform then you will see the dual of $H^s$ is $H^{-s}$, not by definition but by computation.


text:
Q: Clustering large 3D dataset into many clusters I have a 3D point cloud with several million points and I need to partition it into roughly 50k clusters. As the clusters have to be spherical, usually a drawback of k-means, k-means seems pretty appropriate. My problem is that $k$ is too big, thus the runtime is unacceptable. The clusters don't have to be exact, I can tolerate misclassifications quite well.
I found a paper on mini-batch k-means, which might work. And this paper utilizing MapReduce. I also read this and other questions, but question and answers are too vague. This (slide 2) source claims with the use of k-d trees runtime can be reduced from $O(l*K*m*n)$ to $O(m*logm)$, I can't find how that should work?
Is mini-batch k-means the way to go? Is there maybe some simple solution for low dimensional data (3D)?
I would appreciate a C++ implementation, so far I could only find mini batch k-means in scikit which I might translate. Can you recommend any other?

A: I have seen people use OPTICS on millions of points, but that won't create "spherical" clusters.
Probably something extremely simple like LEADER is what you want.
K-means with large k is pretty problematic. First of all, the runtime scales badly with k, and secondly on noisy data you will have clusters with just one outlier quite often.
For just 3 dimensional data, k-d-trees are definitely worth a try. In particular for large k. However these methods are not easy to implement. You'd need a nearest-neighbor join of two trees (one with the data, one with the centers). That requires some pretty complex data management that is not fun to do, and I don't know any k-d-tree library that would provide this functionality.
Mini-batch k-means won't help you much either. The batch sizes must be much larger than k. Plus, it never converges. So you'd need to run it as long as you can afford and then hope the result is good enough. That is okay for visual-bag-of-words but not for many other cases.


text:
Q: bindingConfiguration vs bindingName What exactly is the difference between bindingConfiguration and bindingName elements in a WCF endpoint element?  The reason that I ask is I am creating an endpoint which uses basicHttpBinding and SSL.  I configured the web.config like this:
<basicHttpBinding>
<binding name="basicHttps">
  <security mode="Transport">
    <transport clientCredentialType="None"/>
  </security>
</binding>

<endpoint binding="basicHttpBinding" bindingConfiguration="basicHttps" contract="Hsp.Services.Interface.Catalog.ICatalogService" address="" />

However, when using bindingConfiguration then https isn't working.  When I change bindingConfiguration to bindingName it works as expected.  So, what exactly is the difference between the two?

A: From the MSDN documentation
bindingConfiguration: A string that specifies the binding name of the binding to use when the endpoint is instantiated. The binding name must be in scope at the point the endpoint is defined. The default is an empty string. This attribute is used in conjunction with binding to reference a specific binding configuration in the configuration file. Set this attribute if you are attempting to use a custom binding. Otherwise, an exception may be thrown.
bindingName: A string that specifies the unique qualified name of the binding for definition export through WSDL. The default is an empty string.
I've never used bindingName, but it seems to only affect the WSDL generated for your endpoint. If something isn't working when you use bindingConfiguration="basicHttps", then it sounds like you have a misconfiguration that's preventing it from working correctly (if no bindingConfiguration is specified, the defaults will be applied, which is what's happening when you change bindingConfiguration to bindingName). I don't think <transport clientCredentialType="None"/> is valid, the possible values are Basic, Certificate, Digest, Windows, or NTLM. See Transport Security Overview

A: Your service configuration binding is incorrect. So when you correctly refer to your binding configuration using the bindingConfiguration attribute, your service is not working. When you use the bindingName attribute, which is an invalid used attribute in your case, the service just starts a basicHttpBinding without looking at your custom configuration, which seems to work correctly.
For the different between the two elements look at: http://msdn.microsoft.com/en-us/library/ms731320.aspx.
So, using the bindingConfiguration attribute is the only correct thing. Now we still need to look at what is wrong with you binding configuration itself :-) See the following example to extract your relevant information from.
<system.web.extensions>
  <scripting>
    <webServices>
      <authenticationService enabled="true"
         requireSSL = "true"/>
    </webServices>
  </scripting>
</system.web.extensions>
<system.serviceModel>
  <services>
    <service name="System.Web.ApplicationServices.AuthenticationService"
        behaviorConfiguration="AuthenticationServiceTypeBehaviors">
      <endpoint contract=
        "System.Web.ApplicationServices.AuthenticationService"
        binding="basicHttpBinding"
        bindingConfiguration="userHttps"
        bindingNamespace="http://asp.net/ApplicationServices/v200"/>
      </service>
  </services>
  <bindings>
        <basicHttpBinding>
            <binding name="userHttps">
                <security mode="Transport" />
            </binding>
        </basicHttpBinding>
  </bindings>
  <behaviors>
    <serviceBehaviors>
      <behavior name="AuthenticationServiceTypeBehaviors">
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment
    aspNetCompatibilityEnabled="true"/>
</system.serviceModel>

See http://msdn.microsoft.com/en-us/library/bb398990.aspx for more details.

A: The binding= attribute just defines, which binding (protocol) you want - basicHttpBinding, wsHttpBinding, netTcpBinding etc.
Those bindings all have system default values - if you don't specify any binding configuration, those system defaults will be used.
What you've defined in your <bindings> section of your config is a binding configuration - a set of parameters for your binding of choice that will be used instead of the system defaults.
So the binding= and the bindingConfiguration= need to match - you cannot define one binding (e.g. basicHttpBinding) but then assign a binding configuration for a different binding.
That however still doesn't explain why your https doesn't work - that must be some other problem. Can you elaborate a bit more? How does it not work? Just no response, or do you get an error (if so: what is that error??)

A: bindingConfiguration
A string that specifies the binding name of the binding to use when the endpoint is instantiated. The binding name must be in scope at the point the endpoint is defined. The default is an empty string.
This attribute is used in conjunction with binding to reference a specific binding configuration in the configuration file. Set this attribute if you are attempting to use a custom binding. Otherwise, an exception may be thrown.
bindingName
A string that specifies the unique qualified name of the binding for definition export through WSDL. The default is an empty string.


text:
Q: Using Classes when Python Scripting for Maya I am working through  Maya Programming with Python Cookbook by Adrian Herbez and having trouble with an example (pg. 31) which creates a class which produces a user interface for making simple spheres in Maya. When I reproduce the code and run the script it loads but nothing happens in Maya. I was able to create user interfaces without using the class method previously so I am wondering if there is something wrong with the class code. My understanding of classes is a bit shaky but I can't find what could be wrong with it. I am using Atom and calling the script using
import(makeSpheres) and reload(makeSpheres).
Here is the code:
import maya.cmds as cmds

class SpheresClass:
    def __init__(self):
        self.win = cmds.window(title="Make Spheres",widthHeight=(300,200))
        cmds.columnLayout()
        self.numSpheres = cmds.intField(minValue=1)
        cmds.button(label="Make some spheres", command=self.makeSpheres)
        cmds.showWindow(self.win)

    def makeSpheres(self, *args):
        number = cmds.intField(self.numSpheres,query=True,value=True)
        for i in range(0,number):
            cmds.polySphere()
            cmds.move(i*2.2,0,0)

        SpheresClass()

In Atom the self.win,self.numSpheres and self.makeSpheres is being highlighted in red but but the linter doesn't have any error messages.

A: Turns out I was calling the SpheresClass from within the makeSpheres function.


text:
Q: cannot POST /graphql (404) error when running e2e test in jest (GraphQL Federation) I am trying to test my graphql service end to end using supertest + jest in a Nest.js application but keep getting this error:

Error: cannot POST /graphql (404)

I have tried many things but couldn't get the test to run completely due to that error.
Below is my test file:
import request from 'supertest';
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { GatewayAppModule } from '../../../app-gateway.module';
import { AppModule } from '../../../app.module';
import { CreateAccountArgs } from '../dto/create-account.args';

jest.mock('graphql-moment', () => ({
  GraphQLDate: jest.fn(),
}));

describe('Auth resolver: Authentication module e2e test', () => {
  let mainApp: INestApplication;
  let gatewayApp: INestApplication;

  beforeAll(async () => {
    const mainAppModuleRef: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    mainApp = mainAppModuleRef.createNestApplication();
    await mainApp.init();

    const gatewayModuleRef: TestingModule = await Test.createTestingModule({
      imports: [GatewayAppModule]
    }).compile();

    gatewayApp = gatewayModuleRef.createNestApplication();
    await gatewayApp.init();
  });

  afterAll(async () => {
    jest.clearAllMocks();
    await mainApp.close();
    await gatewayApp.close();
  });

  describe('registerAccount mutation: Create a new account', () => {
    const mockUser: CreateAccountArgs = {
      firstName: 'TestUserFirstName',
      lastName: 'TestUserLastName',
      email: "TestUser@email.com",
      password: 'TestUserPassword',
    };

    it('should register a new user account with correct user information', async () => {
      const response = await request(mainApp.getHttpServer())
      .post('/graphql')
      .send({
        query:
        `mutation {registerAccount(registerAccount: ${mockUser}) {accessToken}}`,
      })
      console.log(response.error, '==========================>')
      expect(response.status).toBe(201);
    });
  });
});

Below is the error I get after logging to the console:
Expected: 201
    Received: 404

      53 |       })
      54 |       console.log(response.error, '==========================>')
    > 55 |       expect(response.status).toBe(201);
         |                               ^
      56 |     });
      57 |   });
      58 | });

      at Object.<anonymous> (src/modules/auth/tests/auth.e2e.spec.ts:55:31)

  console.log
    Error: cannot POST /graphql (404)
        at Response.toError (/Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/superagent/src/node/response.js:95:15)
        at Response._setStatusProperties (/Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/superagent/src/response-base.js:126:48)
        at new Response (/Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/superagent/src/node/response.js:41:8)
        at Test._emitResponse (/Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/superagent/src/node/index.js:928:20)
        at IncomingMessage.<anonymous> (/Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/superagent/src/node/index.js:1130:38)
        at IncomingMessage.emit (events.js:327:22)
        at IncomingMessage.EventEmitter.emit (domain.js:482:12)
        at endReadableNT (_stream_readable.js:1221:12)
        at processTicksAndRejections (internal/process/task_queues.js:84:21) {
      status: 404,
      text: '<!DOCTYPE html>\n' +
        '\n' +
        '\n' +
        '<meta charset="utf-8">\n' +
        '<title>Error</title>\n' +
        '\n' +
        '\n' +
        '
Cannot POST /graphql
\n' +
        '\n' +
        '\n',
      method: 'POST',
      path: '/graphql'
    } ==========================>

      at Object.<anonymous> (src/modules/auth/tests/auth.e2e.spec.ts:54:15)


text:
Q: php foreach is outputting everything twice everything works fine, but the output is being listed twice.
so it echos out: 'output a' 'output a' 'output b' 'output b' 'output c' 'output c' and so on.
when i do a mysql query in phpmyadmin, everything is only listed once.
any ideas?
what my code is doing is going and getting a many-to-many field
<?
    $something = mysql_query('select UserID from users where Username ="'. $username .'"');
    while ($row = mysql_fetch_array($something)) {
        $barf = $row['UserID'];
    }
    $result = mysql_query('SELECT name FROM items p LEFT JOIN list up ON p.item_id = up.item_id WHERE up.UserID =  "' . $barf . '"');
    while ($r = mysql_fetch_array($result)) {
        foreach($r as $uue) {
            echo $uue . '
';}
        }
    }
?>

A: Try this code:
while ($r = mysql_fetch_assoc($result)){
  foreach($r as $uue) {
    echo $uue . '
';
  }
}

You get duplicate results because by default (MYSQL_BOTH flag) mysql_fetch_array returns 2x sized array : number-indexed + string-indexed.
So, for example $r[0] and $r['name'] will be different elements in the array that contain the same values.
Also, you should stop using mysql_* as it is deprecated. Read on mysqli_* functions.

A: Here is an example using a single query with a sub query. No need to do 2 loops when mysql can give you the data you need on the first run. Also the extra foreach loop in your while isn't needed since your data is being returned as an array of columns. You can just echo what you want by index. Since you are only pulling one column you can echo $r['name'] or if you do MYSQL_NUM you can do $r[0].
<?
$escaped_username = mysql_real_escape_string($username);
$query = <<<SQL
SELECT
    name
FROM
    items p
    LEFT JOIN list up ON p.item_id = up.item_id
WHERE
    up.UserID = (SELECT UserID FROM users WHERE Username = '{$escaped_username}')
SQL;

$result = mysql_query($query);
while ($r=mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo $r['name'] . '
';
}
?>

Also using mysqli would probably be a better route to take as others have said. You can go the procedural route which would be pretty much replacing mysql_ with mysqli_ or you can go the object oriented route.
<?
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$result = $mysqli->query($query);

while ($r = $result->fetch_object()) {
    echo $r->name . '
';
}
?>

A: regardless of your true answer which is for @jari i think, Why you don't use just a simply echo $r[0]. '
'; or echo $r['name']. '
'; instead of that extra foreach


text:
Q: LiveData transformations map functionality Recently i've been learning transformations methods on LiveData
I know that we can use map or switchMap method to transform livedata.
Let's say we have Player data class similar below
data class Player(val name: String, val score: Int = 0)

And we use map method to transform player livedata to playerName livedata
val player: LiveData<Player> = ...

val playerName: LiveData<String> =
    Transformations.map(player) { it.name }

My question is, what is the difference doing it in observer function as they both run in main thread? I mean, if we want  to get playerName then we can get it in observer function too. Why we declare second LiveData instance to get that
I took example code from this guide : https://proandroiddev.com/livedata-transformations-4f120ac046fc

A: Assuming Observer is part of Android UI which is Activity or Fragment and LiveData is part of ViewModel,

*

*Doing the transformations in Observer will be local to that Observer, if Activity gets restarted due to any Config changes, your data inside Activity will be destroyed unless you save it somehow, but LiveData persists activity recreation, so if you have transformation in Observer side, it have to do it every time , but in case of LiveData, transformed data will be cached and will be provided every time you call it.

*Second thing is UI should be as dumb as possible, make all your data transformations before data reaches the UI. This way you can test your transformations using Unit Test without actually needing to rely on UI.


text:
Q: what type of sql agent jobs are these with weird name Name of the job is :- E14DF5CB-E9A1-49B7-9ECD-A1EDBFC7993E
and there are many more like this.

A: It looks like the job_id may have been used as the name, you will have to dig into it yourself.
Start by looking in msdb.dbo.sysjobs
SELECT
    job_id,
    name,
    date_created,
    date_modified,
    job_owner=suser_sname(owner_sid)
FROM msdb.dbo.sysjobs
WHERE job_id = 'E14DF5CB-E9A1-49B7-9ECD-A1EDBFC7993E'
OR name = 'E14DF5CB-E9A1-49B7-9ECD-A1EDBFC7993E'

A: Actually I got it. These are system generated report server jobs which gets created as soon as you will configure reporting service config manager.


text:
Q: closure of polynomial mapping is irreducible I'm working on an exercise from Kunz' Into to Algebraic Geometry which I've paraphrased:
Let $L|K$ be a field extension where $L$ infinite. Given $f_1,\cdots,f_n \in K[t_1,\cdots,t_m]$, let $V$ denote the closure (in the Zariski topology over $k^n$) of the set $V_0=\{(f_1(t_1,\cdots,t_m),\cdots,f_n(t_1,\cdots,t_m)),(t_1,\cdots,t_m)\in L^m\}$. Show that $V$ is irreducible.
(hint: Consider the $K$-homomorphism $K[x_1,\cdots,x_n]\rightarrow K[t_1,\cdots,t_m]$ defined by sending $x_i\to f_i(t_1,\cdots,t_m)$, then recall that the complement of any nontrivial variety in $L^n$ is infinite.)
My approach is to show the ideal of $V$, $\mathbb{J}(V)=\{f:f(x_1,\cdots,x_n)=0,(x_1,\cdots,x_n)\in L^n\}$, is prime. Also note that $\mathbb{J}(V)$ is the kernel of the mapping
\begin{equation}
\Phi:K[x_1,\cdots,x_n]\rightarrow K[t_1,\cdots,t_m]
\end{equation}
defined in the hint. So by the first isomorphism theorem, $\mathbb{J}(V)$ is prime if and only if $Im(\Phi)$ is an integral domain. It would then be sufficient to show that $\Phi$ is surjective, but I don't know if this is the case, or how to prove it if it is. I'm also not sure where I'd be using the fact that the complement of any variety is infinite.


text:
Q: cant displaying operator in php I am trying to make a math game where two numbers are generated and are either added or subtracted from each other every time u type the answer. i can get the numbers to display but i cant get the operator to display. how would i do that? here is my code:
php
<?php

$num1 = rand(0, 20);
$num2 = rand(0, 20);

$operators = array(
    "+",
    "-",
);

switch ($operators[array_rand($operators)]) {
    case "+":
        $result = $num1 + $num2;
        break;
    case "-":
        $result = $num1 - $num2;
        break;
}
    echo'

'. $num1 .'

'. $operators .'

'. $num2 .'

        '
?>

A: <?php

$num1 = rand(0, 20);
$num2 = rand(0, 20);

$operators = array(
    "+",
    "-",
);
$operator = $operators[array_rand($operators)];
switch ($operator) {
    case "+":
        $result = $num1 + $num2;
        break;
    case "-":
        $result = $num1 - $num2;
        break;
}
    echo'

'. $num1 .'

'. $operator .'

'. $num2 .'

        '
?>

A: try to somethinf like this...
<?php

$num1 = rand(0, 20);
$num2 = rand(0, 20);

$operators = array("+","-",
);
$operator =  $operators[array_rand($operators)];
switch ($operator) {
    case "+":
        $result = $num1 + $num2;
        break;
    case "-":
        $result = $num1 - $num2;
        break;
}
    echo'

'. $num1 .'

'. $operator.'

'. $num2 .'

        '
?>

A: <?php

$num1 = rand(0, 20);
$num2 = rand(0, 20);

$operators = array(
    "+",
    "-",
);

switch ($operator=$operators[array_rand($operators)]) {
    case "+":
        $result = $num1 + $num2;
        break;
    case "-":
        $result = $num1 - $num2;
        break;
}
    echo'

'. $num1 .'

'. $operator .'

'. $num2 .'

        '
?>


text:
Q: How to judge the extent to which experiment supports a theory? I am aware of the 'one sigma', 'two sigma' etc 'level of significance'. However this description of the significance of a result with sigmas seems to say 'If this other theory was not correct, then there would be only an $x\%$ chance of this experimental result'. For example, with the Higgs boson 'discovery', the result was significant to the 5 sigma level because there was only a one in 3.5 million chance of the Higgs boson-like 'hump' that was seen simply being part of the background noise.
Suppose you are trying to test how closely a value predicted by a theory matches experiment. You perform the experiment and get, say, 0.998$\pm$0.014 and the predicted value is 1. Is there anything that you can say about this particular data to judge how closely the experiment fits with the data (e.g. can you divide the error up and say that the experimental value is within a quarter of a standard error)? Or are you simply limited with this given data to saying that the experiment is consistent with the theoretical prediction within the error, and then to judge more closely how well the prediction matches with the real world you would need to conduct higher precision experiments or take more repeats to reduce the standard error in your experimental value?

A: As you've noticed, traditional physics analyses, including the discovery of the Higgs boson, use frequentist hypothesis testing. One calculates the probability of obtaining data at least as 'extreme' as that observed, were the null hypothesis (e.g., the standard model without a Higgs boson) true. This is known as a $p$-value. If the $p$-value is sufficiently small, we decide to reject the null hypothesis.
This says nothing directly about the plausibility of the alternative or null hypotheses, and, even if the null hypothesis is true, the $p$-value won't indicate that it's favoured by data. Even asymptomatically, it wouldn't converge, but make a random walk between zero and one.
There is, however, an alternative framework - Bayesian statistics - in which one may directly calculate the change in relative plausibility of models in light of data. This requires at least two competing explanations of data.
Suppose you measured a quantity, $D =0.998±0.014$. With Bayesian statistics,  you can find the change in relative plausibility of two competing models, in light of that measurement. See e.g. my article about the notorious diphoton anomaly for a pedagogical example. The plausibility of a new massive resonance relative to the standard model increased by about 10 in light of early run-2 LHC data.


text:
Q: Check if a link already exists on a page I'm trying to solve for two scenarios:

*

*Identify if the link clicked exists already on the page.

*Then if the link already exists, get the index() for the link clicked of the duplicate links.
My code is not working correctly since it's not identifying correctly if the link clicked is a duplicate and it's giving me an index of the sum of all links instead of the duplicate link.
$("a").click(function() {
   Rank = $(this).index('a');
   if($("a").attr("href") != $(this).attr("href")) {
        alert('\nLink Rank '+Rank+'\n\nYes, this is duplicate link');
       return false;
    }
    else {
        alert('\nLink Rank '+Rank+'\n\nNo, this is NOT a duplicate link');
        return false;
    }
});

Demo: http://jsfiddle.net/no4gkk0n/1/

A: You can look for elements with the same attribute with the attribute selector: [href="foo"], then check the length property. If it's more than 1, there is a duplicate link:
$("a").click(function (e) {
    e.preventDefault();
    Rank = $(this).index('a');
    if ($("a[href='" + $(this).attr("href") + "']").length > 1) {
        alert('\nLink Rank ' + Rank + '\n\nYes, this is duplicate link');
    } else {
        alert('\nLink Rank ' + Rank + '\n\nNo, this is NOT a duplicate link');
    }
});

Example fiddle


text:
Q: Delete records from a given table how i Delete all the artists which have not recorded any jazz titles
my artists table is :
artistid , artistname,city,regon

my titlesid Is:
titleid,artistid titles

and I tried this query
DELETE a.*
FROM artists a
     LEFT JOIN titles t ON a.artistid = t.artistid AND t.genre = 'jazz'
WHERE t.artistid IS NULL

but the result will delete all the artists except who have not recorded any jazz title !!!

A: Unless I'm misunderstanding your question, your query is doing exactly what you want. You're deleting artists who have never recorded a jazz title. If you are trying to delete only artists who have recorded a jazz title, then you would change the WHERE clause to be WHERE t.artistid IS NOT NULL, or preferably, change your LEFT JOIN to an INNER JOIN


text:
Q: Is it true that there is no need to learn C because C++ contains everything? I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features.  However, some others have told me that this is not necessarily true.  Can anyone shed some light on this?

A: Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function).  C++ does change the definition of some terms in C such as structs, although still in a superset way.
Examples of why it is not a strict superset:
This Wikipedia article has a couple good examples of such a differences:

One commonly encountered difference is
  that C allows implicit conversion from
  void* to other pointer types, but C++
  does not. So, the following is valid C
  code:
int *i = malloc(sizeof(int) * 5);

... but to make it work in both C and
  C++ one would need to use an explicit
  cast:
int *i = (int *) malloc(sizeof(int) * 5)

Another common portability issue is
  that C++ defines many new keywords,
  such as new and class, that may be
  used as identifiers (e.g. variable
  names) in a C program.

This wikipedia article has further differences as well:

C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:

 void fn(void)
 {
  goto flack;
  int i = 1;
 flack:
   ;
 }

What should you learn first?
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first.  You will eventually learn just about everything about C anyway because it is more or less contained in C++.

A: It might be true that you don't need to learn the syntax of C if you know the syntax of C++ but you cetainly do need to learn of how coding practices are different in C than in C++.
So your professor wasn't 100% right.
In C you don't have the classes to arrange your code into logical modules and you don't have C++ polymorphism. Yet you still need to achieve these goals somehow.
although the syntax of C is to some extent a subset of C++, programming in C is not a subset of programming in C++. it is completely different.

A: Yes and no.
As others have already answered, the language C++ is a superset of the language C, with some small exceptions, for example that sizeof('x') gives a different value.
But what I don't think has been very clearly stated is that when it comes to the use of these two languages, C++ is not a superset, but rather different. C++ contains new (it can be discussed if they are better) ways of doing the basic things, such as writing to the screen. The old C ways are still there, but you generally use the new ways. This means that a simple "hello world" program looks different in C and in C++. So it is not really true that the simple things are the same in C and C++, and then you just add more advanced stuff, such as support for object-oriented programming, in C++.
So if you have learnt C++, you will need to re-learn quite a lot before you can program in C. (Well, it is possible to teach C++ as an extension to C, still using printf and malloc instead of iostreams and new, and then adding classes and other C++ things, but that way of using C++ is generally frowned upon.)

A: No C++ isn't really a superset of C. You can check this article for a more extensive list of the differences if you're interested:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

A: Not entirely true.
The biggest "gotcha" is typing -- C++ is much more strongly typed than C is, and the preferred methods for solving this in C++ are simply not available in C. Namely, you can silently cast between types in C (particularly pointer types), but not in C++. And C++ highly recommends using the static_cast/reinterpret_cast/const_cast methods for resolving these issues.
More importantly, if you learn C++ syntax and mannerisms, you'll probably find it difficult to deal with C (some may say this is good; and I prefer C++ myself, but sometimes it just isn't an option, or you have to deal with legacy code that's in C and not C++). Again, the most likely issues you'll encounter are dealing with pointers (particularly char*'s and general array usage; in C++ using std::string and std::vector or other collections is simply better).
It's certainly possible to learn C++, and then learn the differences between C and C++ and be capable of programming in both. But the differences are far more than just skin deep.

A: It is true that for most purposes, C++ contains everything that C does. Language lawyers will be quick to point out that there are some very special edge cases that are valid C but not valid C++.
One such example might be the C declaration
int virtual;

which declares an integer named "virtual". Since "virtual" is a keyword in C++, this is not valid C++.

A: There is a large common core of C (especially C89) and C++, but there are most certainly areas of difference between C and C++.  Obviously, C++ has all the object-oriented features, plus the generic programming, plus exceptions, plus namespaces that C does not.  However, there are also features of C that are not in C++, such as support for the (close to archaic) non-prototype notation for declaring and defining functions.  In particular, the meaning of the following function declaration is different in C and C++:
extern void function();

In C++, that is a function that returns no value and takes no parameters (and, therefore, is called solely for its side-effects, whatever they are).  In C, that is a function which returns no value but for which there is no information about the argument list.  C still does not require a declaration in scope before a function is called (in general; you must have a declaration in scope if the function takes a variable list of arguments, so it is critical to #include <stdio.h> before using printf(), etc).
There are also differences:
sizeof('c')

In C++, the answer is 1; in C, the answer is normally 4 (32-bit systems with 8-bit characters) or even 8 (64-bit systems with 64-bit int).
In general, you can write code that will compile under both C and C++ compilers without much difficulty - the majority of my code does that all the time.  The exceptions are either a result of carelessness on my part, or because I've consciously exploited the good features of C99 that are not in C++ 98, such as designated initializers, or long long.

A: Stroustrup himself advices against learning C first. But then again, he (and many others of his generation) managed to become a C++ guru starting from C.

A: I personally would disagree with your professor.
Generally speaking, C++ is based on C and in that "sense" contains it and extends it.
However, since traditionally people learned C and only then the extensions of C++, your professor's statement is incorrect since to use C++ correctly you would need to master the C origins. It is possible that when teaching you something, your professor or textbook will not specifically mention what came from which language.
In addition, it is important to understand that despite the similarities, not every C program runs in the same way under C++. For example, C structs are interpreted differently (as classes with everything public) by the C++ compiler.
When I teach, I teach the C core first, and then go to C++.

A: While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.
There was a term of art called using C++ as a better C. This meant using some C++ language features and tools to make C programming easier (e.g., declaring the index variable of a for loop within the for statement). But now, modern C++ development seems very different from C other than a great deal of the syntax and in those cases the C legacy often seems to be a burden rather than a benefit.

A: If any of the students in the class intend to become embedded software engineers, then they may have no choice but to program in C (see this question, and this one, among others).
Of course, having learnt C++, it may be less of a transition for them than starting from scratch - but it still makes your professor's statement untrue!


text:
Q: adding rows for missing intervals between existing intervals in R Problem:
I have a data set that contains interval data with start and end dates and my goal is it to add rows to that data set that reflect the potential gaps between these intervals (per group). The complexity is that the already existing intervals may overlap and there might be an arbitrary number of gaps.
Example: We have start and end dates showing from when to when a person has occupied an apartment. There may have been multiple people at one apartment at the same time and there needs to be rows added for the time the apartment has been "empty".
Example data:
example_dates <- structure(list(apartment = c("A", "A", "A", "A", "B", "B",
                                                "B", "C", "C", "C"),
                                start_date = structure(c(1640995200, 1642291200,
                                                         1649980800, 1655769600, 1644451200, 1646092800, 1659312000, 1646438400,
                                                         1649376000, 1664582400),
                                                       class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                                end_date = structure(c(1642204800, 1648166400, 1655683200,
                                                       1668643200, 1655251200, 1653868800, 1667260800, 1654819200,
                                                       1661385600, 1668470400), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                                status = c("person in apartment", "person in apartment",
                                           "person in apartment", "person in apartment", "person in apartment",
                                           "person in apartment", "person in apartment", "person in apartment",
                                           "person in apartment", "person in apartment")),
                           class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))

Desired output:
desired_outcome <- structure(list(apartment = c("A", "A", "A", "A", "A", "B",
                                                  "B", "B", "B", "C", "C", "C", "C"),
                                  start_date = structure(c(1640995200, 1642291200, 1648252800,
                                                           1649980800, 1655769600, 1644451200, 1646092800,
                                                           1655337600, 1659312000, 1646438400, 1649376000, 1661472000, 1664582400),
                                                         class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                                  end_date = structure(c(1642204800, 1648166400, 1649894400, 1655683200, 1668643200, 1655251200, 1653868800,
                                                         1659225600, 1667260800, 1654819200, 1661385600, 1664496000, 1668470400),
                                                       class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                                  status = c("person in apartment", "person in apartment", "apartment empty",
                                             "person in apartment", "person in apartment", "person in apartment",
                                             "person in apartment", "apartment empty", "person in apartment", "person in apartment",
                                             "person in apartment", "apartment empty", "person in apartment"
                                                  )),
                             class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -13L))

A: I think this is a great use case for the ivs package that I created for working with intervals in the tidyverse. The main details here are:

*

*Convert to dates rather than date-times

*Add 1 to end_date to make ranges that match [, ), which is what ivs wants (and makes more sense here)

*For each apartment, compute the interval complement with iv_complement(). These are the empty dates (it keeps in mind any overlaps)

*Bind the complement with the original data and sort

The end dates in the final result will be +1 vs what is in your desired_outcome but I find these interval problems are easier to think about if you use right open intervals, [, ).
library(dplyr, warn.conflicts = FALSE)
library(ivs)

example_dates <- structure(
  list(
    apartment = c("A", "A", "A", "A", "B", "B", "B", "C", "C", "C"),
    start_date = structure(
      c(
        1640995200, 1642291200, 1649980800, 1655769600, 1644451200,
        1646092800, 1659312000, 1646438400, 1649376000, 1664582400
      ),
      class = c("POSIXct", "POSIXt"),
      tzone = "UTC"
    ),
    end_date = structure(
      c(
        1642204800, 1648166400, 1655683200, 1668643200, 1655251200,
        1653868800, 1667260800, 1654819200, 1661385600, 1668470400
      ),
      class = c("POSIXct", "POSIXt"),
      tzone = "UTC"
    ),
    status = c(
      "person in apartment", "person in apartment", "person in apartment",
      "person in apartment", "person in apartment", "person in apartment",
      "person in apartment", "person in apartment", "person in apartment",
      "person in apartment"
    )
  ),
  class = c("tbl_df", "tbl", "data.frame"),
  row.names = c(NA, -10L)
)

# Convert dates to dates rather than date-times
example_dates <- example_dates %>%
  mutate(
    start_date = as.Date(start_date),
    end_date = as.Date(end_date)
  ) %>%
  mutate(
    # Make `end_date` exclusive
    end_date = end_date + 1
  )

example_dates
#> # A tibble: 10 × 4
#>    apartment start_date end_date   status
#>    <chr>     <date>     <date>     <chr>
#>  1 A         2022-01-01 2022-01-16 person in apartment
#>  2 A         2022-01-16 2022-03-26 person in apartment
#>  3 A         2022-04-15 2022-06-21 person in apartment
#>  4 A         2022-06-21 2022-11-18 person in apartment
#>  5 B         2022-02-10 2022-06-16 person in apartment
#>  6 B         2022-03-01 2022-05-31 person in apartment
#>  7 B         2022-08-01 2022-11-02 person in apartment
#>  8 C         2022-03-05 2022-06-11 person in apartment
#>  9 C         2022-04-08 2022-08-26 person in apartment
#> 10 C         2022-10-01 2022-11-16 person in apartment

# Combine start/end into an interval vector
example_dates <- example_dates %>%
  mutate(range = iv(start_date, end_date), .keep = "unused")

example_dates
#> # A tibble: 10 × 3
#>    apartment status                                 range
#>    <chr>     <chr>                             <iv<date>>
#>  1 A         person in apartment [2022-01-01, 2022-01-16)
#>  2 A         person in apartment [2022-01-16, 2022-03-26)
#>  3 A         person in apartment [2022-04-15, 2022-06-21)
#>  4 A         person in apartment [2022-06-21, 2022-11-18)
#>  5 B         person in apartment [2022-02-10, 2022-06-16)
#>  6 B         person in apartment [2022-03-01, 2022-05-31)
#>  7 B         person in apartment [2022-08-01, 2022-11-02)
#>  8 C         person in apartment [2022-03-05, 2022-06-11)
#>  9 C         person in apartment [2022-04-08, 2022-08-26)
#> 10 C         person in apartment [2022-10-01, 2022-11-16)

# Compute the complement per apartment
empty_dates <- example_dates %>%
  group_by(apartment) %>%
  summarise(range = iv_complement(range)) %>%
  mutate(status = "apartment empty")

empty_dates
#> # A tibble: 3 × 3
#>   apartment                    range status
#>   <chr>                   <iv<date>> <chr>
#> 1 A         [2022-03-26, 2022-04-15) apartment empty
#> 2 B         [2022-06-16, 2022-08-01) apartment empty
#> 3 C         [2022-08-26, 2022-10-01) apartment empty

# Bind and sort
bind_rows(example_dates, empty_dates) %>%
  arrange(apartment, range) %>%
  mutate(start_date = iv_start(range), end_date = iv_end(range), .keep = "unused")
#> # A tibble: 13 × 4
#>    apartment status              start_date end_date
#>    <chr>     <chr>               <date>     <date>
#>  1 A         person in apartment 2022-01-01 2022-01-16
#>  2 A         person in apartment 2022-01-16 2022-03-26
#>  3 A         apartment empty     2022-03-26 2022-04-15
#>  4 A         person in apartment 2022-04-15 2022-06-21
#>  5 A         person in apartment 2022-06-21 2022-11-18
#>  6 B         person in apartment 2022-02-10 2022-06-16
#>  7 B         person in apartment 2022-03-01 2022-05-31
#>  8 B         apartment empty     2022-06-16 2022-08-01
#>  9 B         person in apartment 2022-08-01 2022-11-02
#> 10 C         person in apartment 2022-03-05 2022-06-11
#> 11 C         person in apartment 2022-04-08 2022-08-26
#> 12 C         apartment empty     2022-08-26 2022-10-01
#> 13 C         person in apartment 2022-10-01 2022-11-16

A: what about this?
library(lubridate)
library(data.table)

setDT(example_dates)
setDT(desired_outcome)

example_dates[, start_date := lubridate::ymd(start_date)]
example_dates[, end_date := lubridate::ymd(end_date)]
example_dates[, start_date_int := as.numeric(start_date)]
example_dates[, end_date_int := as.numeric(end_date)]

agg <- example_dates[, g := c(0L, cumsum(shift(start_date_int, -1L) > cummax(end_date_int))[-.N]), apartment][,.(min(start_date_int), max(end_date_int)), .(g, apartment)]
colnames(agg) <- c("g", "apartment", "start_date", "end_date")
agg[, start_date := as_date(start_date, origin="1970-01-01")]
agg[, end_date := as_date(end_date, origin="1970-01-01")]

agg[, gap := start_date - shift(end_date) - 1, by = .(apartment)]
agg[, empty_start := shift(end_date) + lubridate::days(1)]
agg[, empty_end := empty_start + gap - lubridate::days(1)]

empty.dt <- agg[gap > 1, .(apartment, empty_start, empty_end)]
empty.dt$status <- "apartment empty"
colnames(empty.dt) <- c("apartment", "start_date", "end_date", "status")
full.dt <- example_dates[, .(apartment, start_date, end_date, status)]
res <- rbindlist(list(full.dt, empty.dt))


text:
Q: MVC4 minification and bundle on publish? I am creating an install for an MVC4 site that will be installed at customer sites.  I do not want the javascript to exist on disk "not minified". Is there a way to use the existing bundling framework to bundle and minify on publish?  Right now the files are served minified but are stored in their original readable format.  Prior to MVC4 I was using a build script to do this, I hope to not have to go back to that.  Is this possible?

A: I believe that this tool will do what you want; for what you're trying to do you'll probably want to use the MSBUILD-related functionality:
http://yuicompressor.codeplex.com/


text:
Q: How to prevent R from alphabetically ranking data in ggplot and specify the order in which data is plotted (Data + Code + Graphs provided)? I'm trying to fix an issue with my GGBalloonPlot graph with regards to how R processes the axis labels.
By default R plots the data using the labels ranked in reverse alphabetical order but to reveal the pattern of the data, the data need to be plotted in a specific order. The only way I've been able to do trick the software is by manually adding a prefix to each label in my .csv table so that R would rank them properly in my output. This is time consuming since I need to manually order the data first before adding the prefix and then plotting.
I would like to input a character vector (or something like that) which would essentially specify the order in which I want to have the data plotted which would reveal the pattern without the need for a prefix in the label name.
I have made some attempts with "scale_y_discrete" without success. I would also like to do the same thing for the X axis since I've had to use the same "trick" to display the columns in the proper non-alphabetical order which offsets the position of the labels. Any idea on how to get GGplot to display my values as seen in the graph without having to "trick" the software since this is quite time consuming ?
Data + Code
#Assign data to "Stack_Overflow_DummyData"

Stack_Overflow_DummyData <- structure(list(Species = structure(c(8L, 3L, 1L, 5L, 6L, 2L,
                                     7L, 4L, 8L, 3L, 1L, 5L, 6L, 2L, 7L, 4L, 8L, 3L, 1L, 5L, 6L, 2L,
                                     7L, 4L, 8L, 3L, 1L, 5L, 6L, 2L, 7L, 4L), .Label = c("Ani", "Cal",
                                                                                "Can", "Cau", "Fis", "Ort", "Sem", "Zan"), class = "factor"),
               Species_prefix = structure(c(8L, 7L, 6L, 5L, 4L, 3L, 2L,
                                            1L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 8L, 7L, 6L, 5L, 4L, 3L,
                                            2L, 1L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L), .Label = c("ac.Cau",
                                                                                "ad.Sem", "af.Cal", "ag.Ort", "as.Fis", "at.Ani", "be.Can",
                                                                                "bf.Zan"), class = "factor"), Dist = structure(c(2L, 3L,
                                                                                5L, 2L, 1L, 1L, 4L, 5L, 2L, 3L, 5L, 2L, 1L, 1L, 4L, 5L, 2L,
                                                                                3L, 5L, 2L, 1L, 1L, 4L, 5L, 2L, 3L, 5L, 2L, 1L, 1L, 4L, 5L
                                                                                ), .Label = c("End", "Ind", "Pan", "Per", "Wid"), class = "factor"),
               Region = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
                                    4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Cen", "Col",
                                                                                "Far", "Nor"), class = "factor"), Region_prefix = structure(c(1L,
                                                                                1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                                                3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
                                                                                4L), .Label = c("a.Far", "b.Nor", "c.Cen", "d.Col"), class = "factor"),
               Frequency = c(75, 50, 25, 50, 0, 0, 0, 0, 11.1, 22.2, 55.6,
                             55.6, 11.1, 0, 5.6, 0, 0, 2.7, 36.9, 27.9, 65.8, 54.1, 37.8,
                             28.8, 0, 0, 0, 3.1, 34.4, 21.9, 78.1, 81.3)), class = "data.frame", row.names = c(NA,
                                                                                -32L))

# Plot Data With Prefix Trick

library(ggplot2)
library(ggpubr)

# make color base on Dist, size and alpha dependent on Frequency
ggballoonplot(Stack_Overflow_DummyData, x = "Region_prefix", y = "Species_prefix",
              size = "Frequency", size.range = c(1, 9), fill = "Dist") +
  theme_set(theme_gray() +
  theme(legend.key=element_blank())) +
  # Sets Grey Theme and removes grey background from legend panel
  theme(axis.title = element_blank()) +
  # Removes X axis title (Region)
  geom_text(aes(label=Frequency), alpha=1.0, size=3, nudge_x = 0.4)
# Add Frequency Values Next to the circles

# Plot Data Without Prefix Trick

library(ggplot2)
library(ggpubr)

# make color base on Dist, size and alpha dependent on Frequency
ggballoonplot(Stack_Overflow_DummyData, x = "Region", y = "Species",
              size = "Frequency", size.range = c(1, 9), fill = "Dist") +
  theme_set(theme_gray() +
  theme(legend.key=element_blank())) +
  # Sets Grey Theme and removes grey background from legend panel
  theme(axis.title = element_blank()) +
  # Removes X axis title (Region)
  geom_text(aes(label=Frequency), alpha=1.0, size=3, nudge_x = 0.4)
# Add Frequency Values Next to the circles

Here below are the graphs
Good Graph.
Using the label prefix trick with the visible pattern in the data:

Wrong Graph (R default).
Without the prefix trick when GGplot automatically orders the data/labels and the graph makes no sense:

To sum up, I would like the Good graph output without having to have to previously add a prefix in my labels.
Many Thanks in advance for your help.

A: For the axis labels I would define a previous function to override the breaks:
shlab <- function(lbl_brk){
  sub("^[a-z]+\\.","",lbl_brk) # removes the starts of strings as a. or ab.
}

Then, to change the labels you just have to use scale_x,y_discrete with labels = shlab (if you look at the help of scale_x_discrete you will see that one of the options for labels is A function that takes the breaks as input and returns labels as output).
For the colours would be enough to change them (values) in scale_fill_manual and for the sizes, using guides so:
library(ggplot2)
library(ggpubr)
shlab <- function(lbl_brk){
  sub("^[a-z]+\\.","",lbl_brk)
}
ggballoonplot(Stack_Overflow_DummyData, x = "Region_prefix", y = "Species_prefix", size = "Frequency", size.range = c(1, 9), fill = "Dist") +
  scale_x_discrete(labels = shlab) +
  scale_y_discrete(labels = shlab) +
  scale_fill_manual(values = c("green", "blue", "red", "black", "white")) +
  guides(fill = guide_legend(override.aes = list(size=8))) +
  theme_set(theme_gray() + theme(legend.key=element_blank())) +     # Sets Grey Theme and removes grey background from legend panel
  theme(axis.title = element_blank()) +                             # Removes X axis title (Region)
  geom_text(aes(label=Frequency), alpha=1.0, size=3, nudge_x = 0.4) # Add Frequency Values Next to the circles

UPDATE:
With the new dataset and vector labels:
library(ggplot2)
library(ggpubr)

# make color base on Dist, size and alpha dependent on Frequency
ggballoonplot(Stack_Overflow_DummyData, x = "Region", y = "Species",
              size = "Frequency", size.range = c(1, 9), fill = "Dist") +
  scale_y_discrete(limits = c("Cau", "Sem", "Cal", "Ort", "Fis", "Ani", "Can", "Zan")) +
  scale_x_discrete(limits = c("Far", "Nor", "Cen", "Col")) +
  theme_set(theme_gray() +
              theme(legend.key=element_blank())) +
  # Sets Grey Theme and removes grey background from legend panel
  theme(axis.title = element_blank()) +
  # Removes X axis title (Region)
  geom_text(aes(label=Frequency), alpha=1.0, size=3, nudge_x = 0.4)


text:
Q: Java Reflection - Get all instance variable names of a class I'm writing an android app that requires binding a JSON object into a domain entity with the keys from the JSON as instance variables. Since there are several domain entities, each with different instance variables that the JSON needs to bind to in the app, i'd like to write a method such as ths following:

*

*Loop through all the instance variables from the domain

*if a key exists in the JSON with the name of the instance variable, take the value for this key from the JSON and set the Domain's instance variable with this key name equal to this value.

The reason i'm interested in the doing the binding from the class to the JSON is because if the JSON changes for some reason, I don't want it to break the app when the instance variable doesn't exist in the app's domain for a specific JSON key.
Thanks in advance for any help!

A: Most likely you want to use a json library that does this for you. Jackson is a good one that is also used by Spring MVC.
To answer your question, you can use getDeclaredFields() on a class, and use java.lang.reflect.Modifier.isStatic() to check if the field is static.
private static class Foo {
    private static long car;
    private int bar;
    private String baz;
}

public static void main(String[] args) {
    for (Field field : Foo.class.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            System.out.println("Found non-static field: " + field.getName());
        }
    }
}

This will print out:
Found non-static field: bar
Found non-static field: baz

A: oksayt's answer is correct, but I'd take it with a grain of salt. Not every field holds a property that should be exposed publically. The mechanism to use is the Java Beans Introspector. You can use my answers to these previous Questions as reference:

*

*How to get the fields in an Object via reflection?

*Accessing Methods and functions of a object whose class type is dynamically known
Additional Reference:

*

*Java Beans Specification

*Java Tutorial: Introspection


text:
Q: How to trigger route resolver manually I'm resolving a user before accessing the account fragment of my user page :
app-routing.component.ts
{
  path: 'users/:id',
  component: UserComponent,
  resolve: {user: UsersService},
  children: [
    {path: '', pathMatch: 'full', redirectTo: 'account'},
    {path: 'account', component: UserAccountComponent},
    {path: 'sites', component: UserSitesComponent}
  ]
}

users.service.ts
resolve(route: ActivatedRouteSnapshot, r: RouterStateSnapshot) {
  return this.getUser(route.params['id']);
}

user-account.component.ts
ngOnInit() {
  this.route.parent.data.subscribe(data => {
    this.user = data['user'];
    // Initialize the form and its validators
    this.initForm();
  });
}

In the user account component I can save or reset the form. In both cases I'd like to update the user of the component and to reset the form and the validators. Ideally It'd like the subscription to be triggered again.
Any idea how to trigger the resolver manually ?
(I used to re-navigate to the same route modulo a random number as the last fragment, but since I exploded my user page into parent/children routes, the resolver, within the parent, is not called anymore when the last fragment changes)

A: If you need to rerun your guards and resolvers for specific conditions (specific queryparams, ...) there also the more flexible option to pass a function to runGuardsAndResolvers in the routing module. Example:
const routes: Routes = [
  {
    path: 'home/:id',
    component: HomeComponent,
    ...
    runGuardsAndResolvers: (curr: ActivatedRouteSnapshot, future: ActivatedRouteSnapshot) => {
      // inspect the current router state and then return true|false
      return false;
    }
  }
];

Example taken from the following article:
https://juristr.com/blog/2019/01/Explore-Angular-Routers-runGuardsAndResolvers/

A: I agree with "Woot", but if you want to trigger the resolver again, go to your routing module and add
runGuardsAndResolvers: "always"

Now you can navigate on the same page again an the resolver will run again. But be aware only the resolver will run again, no other lifecyle, like "ngOnInit".
Example according to you code
app-routing.component.ts
{
  path: 'users/:id',
  component: UserComponent,
  resolve: {user: UsersService},
  children: [
    {path: '', pathMatch: 'full', redirectTo: 'account'},
    {path: 'account', component: UserAccountComponent, runGuardsAndResolvers: "always"},
    {path: 'sites', component: UserSitesComponent}
  ]
}

Now if you route to the same page again the subscription on your user-account.component.ts will be triggered again

A: Typically you wouldn't want to trigger a route resolver manually.
Since your resolver looks to be part of your service and all it does is call this.getUser(id) you could easily call it after a change is made.
What I would do in this scenario is have my service injected into my class, and then after the action that updates the user call the this.getUser(id).
Possible implementation
export class UserAccountComponent implements OnInit {
  userId: number;
  constructor(private route: ActivatedRoute, private userService: UserService) {}

  ngOnInit() {
    this.route.params.pipe(
      do((params) => {
        this.userId = +params['id'];
      }),
      take(1)
    );
  }

  doSomeChange() {
    // this will execute a change and update the user.
    this.userService.get(this.userId);
  }
}

Note: I am using code that is dependent on rxjs 5.5
Additionally your service must be included in your providers for this to work