text:
Q: Adding textfield below another textfield programmatically in iOS In my app I want to programmatically add textfield below another if required on click of a button. I already had provided two textFields. if a user want to add another textfield he can do so by clicking a button. I have already written code to obtain the textfield but the problem is that it overlaps the already designed textFields. How can I do it?
Is there any way through which I can get the x and Y co-ordinates of already designed textfield so that I can place new textField relative to those co-ordinates.

A: This code add textField to view dynamically when every click action on button

ExampleViewController.h

#import <UIKit/UIKit.h>

@interface ExampleViewController :UIViewController<UITextFieldDelegate>

@property int positionY;
@property int fieldCount;

@property (strong,nonatomic)  UIScrollView *scroll;

@end

ExampleViewController.m

#import "ExampleViewController.h"

@interface ExampleViewController ()

@end

@implementation ExampleViewController

@synthesize positionY;
@synthesize fieldCount;
@synthesize scroll;

- (void)viewDidLoad {
  [super viewDidLoad];

scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.backgroundColor = [UIColor whiteColor];

[self.view addSubview:scroll];

UIButton *clickToCreateTextField = [[UIButton alloc] initWithFrame:CGRectMake(40, 80, self.view.frame.size.width-80, 75)];
[clickToCreateTextField setTitle:@"Create Text Field" forState:UIControlStateNormal];
[clickToCreateTextField addTarget:self action:@selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];
[clickToCreateTextField setBackgroundColor:[UIColor blackColor]];
[scroll addSubview:clickToCreateTextField];

positionY = clickToCreateTextField.center.y;
fieldCount = 0;

// Do any additional setup after loading the view.
}

-(void) clickedButton{
  //add text field programmitacally
  UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, positionY, self.view.frame.size.width-80, 75)];
  textField.delegate = self;
//give a tag to determine the which textField tapped
textField.tag = fieldCount;
textField.placeholder = [NSString stringWithFormat:@"Your dynamically created textField: %d", fieldCount ];
[scroll addSubview:textField];

//check if the textFields bigger than view size set scroll size and offset
if (positionY>= self.view.frame.size.height) {
    scroll.contentOffset = CGPointMake(0, positionY);
    scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height+positionY);
}

fieldCount++;
//increase the position with a blank place
positionY = positionY+textField.frame.size.height+20;
}
#pragma mark TextField Delegate Methods
  -(void) textFieldDidBeginEditing:(UITextField *)textField{
//Do what ever you want
}

-(void) textFieldDidEndEditing:(UITextField *)textField{
  [textField resignFirstResponder];
//do anything
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
  [textField resignFirstResponder];
  return YES;
}

-(void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

You can do any additional changes on this code.
I think this example explain your answer.
Hope it helps.

A: Use a counter and calculate y like this counter*texfield.frame.size.height.


text:
Q: Set the aggregation text of fragments from controller I have a xml-fragment. I set items as "{path: '/idFamiglia' }"
<core:FragmentDefinition
  xmlns="sap.m"
  xmlns:core="sap.ui.core">
  <SelectDialog
    id="idSelectDialog"
    noDataText="Nessun dato"
    title="Suggerimento"
    search="handleLocalSearch"
    liveChange="handleLocalSearch"
    confirm="handleClose"
    close="handleClose"
    items="{
      path: '/idFamiglia'
    }">
    <StandardListItem
      title="{title}"
      description="{description}"
      icon=""
      iconDensityAware="false"
      iconInset="false"
      type="Active" />
  </SelectDialog>
</core:FragmentDefinition>

From the controller I want set this string. I try in this methods:
handleValueLocalHelp : function(oEvent) {
        this.inputId = oEvent.oSource.sId;
        if (!this._oDialog) {
            this._oDialog = sap.ui.xmlfragment("ui5bp.view.fragment.HintLocalDialog",this);
        }
        //1
        sap.ui.getCore().byId("idSelectDialog").setAggregation("items", "{path: '/idFamiglia'}");
        //2
        this._oDialog.bindElement("/idFamiglia");
        //3
        sap.ui.getCore().byId("idSelectDialog").bindElement("/idFamiglia");

        this._oDialog.setModel(this.getView().getModel("hint"));
        // toggle compact style
        jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._oDialog);
        this._oDialog.open();
    },

I have some errors..

*

*Uncaught Error: Aggregation 'items' of Element sap.m.List#idSelectDialog-list used with wrong cardinality (declared as 0..n) if I try the forst mode

*If I try the second mode it not change the string

*the same behavior

How can I modify the aggregation string (items for example) from controller?

A: Since the control you are using (SelectDialog), the "item" aggregation can only be used with sap.m.ListItemBase[] whereas I can see you are binding with '/idFamiglia'. This is not a property binding, it is can aggregation binding.
var oSelectDialog = new sap.m.SelectDialog({
                multiSelect : true,
                title : "Title",
                items: {
                    path: "/",
                    template: new sap.m.StandardListItem({
                        title: "{text}",
                        description: "{key}"
                        //selected: "{JSON>selected}"
                    })
                },
                rememberSelections : true,
            });

A: I try a solution to set a default fragment by XML-view and personalize it from controller:
handleValueLocalHelp : function(oEvent) {
        this.inputId = oEvent.oSource.sId;
        if (!this._oDialog) {
            this._oDialog = sap.ui.xmlfragment("ui5bp.view.fragment.HintLocalDialog",this);
            this._oDialog._dialog.mAggregations.content[1].mBindingInfos.items.path="/idFamiglia";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: error exe-bad access after executing this line NSURL *url = [NSURL URLWithString:
                  [NSString stringWithFormat:@"%@%@%@%@%@",[ConfigDB valueForKey:categoryURL], @"?ownerId=", 20,@"&userId=",64]];
can any one tell me wat wrong with this

A: For numbers you are supposed to use %d, not %@.
@"%@%@%d%@%d"


text:
Q: How to use the ba command (Break on Access) in WinDbg? I have a this very minimal C program:
#include <windows.h>

void funAdd() {
    int a = 2; // I want to break here
}

int CALLBACK
WinMain(HINSTANCE Instance,
    HINSTANCE PrevInstance,
    LPSTR CommandLine,
    int ShowCode)
{
    funAdd();
}

I would like to break inside the funAdd() function using break on access inside WinDbg. The visual studio dissassembly tells me that the int a = 2 instruction is located at memory address 002416BC:

According to the documentation here : https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/ba--break-on-access-
If I write the command ba r4 02416be I would expect the debugger to break inside my funAdd() function, however when I enter the command I get the following error: Data breakpoint must be aligned.
Am I understanding this correctly? And if so, how do I properly align this address to 4 bytes in order to match the r4 command option?

A: 0x2416be is instruction pointer or virtual address of the instruction
to set access breakpoint on this address you shouldn't use r or w  you should use e
ba e 2416be  this doesn't require either alignment or size
if you want to set a data breakpoint on your variable a
you have to find the virtual address of a
compilers normally align variable addresses so you normally don't have to worry about alignment
use dv  /v  a   ( you need private pdb for local variable display
and since windbg renamed the local var as a instead of ebp-xx you should be having your private pdb )
windbg will spit a result like
local var a @ xxxxxx
here xxxxx is the address of variable a  ( 2 would be stored
in ths address  )
use ba r4  or r2 or r1 as required on this address
be aware this address may be in stack   and this breakpoint may fire many times  before it actually hits your  condition
data read breakpoints are useful for global variables
and are not  so good for locals and heap addresses that are dynamic in nature
you can specify arbitrary function address to dv to look at the functions locals (need private pdb )
0:000> dv /v /i /t /f funadd!funAdd
prv local  <virtual frame 2ffa84>-0x0004       int myvar

executing upto the function start
0:000> g funadd!funAdd
eax=767fed5a ebx=7ffd4000 ecx=00000000 edx=01351000 esi=00000000 edi=00000000
eip=01351010 esp=002ffeb8 ebp=002ffebc iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
funadd!funAdd:
01351010 55              push    ebp

using local display
0:000> dv /V /i /t
prv local  002ffeb0          <virtual frame 2ffeb4>-0x0004       int myvar = 0n0

using display type command also will give the virtual address of the local
0:000> dt -n myvar
Local var @ 0x2ffeb0 Type int
0n0

you can set a read breakpoint on this address
0:000> ba r4 0x2ffeb0

execute and wait for you bp to hit
0:000> g
Breakpoint 0 hit
eax=767fed5a ebx=7ffd4000 ecx=00000000 edx=01351000 esi=00000000 edi=00000000
eip=01351014 esp=002ffeb0 ebp=002ffeb4 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
funadd!funAdd+0x4:
01351014 c745fc02000000  mov     dword ptr [ebp-4],2 <<<<<<<<<  ss:0023:002ffeb0=00000000

the value is not written yet to the local myvar
0:000> bl
     0 e Disable Clear  002ffeb0 r 4 0001 (0001)  0:****

0:000> ? myvar
Evaluate expression: 3145392 = 002ffeb0

0:000> ? poi(myvar)
Evaluate expression: 0 = 00000000


text:
Q: Remove all instances of a character from string I want to remove all instances of a character from a string except where that character is followed by any form or whitespace. I haven't written unit tests yet but it seems like the code below achieves what I want (possibly forgetting an edge case or two which is ok for now).  It feels pretty clunky though. Can anyone suggest an improvement?
public string Strip(string text, char c)
{
    if (!string.IsNullOrEmpty(text))
    {
        bool characterIsInString = true;
        int currentIndex = 0;

        while (characterIsInString)
        {
            currentIndex = text.IndexOf(c, currentIndex + 1);

            if (currentIndex != -1)
            {
                var charAfter = text.Substring(currentIndex + 1, 1);

                if (charAfter != " ")
                {
                    text = text.Remove(currentIndex, 1);
                }
            }
            else
            {
                characterIsInString = false;
            }
        }
    }

    return text;
}

A: You can use Regular Expression( here i have assumed that character is x):
string result = Regex.Replace( input , "x(?=\\S)" , "");

Live Demo. Please check that it uses very few steps finding it.

A: I suggest, you use the following code:
public string Strip(string text, char c)
{
    Regex regex = new Regex(c.ToString() + @"[^\s]");
    return regex.Replace(text, "");
}

This will remove the char in text if it's not followed by a White Space.
This is a very simple and fast regex.

A: if you want replace character
you can replace char with Replace method
Follow code:
Console.ReadLine().Replace("e","h");


text:
Q: Remove duplicate rows from a big table I've got data from third party and imported to SQL server. The table has 255,072,636 records and 61,714,772 are unique among these records. The table has neither specific order nor any index. The table has 4 columns: Field1(float), Field2(varchar(255), Field3(varchar(255), Field4(varchar(255). I want to delete the duplicate record based upon Field1 for which I've run the following query:
WITH CTE(Field1, Field2, Field3, Field4, DuplicateCount)
AS (SELECT *,
           ROW_NUMBER() OVER(PARTITION BY Field1 ORDER BY Field1) AS DuplicateCount
    FROM MyTable)
DELETE FROM CTE
WHERE DuplicateCount > 1;

but it took 13 hours and then I cancelled it and the above mentioned figures are after that. Is there any better way to remove duplicates?

A: Instead of delete you can insert unique rows into a temp table then you can rename that table or copy your desired rows to the original table after truncating that.
Insert unique rows into a table.
WITH CTE(Field1, Field2, Field3, Field4, DuplicateCount)
AS (SELECT *,
           ROW_NUMBER() OVER(PARTITION BY Field1 ORDER BY Field1) AS DuplicateCount
    FROM MyTable)
select * into TempTable FROM CTE
WHERE DuplicateCount = 1;

Then either you can rename that table like below:
drop table MyTable;
sp_rename 'temptable','MyTable';

Or copy unique rows back to the original table:
Truncate table MyTable;
insert into MyTable select *from TempTable ;
drop table temptable;

A: I would do this:

*

*make an index on filed1 (this will takes hours)
create ix_table on MyTable(files1)

*then either delete dups or make a new table for unique values, probably a little bit faster if you just insert into a new table
SELECT Field1, Field2, Field3, Field4
from
( select * ,
           ROW_NUMBER() OVER(PARTITION BY Field1 ORDER BY Field1) AS dups
  FROM MyTable
) tt
where dups = 1

but if you delete from original table , however it would be slower, you already have an index on field1 on that table , if you would need to use that index later on for any query purposes. so in longterm it might be more efficient to keep original table

A: Just recreate the table:
select distinct *
into new_t
from t;

I would suggest adding an index on (field1, field2, field3, field4) before doing this.
Or for one column uniqueness:
select t.*
from (select t.*,
             row_number() over (partition by field1 order by (select null)) as seqnum
      from t
     ) t
where seqnum = 1;

For this, you want an index on (field1).
If you really need to re-use the name of the original table, either truncate it and re-insert from new_t or rename the table.

A: Thanks to "Kazi Mohammad Ali Nur" and "eshirvana". I've combine there solutions. At first I created index on Field1.
CREATE CLUSTERED INDEX Index_Name
    ON MyTable(Field1);

and then I executed following query to insert unique records into a new table and deleted original table.
WITH CTE(Field1, Field2, Field3, Field4, DuplicateCount)
AS (SELECT *,
           ROW_NUMBER() OVER(PARTITION BY Field1 ORDER BY Field1) AS DuplicateCount
    FROM MyTable)
select * into TempTable FROM CTE
WHERE DuplicateCount = 1;

and it worked.
Thanks to all.


text:
Q: program does not delete file when launched from shortcut i have a small problem which is having big consequences.
whenever i launch my application from a shortcut it says that a file already exists in that location. the code i'm using is this:
Dim myfile As String = "HyperCredit.exe"

If System.IO.File.Exists(myfile) = True Then
    Dim fi As New FileInfo(myfile)
    fi.Delete()
End If

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", "C:\Program Files\HyperCredit\HyperCredit.exe")
Shell("HyperCredit.exe")

Me.Close()

As you can see this shouldn't happen because it deletes the file then download it.
The weird thing is the fact that it works fine just as it should when i launch the application from the exe, this only happens when i launch it from the shortcut
can someone please help me out?
Thanks
Edit: im getting this error mydirectory is not declared, it may be inaccessible due to its prptection level
Dim myfile As String = "HyperCredit.exe"

If System.IO.File.Exists(myfile) = True Then
    Dim fi As New FileInfo(myfile)
    fi.Delete()
End If

Dim pf As System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", pf & "\HyperCredit.exe")
Shell("HyperCredit.exe")

Me.Close()

A: The way I see it, the file actually does not exist from the app's working directory, which could be very different from what your code assumes when it tries to download.
Assuming the WD is in C:\Program Files is a mistake. On a 64 bits machine for example, that path could very well be Program Files (x32) if your app is a 32 bits application. Also, what if the system is installed on D: rather than C:?
You should instead use System.IO.Directory.GetCurrentDirectory() to dynamically retrieve the app's working directory and THEN use that as your file root directory.
EDIT:
You may want to use this instead:
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
This will give you your executable assembly's regardless of any shortcut's working directory. Likely you will prefer that.
Here how it should look like in your code:
Dim myfile As String = "HyperCredit.exe"
Dim myDirectory As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
Dim myFullPath As String = System.IO.Path.Combine(myDirectory, myFile)

If System.IO.File.Exists(myFullPath) Then
    System.IO.File.Delete(myFullPath)
End If

My.Computer.Network.DownloadFile("http://hypercredit.co.uk/HyperCredit.exe", myFullPath)

Shell(myFullPath)


text:
Q: How to add indent after formula? I have stuation like this:

I need indent after formulas (where question mark is). How to do that?
UPDATE
Code, used in here
\textbf{Определение 1\cite{1}.} \textit{Непрерывная на всей вещественной оси
функция $f(x)$ называется равномерной почти--периодической, если для каждого
$\varepsilon>0$ можно указать такое положительное число $l=l(\varepsilon)$,
что в каждом интервале длины $l$ найдется хотя бы одно число $\tau$, для
которого выполняется неравенство}
\[
|f(x+\tau)-f(x)|<\varepsilon(-\infty<x<\infty).
\]
Пространство равномерных почти--периодических функций, его обозначим через  $\mathbf{B}$, есть замыкание множества тригонометрических полиномов

A: To avoid the extra space that comes with an actual \par, you can issue a \hspace*{\parindent} following the formula.
As had been my original comment to the OP, David also suggests using an actual blank line (\par) after the formula to actually force a new paragraph.  However, for those using \parskip, this will cause additional vertical space to be inserted.  Since the OP replied to that comment, making reference to undesirable "empty space" being inserted, this perhaps applies to the OP's particular case.
The MWE shows the unusual case where both \parskip and \parindent are active.  I have set \parskip unusually large to amplify the effect.
\documentclass{article}
\usepackage[showframe]{geometry}
\parskip 4ex\relax% TO EXAGGERATE
\newcommand\fauxpar{\hspace*{\parindent}}
\begin{document}
text text text text text text
text text text text text text
\[y = x\]
\fauxpar Faux Par
text text text text text text
text text text text text text
text text text text text text
text text text text text text
\[y = x\]

Normal Par
text text text text text text
text text text text text text
text text text text text text
text text text text text text
\end{document}


text:
Q: Integral: $\int\frac{x^2}{\sqrt{4-x^2}} dx$ So, I am really just having one issue with this integral, but I will go through the steps I have taken.
Consider $$\int\frac{x^2}{\sqrt{4-x^2}} dx$$
First, I set $x = 2\sin\theta$, found $dx = 2\cos\theta\space d\theta$ and plugged this back in, making $$4\int \frac{\sin^2\theta}{\sqrt{1-\sin^2\theta}} \cos\theta \space d\theta$$
Using $\sin^2\theta + \cos^2\theta = 1$, I canceled $\sqrt{1-\sin^2\theta}$ with $\cos\theta$, leaving  $$4\int\sin^2\theta\space d\theta$$
Using $\sin^2\theta = \frac{1}{2}(1 -\cos2\theta)$,  I simplified, ending up with $$4(\frac{\theta}{2} - \frac{\sin 2\theta}{4})$$
When trying to put the solution back in terms of $x$, $\sin 2\theta$ is giving me trouble. Using the relationship from before, I got that $\theta = \sin^{-1}(\frac{x}{2})$. I am able to obviously substitute this back in for $\theta$, but again I am lost what to do with $\sin 2\theta$.

A: Hint: $\sin(2\theta)=2\sin(\theta)\cos(\theta)$. Use this to get everything in terms of $\theta$ instead of $2\theta$.

A: Hint
Just use that $$\sin 2\theta=2\sin \theta\cos\theta=2\left(\frac x2\right)\left(\sqrt {1-\frac {x^2}{4}}\right) =\frac {x\sqrt {4-x^2}}{2}$$


text:
Q: Неработает CopyFile C++ #include <winbase.h>

int main() {
    CopyFile("C:\\Users\\Asus\\Downloads\\hax.jar", "C:\\", false);
    GetLastError();
    Sleep(1000);
    return 0;
}

Не могу понять почему не копирует файл в директорию.

A: Вторым параметром функции CopyFile нужно указывать имя файла. Т.е. в вашем случае вызов должен быть
CopyFile("C:\\Users\\Asus\\Downloads\\hax.jar", "C:\\hax.jar", false);

И желательно обрабатывать ошибки. В тексте ошибок так же может быть полезная информация, которая пригодится для отладки.


text:
Q: Flutter SliverAppBar with CupertinoPageRoute Is there a way to use SliverAppBar with CupertinoPageRoute?
I've tried:
 onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
          case HomeScreen.routeName:
            return CupertinoPageRoute(
              builder: (_) => const HomeScreen(),
              settings: settings,
            );
          }
    }

But it's not working when navigating from a page with SliverAppBar.
Sadly I can't use CupertinoSliverNavigationBar because there are not enough options for customization.


text:
Q: How do I get a return value from a signal handler in C? I read a similar question in this link but it didn't solve my problem so apologies for the repeat question.
I have the following code that basically receives Ctrl+C and Ctrl+Z when the program is executed but I would like for the 2 signal handler functions to return 1 when it receives the signals from terminal.
The link said something about using typedef and being fairly new to C I don't know how to implement that in the code I have.
Here's the code :
#include <stdio.h>
#include <signal.h>

/* Signal Handler for SIGINT */
void sigintHandler(int sig_num) {

    signal(SIGINT, sigintHandler);
    printf("\n Cannot be terminated using Ctrl+C \n");
    fflush(stdout);
}

/* Signal Handler for SIGTSTP */
void sigtstpHandler(int sig_num) {
    signal(SIGTSTP, sigtstpHandler);
    printf("\tCtrl+z received\n");
    fflush(stdout);
}

int main (void) {

    signal(SIGINT, sigintHandler);
    signal(SIGTSTP, sigtstpHandler);

    while(1) {}  //infinite loop.
    return 0;
}

Thank you for your time/help.
EDIT : I'd like for the 2 signal handler functions that are currently
    void sigintHandler(int sig_num)
    void sigtstpHandler(int sig_num)

to return 1 instead of just void. So that I can do something like
int sigIntReturn = signal(SIGINT, sigintHandler);

in the main function.

A: Signal handler is like an interrupt and does not return to anyone. The link you posted talks about returning value while setting the signal handler and not about signal handler returning value (Note that signal is just setting signal handler).
You can however do something similar to the following to return from main whenever the signal happens.
volatile int g_flag = 0;
void sigintHandler(int sig_num) {

    signal(SIGINT, sigintHandler);

    /* Not safe to use these functions in a signal handler */
    printf("\n Cannot be terminated using Ctrl+C \n");
    fflush(stdout);
    g_flag = 1;
}

int main (void) {

    signal(SIGINT, sigintHandler);
    signal(SIGTSTP, sigtstpHandler);

    while(g_flag == 0) {}  //infinite loop.
    return g_flag;
}

Please note that it is a busy loop in main which is not recommended. You an use something like eventfd to signal.


text:
Q: C# getting json name without knowing them I have this Json:
{
  "objects": {
    "realms/lang/de_DE.lang": {
      "hash": "729b2c09d5c588787b23127eeda2730f9c039194",
      "size": 7784
    },
    "realms/lang/cy_GB.lang": {
      "hash": "7b52463b2df4685d2d82c5d257fd5ec79843d618",
      "size": 7688
    },
    "minecraft/sounds/mob/chicken/step2.ogg": {
      "hash": "bf7fadaf64945f6b31c803d086ac6a652aabef9b",
      "size": 3838
    },
    "minecraft/sounds/dig/gravel3.ogg": {
      "hash": "48f7e1bb098abd36b9760cca27b9d4391a23de26",
      "size": 6905
    },
    "minecraft/lang/uk_UA.lang": {
      "hash": "02ca127554fb1294b473bac256469a0d908ecd86",
      "size": 97299
    },
    "minecraft/sounds/mob/cat/hitt3.ogg": {
      "hash": "3d98b4b7c37a09101da00d8a3078e0acba6558f4",
      "size": 7371
    },
    "minecraft/sounds/mob/horse/zombie/hit3.ogg": {
      "hash": "ad126e435cca94054bf0d616301799a105526cde",
      "size": 7043
    },
    "minecraft/sounds/mob/endermen/portal.ogg": {
      "hash": "7b4b5323ef066caa1ae43cbe66fffd9dfce4ed32",
      "size": 10010
    },
    "minecraft/sounds/random/glass2.ogg": {
      "hash": "87c47bda3645c68f18a49e83cbf06e5302d087ff",
      "size": 7532
    },
    "minecraft/sounds/mob/bat/hurt1.ogg": {
      "hash": "fddba78b2426f8056be081c98fe82e8411a0a5cf",
      "size": 4878
    },
    "minecraft/sounds/ambient/cave/cave9.ogg": {
      "hash": "b463fa47816fe9a5dfe508093150e647403e4db6",
      "size": 27096
    },
    "minecraft/sounds/records/13.ogg": {
      "hash": "9cbed0e40296f68c61090c9b81816061e068a0ec",
      "size": 1071028
    },
    "minecraft/sounds/mob/enderdragon/wings1.ogg": {
      "hash": "5a368ed32b3357e31629451ace57eb30d90e8874",
      "size": 10617
    },
    "minecraft/lang/ast_ES.lang": {
      "hash": "fc2139572f55c973aedc694b8d633f2a4eb0907a",
      "size": 72927
    },
    "realms/lang/ast_ES.lang": {
      "hash": "3f0a1aea8af9451493927ecb8a18997881ad0e2f",
      "size": 7608
    },
    "minecraft/sounds/mob/cow/step3.ogg": {
      "hash": "482919bc631b317422ab44af3938259bea73fe83",
      "size": 7923
    },
    "minecraft/sounds/step/cloth3.ogg": {
      "hash": "9c63f2a3681832dc32d206f6830360bfe94b5bfc",
      "size": 4897
    },
    "minecraft/sounds/mob/endermen/hit2.ogg": {
      "hash": "cf60aefd0b742c3fa15e808c1a0c33aebd534cc5",
      "size": 6491
    },
    "minecraft/sounds/random/eat3.ogg": {
      "hash": "9f2c4bab5ed55f1714fffa223985c81babc8f6c0",
      "size": 5813
    },
    "minecraft/sounds/step/sand5.ogg": {
      "hash": "9fd6d2c633d276b952f2ff2aaa1fa7e5fb5efd2a",
      "size": 5182
    },
    "minecraft/sounds/step/ladder5.ogg": {
      "hash": "e9a1caaddcde79cdac7aa8eabde50d4cfd1bc578",
      "size": 6077
    },
    "minecraft/sounds/music/game/nuance1.ogg": {
      "hash": "cc1a80b6becfc6d6489c069f053d0a8adc71c339",
      "size": 156322
    },
    "minecraft/lang/zh_TW.lang": {
      "hash": "d2f3c9c340a5cfe30fb7e333c81a4d853d9bbddd",
      "size": 68697
    },
    "minecraft/sounds/random/eat1.ogg": {
      "hash": "dfee39084c771182f6b9e7cfb8c8bc4e255747bc",
      "size": 5678
    },
    "minecraft/icons/minecraft.icns": {
      "hash": "991b421dfd401f115241601b2b373140a8d78572",
      "size": 114786
    },
    "minecraft/lang/es_AR.lang": {
      "hash": "e55edae0011215873faeba154c7d89f590ddb748",
      "size": 74392
    },
    "minecraft/sounds/mob/blaze/breathe4.ogg": {
      "hash": "78d544a240d627005aaef6033fd646eafc66fe7a",
      "size": 22054
    },
    "minecraft/sounds/dig/sand4.ogg": {
      "hash": "37afa06f97d58767a1cd1382386db878be1532dd",
      "size": 5491
    }
  }
}

Here is my code:
    List<string> namesList = new List<string>();
    dynamic json1 = JsonConvert.DeserializeObject(data);

Now I'm stuck...
I have two problems: I have to read every name inside objects like
realms/lang/de_DE.lang

The problem is that i don't know the names and on the internet i just found how to read the values inside dynamic json objects and not how to read the name of it...
The second problem is that on another class i have to process all this data and i need the hashes too. Is it convenient to calculate the hash on the moment for every file(there are 675 files) or to pass the hashes as a return?
I already return a list converted to an array of URL's so i don't know how to return both the URL's and the HASH and then process them.
I add to the namelist the value with a foreach loop:
namesList.Add(finalurl);

And then i return this:
return namesList.ToArray();

A: You should create classes for deserialization like this:
public class MyClass
{
    [JsonProperty("objects")]
    public IDictionary<string, ObjectValue> Objects { get; set; }
}

public class ObjectValue
{
    [JsonProperty("hash")]
    public string Hash { get; set; }

    [JsonProperty("size")]
    public long Size { get; set; }
}

and then you can get your names like this:
MyClass json = JsonConvert.DeserializeObject<MyClass>(data);
var names = json.Objects.Keys.ToList();
var hash = json.Objects[names[0]].Hash; // Get the hash of the first item

Also don't forget to check if null and other possible errors (no data etc).

A: L.B. provides a good answer.
The json data looks to match this question here from user3468962. The accepted answer is posted in VB, however could provide a useful base.
It would also be useful to return a typed object. In my experience I have always tried to avoid dynamic properties where possiable as they are not type safe and can lead to legacy support issues.
Try...
Foo json = JsonConvert.DeserializeObject<Foo>(data);

...
public class Foo
{
  public string Hash { get; set; }
  public long Size { get; set; }
}


text:
Q: CAKeyFrameAnimation presentation layer seems not to change I'm using CAKeyframeAnimation to move CALayer on a circle trajectory. Sometimes I need to stop animation and to move animation to the point at which the animation stopped. Here the code:
CAKeyframeAnimation* circlePathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
CGMutablePathRef circularPath = the circle path;

circlePathAnimation.path = circularPath;
circlePathAnimation.delegate = self;
circlePathAnimation.duration = 3.0f;
circlePathAnimation.repeatCount = 1;
circlePathAnimation.fillMode = kCAFillModeForwards;
circlePathAnimation.removedOnCompletion = NO;
circlePathAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:.43 :.78 :.69 :.99];
[circlePathAnimation setValue:layer forKey:@"animationLayer"];
[layer addAnimation:circlePathAnimation forKey:@"Rotation"];

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    CALayer *layer = [anim valueForKey:@"animationLayer"];
    if (layer) {
        CALayer *presentationLayer = layer.presentationLayer;
        layer.position = presentationLayer.position;
    }
}

But the presentation layer has no changes in position!!! I read that it is no longer reliable from ios 8. So is there any other way I can find the current position of animated layer?

A: I wasn't aware that the position property of the presentation layer stopped telling you the location of your layer in iOS 8. That's interesting. Hit testing using the hitTest method on the presentation layer still works, I just tried it on an app I wrote a while back.
Pausing and resuming an animation also still works.
For a simple path like a circle path you could check the time of the animation and then calculate the position using trig.
For more complex paths you'd have to know about the path your layer was traversing. Plotting a single cubic or quadratic bezier curve over time is pretty straightforward, but a complex UIBezierPath/CGPath with a mixture of different shapes in it would be a bear to figure out.


text:
Q: variable of mixed types in R UPDATE
I imported a database from CSV file using the following command:
data.CGS <- read.csv("filepath", sep=";", na.strings=c(""," ","NA"), stringsAsFactors =F)

One column in the CSV file has different types of data, numerical, integers, percentages and characters strings.
Say, for simplicity, that this column has the following elements col=[1,2,1, c, 2%, 4%, 15.5, 16.5]
So, in R will read this column as if one created this variable
col<-c("1","2", "c", "2%", "4%", "15.5", "16.5", "1980", "1/12/1950")

My purpose is to do some tabulations and compute some statistics based on the "truly" numerical data, which in this example are all values except the letter "c" and the dates, 1980 and 1/12/1950.
What is the easiest way to do this in R ? Any help will be much appreciated.
Of course, there is the very simple thing to do, which is to coerce all elements to be numeric, but then in R this implies convert all characters into NA - which I do not like.

A: You asked a lot of questions in your question. You can have this as an example
 col<-data.frame(var = c("1","2", "c", "2%", "4%", "15.5", "16.5"))
col
library(dplyr)

by gsub you remove % sign from the variable var in filter you remove a cvalue from variable
col %>% mutate(var1 = gsub("%", "", var)) %>% filter(var1 != "c") %>% summarise(m_n = mean(as.numeric(var1)))

       m_n
1 6.833333

A: One way is to create a new vector that is separate from any text characters.
## Create new vector without any characters
col2 <- col[-grep("[a-zA-Z]", col)]

## To strip percentages (%)
strip_percents <- as.numeric(gsub("%", "", col2))

## All numbers except percentages
no_percents <- as.numeric(col2[-grep("%", col2)])

## Save strings in new vector
all_yo_strings <- col[grep("[a-zA-Z]", col)]

## Save percentages in a new vector
all_yo_percents <- col[grep("%", col)]
all_yo_percents <- as.numeric(gsub("%", "", all_yo_percents))/100

Does that work for your purposes?  It will preserve your text strings in the original col variable (which you can access by simply removing the - from col[-grep("[a-zA-Z]", col)]), while giving you a new, numeric vector.


text:
Q: saving csv file to s3 using boto3 I am trying to write and save a CSV file to a specific folder in s3 (exist).
this is my code:
from io import BytesIO
import pandas as pd
import boto3
s3 = boto3.resource('s3')

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

csv_buffer = BytesIO()

bucket = 'bucketName/folder/'
filename = "test3.csv"
df.to_csv(csv_buffer)
content = csv_buffer.getvalue()

def to_s3(bucket,filename,content):
  s3.Object(bucket,filename).put(Body=content)

to_s3(bucket,filename,content)

this is the error that I get:
Invalid bucket name "bucketName/folder/": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$"

I also tried :
bucket = bucketName/folder

and:
bucket = bucketName
key = folder/
s3.Object(bucket,key,filename).put(Body=content)

Any suggestions?

A: Saving into s3 buckets can be also done with upload_file with an existing .csv file:
import boto3
s3 = boto3.resource('s3')

bucket = 'bucket_name'
filename = 'file_name.csv'
s3.meta.client.upload_file(Filename = filename, Bucket= bucket, Key = filename)

A: This should work
def to_s3(bucket,filename, content):
    client = boto3.client('s3')
    k = "folder/subfolder"+filename
    client.put_object(Bucket=bucket, Key=k, Body=content)

A: This should work:
bucket = bucketName
key = f"{folder}/{filename}"
csv_buffer=StringIO()
df.to_csv(csv_buffer)
content = csv_buffer.getvalue()
s3.put_object(Bucket=bucket, Body=content,Key=key)

AWS bucket names are not allowed to have slashes ("/"), which should be part of Key. AWS uses slashes to show "virtual" folders in the dashboard.
Since csv is a text file I'm using StringIO instead of BytesIO


text:
Q: Relation between two polynomial subrings Let $\mathbb{Z}[x_1,x_2,\ldots, x_n]$ be ring in $x_1,\ldots, x_n$ with coefficients from $\mathbb{Z}$.
Let $e_1=x_1+x_2+\cdots + x_n$,  $e_2=\sum_{i<j} x_ix_j$,  $\cdots$, $e_n=x_1x_2\cdots x_n$ : elementary symmetric polynomials.
Let $s_1=x_1+x_2+\cdots + x_n$, $s_2:=x_1^2+x_2^2+\cdots + x_n^2$, $\cdots$, $s_k=x_1^k+x_2^k+\cdots + x_n^k$.
If $R=\mathbb{Z}[e_1,e_2,\ldots, e_n]$ is subring of $\mathbb{Z}[x_1,x_2,\ldots, x_n]$ generated by $e_1,e_2,\ldots, e_n$ and  $S=\mathbb{Z}[s_1,s_2,\ldots, ]$ is subring of $\mathbb{Z}[x_1,x_2,\ldots, x_n]$ generated by $s_1,s_2,\ldots, $, then is there any relation between $R$ and $S$?
(Note: I want to stay within $\mathbb{Z}[x_1,x_2,\ldots, x_n]$, i.e., I do not want to go for rational coefficients for symmetric polynomials).


text:
Q: Understanding SQL Case Conditions I am trying to get a better understanding of how the SQL Case Function works.
Say for example I have the following code in a query and value1 = 'ABCDE'
SELECT CASE ColumnName
           WHEN value1 LIKE '%ABC%' THEN 'Hello'
           WHEN value1 LIKE '%CDE%' THEN 'World'
           ELSE 'Nothing'
       END AS Answer
FROM TableName

I am confused by what this code will return.
I would assume from reading it should return HelloWorld, but having ran a similar query I have found it only returns Hello.
Can anyone explain why this is ?
Thanks

A: The CASE expression consists of a series of WHEN/THEN clauses.  Each clause tests a condition.
The CASE expression stops at the first WHEN condition that evaluates to true and returns the THEN value.  In your example, that would be "Hello".
Note:  The ColumnName after CASE is a syntax error, if you have conditions in the WHEN clauses.  I assume this is a typo because your query returns something.
If you want the values concatenated, then use an expression such as:
SELECT ((CASE WHEN value1 LIKE '%ABC%' THEN 'Hello' ELSE '' END) +
        (CASE WHEN value1 LIKE '%CDE%' THEN 'World' ELSE '' END)
       ) AS Answer
FROM TableName;


text:
Q: How to allow searching for users but not allow listing users in Firebase? I am trying to implement a function in my application to let an authenticated user search for another user by entering the user's email address.   I am trying to figure out the best way to implement the security rules in firebase to allow this type of searching, but to NOT allow a logged in user to simply list all users via /users.
Currently I have this security rule:
  "users" : {
    ".indexOn" : "email",
    ".read": "auth != null",
    "$uid": {
      ".write": "auth.uid === $uid"
    }

This clearly lets any authenticated user read the entire users collection.  Removing this line:
".read": "auth != null"

fixes this, but now I can no longer search for a user via email.  What is the recommended approach here?

A: Firebase has two rights you can grant:

*

*read

*write

There is no separate right to allow searching, so that means that anyone who can search a node can also read that node.
But there probably is a workaround to solve your problem. If we assume that you have a users node like this:
users
   twitter:4368352
       id:4368352
       name: "lestyn Lewis"
       email: "lewis@lestyn.net"
   twitter:209103
       id:209103
       name: "Frank van Puffelen"
       email: "puf@stackoverflow.com"

Hint: it would be nice if you could update your question and include the actual structure of your users node.
With the above structure, you'd have to give the users .read rights to all nodes under Users. This would allow them to read not only the email addresses and ids, but also any other information you might keep on them.
To give your users access to only a subset of this data, you can duplicate that data into another node. So if you want to allow all users to search on email address, then you need to add a node that maps email addresses to uids:
users
   twitter:4368352
       id:4368352
       name: "lestyn Lewis"
       email: "lewis@lestyn.net"
   twitter:209103
       id:209103
       name: "Frank van Puffelen"
       email: "puf@stackoverflow.com"
email_to_uid:
    "lewis@lestyn.net": "twitter:4368352"
    "puf@stackoverflow.com": "twitter:209103"

You can then give all users rights to search, but only give access to the full user settings to a more limited set of users:
"users" : {
  ".indexOn" : "email",
  "$uid": {
      ".read": "auth === $uid",
      ".write": "auth.uid === $uid"
  }
},
"email_to_uid" {
    ".read": "auth != null"
}

Note that you are essentially building your own index here, similar to what ".indexOn": "email" does, so that you can control what information goes in it and who can access it.


text:
Q: Cutting a string using multiple delimiters using the awk or sed commands I am using a SIPP server simulator to verify incoming calls.
What I need to verify is the caller ID and the dialed digits. I've logged this information to a file, which now contains, for example, the following:
From: <sip:972526134661@server>;tag=60=.To: <sip:972526134662@server>}

in each line.
What I want is to modify it to a csv file containing simply the two phone numbers, such as follows:
972526134661,972526134662

and etc.
I've tried using the awk -F command, but then I can only use the sip: as a delimiter or the @ or / as delimiters.
While, basically what I want to do is to take all the strings which begin with a < and end with >,  and then take all the strings that follow the sip: delimiter.
using the cut command is also not an option, as I understand that it cannot use strings as delimiters.
I guess it should be really simple but I haven't find quite the right thing to use.. Would appreciate the help, thanks!

A: OK, for fun, picking some random data (from your original post) and using awk -F as you originally wanted.
To note, because your file is "generated", we can assume a regular format for the data and not expect the "short" patterns to cause mis-hits.
[g]awk -F'sip:|@' -v OFS="," '{print $2,$4}' yourlogfile

It uses both sip: and @ as the Field Separator, by means of the alternation operator |. It can easily be extended to allow further characters or strings to also be used to separate fields in the input if required. The built-in variable FS can contain a regular expression/regexp like this.
For that first sample in your question, it yields this:
972526134661,972526134662

For the latest (revision 8) version, and guessing what you want:
[g]awk -F'sip:|@|to_number:' -v OFS="," '{print $2,$5}' yourlogfile

Yields this:
from_number,972526134662

The [g]awk is because I used gawk on my machine, and got same behaviour with awk.
Slight amendment in style, suggested by @fedorqui, to use the command-line option -v to set the value for the Output Field Separator (an AWK built-in variable which can be amended using -v like any other variable) and separating the print fields with a comma, so that they are treated in the output as fields, rather than building a string with a hard-coded "," and treating it as one field.

A: I would suggest using sed to extract the two numbers:
$ sed -n 's/^From: <sip:\([0-9]*\).*To: <sip:\([0-9]*\).*/\1,\2/p' file
972526134661,972526134662

The regular expression matches a line beginning with From and captures the two numbers after <sip:. If the spaces are variable, you may want to add * to those places.

A: You can use a regex replace, as long as the format stays the same (order is always From/To):
sed -E "s/^.*sip:([0-9]+)@.*sip:([0-9]+)@.*$/\1,\2/"

It's not a very specific or perfect solution, but in most cases an approach like this is enough.


text: Q: Is there a way to use fish shell in windows? I want to use fish shell in my vscode. But even with the windows subsystems, I am not able to do it. Is there any way to use fish shell with any vscode extension. Thanks in advance.


text:
Q: CSS divs not displaying inline I have a HTML page like below:

                D7

Home

About

Contact

Prestashop News

And my CSS is :
#header-wrapper{
    background:#F7F7F7;
    width:100%;
}
#header{
    width:1150px;
    margin:0 auto;
}
.logo-slogan-wrapper
{
    display:inline;
    background:#555;

}
.header__region
{
    display:inline;
    background:#99CC33;
}

#logo,#name-and-slogan,#site-name,#site-slogan
{
    display:inline;
}

.menu-block-wrapper{
    float:left;
    padding:10px 0;
}
.menu li{
    display:inline;
    list-style:none;
    margin-left:10px;

I was expecting the name,slogan and the menu to be inline. But instead , the menu is not coming inline and the background:#99CC33; for div header__region is not changing to the desired background color ! How can I overcome these problems ?

A: Depending on what you're going for:
.header__region {
    float:left;
    // or right
}

or
.header__region {
    display: inline-block;
}


text:
Q: SharePoint show hide after presave I have a requirement to show  three text boxes and make them mandatory on check of radio button  else hide the text boxes.
I am able to show hide in New and Edit form. But on Disp read form I am not able to show hide text boxes on radio button check or uncheck:
<script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {

   $('nobr:contains("Description )")').closest('tr').hide();
   $('nobr:contains("Causes )")').closest('tr').hide();
   $('nobr:contains("Immediate)")').closest('tr').hide();
   //$('input:radio').change(function(){
   $('input:radio').on('change', function() {
      if($("span[title='Line of fire']>input").is(":checked")){
          $('nobr:contains("Description )")').closest('tr').show();
          $('nobr:contains("Causes )').closest('tr').show();
          $('nobr:contains("Immediate )")').closest('tr').show();
      }
   });
  });

function PreSaveAction() {
var jq = jQuery.noConflict();
var txtTitle1 = jq(":input[Title='Description ']").val();
var txtTitle2 = jq(":input[Title='Causes ']").val();
var txtTitle3 = jq(":input[Title='Immediate']").val();
var r =(jq("span[title='Other']>input").is(":checked"));
if((txtTitle3 == "")&& r === true){
alert("Please enter Immediate)");
return false;
}

else{

return true;

}
}
</script>


text:
Q: Scatterplot with variable X on X axis and Y on Y axis I have a dataset with variable A (Age) and B (performance). I want to create a scatterplot with variable A on the X axis and B on the Y axis, but Excel is acting all weird with it.
I have approx 120 data entries, and when I select a scatterplot it appears fine at first glance. But, one of the variables is Age. The highest age is 89, yet the graph shows entries as high as 130. Presumably it has coded the X axis by entry number rather than Age. I've tried everything back and forth and I don't understand why Excel won't show a simple XxY graph with Age along the X-axis and performance along the Y-axis.
This shouldn't be difficult, but I have been struggling for an hour without success.
Say the dataset is this:

I can't imagine it should be hard, but all I can get is this:

I imagine this occurs because it has not registering Age as the X axis, but I cannot seem to find out how to do this.

A: Make sure the numbers are really numbers, not text that looks like numbers. From the screenshot of the dataset, it appears that the last few visible rows have text in column A. The green warning triangle is a giveaway.
To quickly change all text to numbers, select the column, click Data > Text to Columns > next > next > finish.


text:
Q: How can i print number of days between of each products expiry date and today date in a template //django view and html template I have model called product in which i have expiry date as DateFiled, i need to calculate number of days left for expiry for all the products and display the product name and number of days left for expiry of every products from product table.

class Product(models.Model):
    category = models.ForeignKey('store.Category',on_delete=models.CASCADE,default='SYRUP')
    itemname = models.CharField(max_length=50,blank=True,null=True)
    itemexpdate = models.DateField(auto_now_add=False, auto_now=False,blank=True,null=True)

class Category(models.Model):
    name = models.CharField(max_length=200,blank=True)

def days_left_for_expiry(expiry_date):
    today = date.today()
    expiry = expiry_date
    delta = expiry - today
    return str(delta.days)

def home(request):
     d = Product.objects.all()
     for product in d:
        expiry_date = product.itemexpdate
        days_left= days_left_for_expiry(expiry_date)
     return render(request,'store/dashboard.html',{'days_left':days_left})

{% for i in d %}

        {{ i.itemname }}
        {{ i.itemexpdate }}
        {{days_left}}

{% endfor %}

output:
image attached
[enter image description here][1]

  [1]: https://i.stack.imgur.com/CU1UZ.png

A: Just create a property on the Product model:
class Product(models.Model):
    category = models.ForeignKey('store.Category',on_delete=models.CASCADE,default='SYRUP')
    itemname = models.CharField(max_length=50,blank=True,null=True)
    itemexpdate = models.DateField(auto_now_add=False, auto_now=False,blank=True,null=True)

    @property
    def days_left(self) -> str:
        today = date.today()
        expiry = self.itemexpdate
        delta = expiry - today
        return str(delta.days)

And you can access it from inside the template:
{% for i in d %}

        {{ i.itemname }}
        {{ i.itemexpdate }}
        {{ i.days_left }}

{% endfor %}

NB you would also need to pass the Product queryset to the template through the context:
def home(request):
     d = Product.objects.all()
     return render(request,'store/dashboard.html',{'d':d})


text:
Q: How to make recursive query in SQLite? if my data structure is like this
parentA
-------parentAA
--------------parentAAA
---------------------childA

if i can get "childA.name" . how can i know all the parent name till the top level.
so it will be like this > parentA/parentAA/parentAAA/childA
what is the best way to do this ?
i'm working with SQLite and JAVA/android .. thanks in adv.
____________ EDIT
Okay guys, thanks for all of u . so i just make it by repeating "select query". BOTTOM-UP this is the method i create
public String getPath(int id, int type) {
        StringBuilder pathBuilder = new StringBuilder();
        String sql = null;
        int parentId = 0;

        if (id == 0) {
            pathBuilder.insert(0, "/root/");
            return pathBuilder.toString();
        }

        if (type == LayerManagementActivity.PARENT) {
            do {
                sql = "SELECT id, name, parent_id from parents_table where id="
                        + id;
                Cursor c = mDatabase.rawQuery(sql, null);
                if (c.moveToFirst()) {
                    parentId = c.getInt(2);
                    id = c.getInt(0);
                    pathBuilder.insert(0, "/" + c.getString(1));
                    c.close();
                }
                id = parentId;
            } while (parentId != 0);

            pathBuilder.insert(0, "/root");
            pathBuilder.append("/");

        } else if (type == LayerManagementActivity.CHILD) {
            sql = "SELECT id, name, folder_id FROM childs_table WHERE id=" + id;
            Cursor c = mDatabase.rawQuery(sql, null);
            if (c.moveToFirst()) {
                pathBuilder.append(c.getString(1));
                id = c.getInt(0);
                int folderId = c.getInt(2);
                String path = getPath(folderId, LayerManagementActivity.PARENT);
                pathBuilder.insert(0, path);
            }
            c.close();
        }
        Log.d("crumb", pathBuilder.toString());
        return pathBuilder.toString();
    }

A: In this SQLite Release 3.8.3 On 2014-02-03 has been added support for CTEs. Here is documentation WITH clause
Example:
WITH RECURSIVE
cnt(x) AS (
 SELECT 1
 UNION ALL
 SELECT x+1 FROM cnt
  LIMIT 1000000
)
SELECT x FROM cnt;

A: I have a table called project with a column named rates.
The rates column is a string that holds a JSON array.
To split this string into rows that I can use in an IN statement to get rows from the related table, I use this for the IN part
WITH
 split(s, p) AS (
 SELECT substr(printf("%s%s", ss, ","), instr(ss, ",")+1), trim(substr(ss, 0, instr(ss, ","))) from ( select replace(replace(rates,"[",""), "]","") ss from project where rowid = 1)
 UNION ALL
 SELECT substr(s, instr(s, ",")+1), trim(substr(s, 0, instr(s, ","))) FROM split
 where p!=""
 )
 select p from split where p!=""

A: You can use nested set model. Nested sets have big advantage that they can be implemented in most SQL engines using simple, non-recursive SQL queries.

A: SQLite doesn't support recursive CTEs (or CTEs at all for that matter),
there is no WITH in SQLite. Since you don't know how deep it goes, you can't use the standard JOIN trick to fake the recursive CTE. You have to do it the hard way and implement the recursion in your client code:

*

*Grab the initial row and the sub-part IDs.

*Grab the rows and sub-part IDs for the sub-parts.

*Repeat until nothing comes back.


text:
Q: LibGDX image touchDown slow Currently I am working on a LibGdx project using Android Studio in Java.
I have images as buttons that the app user can click. (Ex: Play Button)
But i feel i am doing something wrong since after i click the image, it takes about 2 seconds to actually go to the Play Screen.
My Play Button's listener is pretty basic
Play Button Listener:
 playButton.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            state.set(new SelectionState(state, prefs, getImageManager()));
            return true;
        }
    });

I do not know what other information to include, sorry! But my main question is why does it take about 2 seconds to update.
I would understand if it would load all black then show the play screen if it took a second to draw it, but here it's just saying on the main screen for 2 seconds which seems like a long time when you push it.
Thanks in advance!


text:
Q: Background colour for H3 extendind more than the content i am having a tag  where i have added a Css for it as
      #jsn-maincontent_inner h3 {
       background-color:#BBB1A5;
       color:white;
       padding:3px 8px;
      text-transform:uppercase;
       }

but the background color extends for the whole row of the line and it is not limiting upto the content .
HOw to resolve this??

A: I thought I'd chip in to tell you why this is happening as the information may be useful in the future.
The "h3" element is a block element. This means it will generally take up an entire "row" as you describe it.
The reason a "span" element (for example) behaves differently is because it is an "inline" element, which means it will take up "just enough" space.
There are two solutions already up to help, you could also set
display: inline;

On the h3 element, but this will change other behaviour too.

A: The easiest thing to do is to put the text inside a span and put the background color on the span:
  #jsn-maincontent_inner h3 {
    padding:3px 8px;
    text-transform:uppercase;
   }
  #jsn-maincontent_inner h3 span {
    background-color:#BBB1A5;
    color:white;
   }

Text here

This will put the background color just around the text. If you want to actually shrink the h3 element, you can either set a width for it (though text will wrap if it is longer than the width), or make it an inline element (though there are other downfalls to this approach).

A: Try setting a width for that:
  #jsn-maincontent_inner h3 {
       background-color:#BBB1A5;
       color:white;
       padding:3px 8px;
       text-transform:uppercase;
       width:500px;
       }

You may also want to set the width for #jsn-maincontent_inner if it doesn't have already:
#jsn-maincontent_inner
{
   width:600px;
}


text:
Q: Perfect pairing in Kummer Theory for the inifinite case Currently, I am pondering about the following remark from Milne's Fields and Galois Theory:

Previously, Milne has shown that
$$
B(E)/F^{\times n} \to \operatorname{Hom}(\operatorname{Gal}(E/F),\mu_n), \quad: a \mapsto \left( \sigma \mapsto \frac{\sigma(a^{1/n})}{a^{1/n}} \right)
$$
is an isomorphism if $E/F$ is a finite Galois extension of exponent $n$. So in this case, the pairing above is perfect. But I am not sure if this is also true if $E/F$ is not finite.

Question: Is this remark also true for infinite Galois extension of exponent $n$ (and if yes, why)?

Here is the section where Milne has shown it for the finite case if anyone is curious (note: $B(E) = E^{\times n} \cap F^\times$ here):

I am not sure here where we needed the finiteness of the extension in this explanation. I do not see immediately why it is needed here, so maybe this explanation also holds for the infinite case (but I may be wrong...).

A: The proof of Kummer's duality theorem certainly needs a finiteness assumption (look again at the details). For infinite abelian galois extensions $E/F$, you must adapt the hypotheses in an obvious way. To fix ideas, let us pick a prime $p$ and consider only infinite abelian pro-$p$-extensions (see example below). To extend Kummer's duality, we clearly need $F$ to contain the group $\mu_{p^{\infty}}$ of all $p$-primary roots of unity. As for the infinite pro-$p$ abelian extension $E/F$, consider it as an inductive limit of finite abelian $p$-extensions $E_n/F$. In characteristic $\neq p$, finite Kummer theory applies to show that $X_n:=Gal(E_n/F)\cong Hom(R_n,\mu_{p^n})$, where the Kummer radical $R_n$ is a finite subgroup of ${F^*/F^*}^{p^n}$. Taking appropriate limits, we get $X_{\infty}:=Gal(E/F)\cong \varprojlim Hom(R_n,\mu_{p^n})$. Writing  $R_{\infty} $ for the inductive limit of the $R_n$, we see that $R_{\infty}$ is a subgroup of $F^* \otimes \mathbf Q_p/\mathbf Z_p$, hence a perfect compact-discrete duality $X_{\infty} \times R_{\infty} \to \mathbf Q_p/\mathbf Z_p$ (Pontryagyn duality).
I singled out this example because it's the starting point of the algebraic part of the so called Iwasawa theory, where $K$ is a given number field containing $\mu_p$, $F=K(\mu_{p^{\infty}})$, and $E/F$ has particular arithmetic properties (e.g. is unramified everywhere). Then $Gal(F/K)\cong \mathbf Z_p$ (pro-$p$-cyclic) acts continuously on $X_{\infty}$ via inner automorphisms. The extraordinary phenomenon is that this action gives rise to the construction of the $p$-adic zeta function (the $p$-adic analogue of the complex Dedekind function.)


text:
Q: Steps of multinomial probit estimation Does anybody have any source containing explanation of steps in estimating coefficients of multinomial probit model (from likelihood function to first and second derivatives)? Thanks in advance.
EDIT:
The dependent variable follows a multinomial distribution with J levels:
$f(y|\beta)=\prod_{i=1}^N\left\{\frac{n_i!}{\prod_{j=1}^Jy_{ij}!}\cdot \prod_{j=1}^J\pi_{ij}(\beta)^{y_{ij}}\right\}$
Since we want to maximize this with respect ot $\beta$, the factorial term that do not contain any of the $\pi_{ij}$ terms can be treated as constant. Thus, the first step would be specifying the correct form of the multinomial probit likelihood function:
$\ell=\prod_{i=1}^N\prod_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})^{y_{ij}}\cdot[1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})]^{n_i-\sum_{j=1}^{J-1}y_{ij}}$
or if we take the natural logarithm:
$ln \ell=\sum_{i=1}^N\sum_{j=1}^{J-1} y_{ij} \cdot ln \Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})+ ({n_i-\sum_{j=1}^{J-1}y_{ij}}) \cdot ln[1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})]$
Would this be the correct form of the kernel of multinomial probit likelihood function which we need to maximize? Is there any simpler form?
How to proceed with the second and third step - first and second derivatives of the log-likelihood function? I would prefer if someone could help a self-learner with the symbolic computation (not in the matrix form).

EDIT #2 (second derivative of the log-likelihood function based on Xi'an's answer):
$\dfrac{\partial^2}{\partial\beta_{kj}\beta'_{kj}}=-\sum_{i=1}^N \cdot\left\{ y_{ij} \cdot \dfrac{(\sum_{k=1}^Kx_{ik}\beta_{jk})\cdot\phi(\sum_{k=1}^Kx_{ik}\beta_{jk})}{\Phi(\sum_{k=1}^Kx_{ik}\beta_{jk})}+y_{ij}\cdot\frac{\phi^2(\sum_{k=1}^Kx_{ik}\beta_{jk})}{\Phi^2(\sum_{k=1}^Kx_{ik}\beta_{jk})}-y_{iJ}\cdot\frac{(\sum_{k=1}^Kx_{ik}\beta_{jk})\phi(\sum_{k=1}^Kx_{ik}\beta_{jk})}{[1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{jk})]^2}+y_{iJ}\cdot\frac{(\sum_{k=1}^Kx_{ik}\beta_{jk})\sum_{j=1}^{J-1}(\Phi\sum_{k=1}^Kx_{ik}\beta_{jk})\phi(\sum_{k=1}^Kx_{ik}\beta_{jk})}{[1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{jk})]^2}+y_{iJ}\cdot\frac{[\phi(\sum_{k=1}^Kx_{ik}\beta_{jk})]^2}{{[1-\sum_{j=1}^{J-1}(\Phi\sum_{k=1}^Kx_{ik}\beta_{jk}}]^2}     \right\}x_{ik}x'_{ik}$

A: While you can indeed write the derivatives of the above [corrected] log-likelihood
$$\dfrac{\partial}{\partial\beta_{kj}}\sum_{i=1}^N \left\{y_{ij} \cdot ln \Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})+ y_{iJ} \cdot ln\left[1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})\right]\right\}$$
as
$$\sum_{i=1}^N \left\{y_{ij} \dfrac{x_{ik}\varphi(\sum_{k=1}^Kx_{ik}\beta_{kj})}{\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})}- y_{iJ} \dfrac{x_{ik}\varphi(\sum_{k=1}^Kx_{ik}\beta_{kj})}{1-\sum_{j=1}^{J-1}\Phi(\sum_{k=1}^Kx_{ik}\beta_{kj})}\right\}$$
I would suggest using instead an EM algorithm for deriving those estimators.


text:
Q: Detecting SINGLE key presses in CONSOLE C# I'm new to coding and have decided to start with C#. I've decided to write a simple console program that will detect key press and if only Enter is pressed, it will show number. The problem is that you can just hold down key and it will continue to show numbers. What should I add to my code so program will detect only SINGLE presses and ignore if user is HOLDING the key?
(I didn't find anything about this issue for CONSOLE C#, only for Forms one. Neither on this forum, nor in Web at all)
Thanks in advance
static void Main(string[] args)
{
    Console.WriteLine("Press Enter to play!");

    int num = 0;
    void WaitForKey(ConsoleKey key)
    {
        while (Console.ReadKey(true).Key != key)
        { }
    }

    for (int i = 0; i < 10; i++)
    {
        WaitForKey(ConsoleKey.Enter);
        Console.Write("{0} ", num);
        num++;
    }
}

A: If your task is to count amount of changes of typed/holded keys you can do it with just remembering of last key
var lastChar = char.MaxValue;
var index = 0;
do
{
    var x = Console.ReadKey();
    if (lastChar != x.KeyChar)
    {
        lastChar = x.KeyChar;
        Console.WriteLine(++index);
    }
} while (index < 10);

If you need to define single key you can use StopWatch class to check time lapsed from previous key had come (in the example 300 is only for testing, I would suggest to research it deeply if that is fit your goal)
var sw = Stopwatch.StartNew();
do
{
    var x = Console.ReadKey();
    if (sw.ElapsedMilliseconds > 300)
    {
        Console.WriteLine(++index);
    }
    sw.Restart();
} while (index < 10);

or combine both of the ways

A: Yes, you cant use ReadKey here. I would recommend to use ReadConsoleInput WinApi function. You can write wrapper class for this purpose, for example:
internal class KeyboardInput
{
    private readonly short _exitKey;
    private readonly uint[] _keyStates = new uint[short.MaxValue];

    public KeyboardInput(ConsoleKey exitKey)
    {
        _exitKey = (short) exitKey;

        // subscribe with empty delegates to prevent null reference check before call
        OnKeyDown += delegate { };
        OnKeyUp += delegate { };
    }

    public event Action<char, short> OnKeyDown;
    public event Action<char, short> OnKeyUp;

    public void Run()
    {
        var exitKeyPressed = false;
        var nRead = 0;
        var records = new INPUT_RECORD[10];

        var handle = GetStdHandle(STD_INPUT_HANDLE);
        while (!exitKeyPressed)
        {
            ReadConsoleInputW(handle, records, records.Length, ref nRead);

            for (var i = 0; i < nRead; i++)
            {
                // process only Key events
                if (records[i].EventType != KEY_EVENT) continue;

                // process key state
                ProcessKey(records[i].KeyEvent.wVirtualKeyCode, records[i].KeyEvent.bKeyDown,
                    records[i].KeyEvent.UnicodeChar);

                // check for exit key press
                if ((exitKeyPressed = records[i].KeyEvent.wVirtualKeyCode == _exitKey) == true) break;
            }
        }
    }

    private void ProcessKey(short virtualKeyCode, uint keyState, char key)
    {
        if (_keyStates[virtualKeyCode] != keyState)
            if (keyState == 1) OnKeyDown(key, virtualKeyCode);
            else OnKeyUp(key, virtualKeyCode);

        _keyStates[virtualKeyCode] = keyState;
    }

    #region Native methods

    private const short KEY_EVENT = 0x0001;
    private const int STD_INPUT_HANDLE = -10;

    [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr GetStdHandle(int nStdHandle);

    [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool ReadConsoleInputW(IntPtr hConsoleInput, [Out] INPUT_RECORD[] lpBuffer, int nLength,
        ref int lpNumberOfEventsRead);

    [StructLayout(LayoutKind.Explicit)]
    private struct INPUT_RECORD
    {
        [FieldOffset(0)] public readonly short EventType;

        //union {
        [FieldOffset(4)] public KEY_EVENT_RECORD KeyEvent;

        //[FieldOffset(4)]
        //public MOUSE_EVENT_RECORD MouseEvent;
        //[FieldOffset(4)]
        //public WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
        //[FieldOffset(4)]
        //public MENU_EVENT_RECORD MenuEvent;
        //[FieldOffset(4)]
        //public FOCUS_EVENT_RECORD FocusEvent;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct KEY_EVENT_RECORD
    {
        public readonly uint bKeyDown;
        public readonly short wRepeatCount;
        public readonly short wVirtualKeyCode;
        public readonly short wVirtualScanCode;
        public readonly char UnicodeChar;
        public readonly int dwControlKeyState;
    }

    #endregion
}

Example of usage:
internal class Program
{
    private static void Main(string[] args)
    {
        var kbInput = new KeyboardInput(ConsoleKey.Escape);
        kbInput.OnKeyDown += OnKeyDown;
        kbInput.OnKeyUp += OnKeyUp;

        kbInput.Run();
    }

    private static void OnKeyDown(char key, short code)
    {
        Console.WriteLine($"Key pressed: {key} (virtual code: 0x{code:X})");
    }

    private static void OnKeyUp(char key, short code)
    {
        Console.WriteLine($"Key released: {key} (virtual code: 0x{code:X})");
    }
}

A: Did you try to add a method keyRelease like that in your loop for after num++ :
 WaitForKeyRelease(ConsoleKey.Enter);
And in your method : while (Console.ReadKey(true).Key == key)
You wait until the key pressed is not enter so it's like a key release.

A: You can check if "enter" is inputted by doing something like this:
`
string input = Console.ReadLine();
if (input == "") {
     //do stuff
}

`


text:
Q: Reverse selection in ArcPy? I am trying to find out the counties that don't contain any stores in ArcGIS using python.
I have a point layer (representing the stores) and a polygon layer (counties). I have managed to write some code to find out the counties that DO contain the stores. The code is below.
import arcpy
arcpy.env.overwriteOutput = True
path="C:/Users/XARDAS/Documents/ArcGIS/Packages/Romania1000k_9E5B7FEC-6005-4D3A-81EA-E95FAACEF69E/v101/ro1mil.gdb"
arcpy.MakeFeatureLayer_management(path+"/Counties", "Counties_lyr")
arcpy.MakeFeatureLayer_management(path+"/Stores", "Stores_lyr")
arcpy.SelectLayerByAttribute_management("Stores_lyr", "NEW_SELECTION","Type=1")
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION")

So this gives me the counties that have stores but I would like to somehow inverse the intersection for the program to give me the ones that don't have any stores. I have thought about just deleting the selected counties but I don't think that it would be too nice.

A: Since you have selected everything that you don't want selected, inverting (or switching) the selection will give you what you want. (ref help page)
Add this line at the end:
arcpy.SelectLayerByAttribute_management("Counties_lyr", "SWITCH_SELECTION")

A: The answer above works but SelectLayerByLocation allows you to invert the selection within the function:
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION","INVERT")


text:
Q: Assuming the Goldbach conjectures are true, will all $O$ and $O ⋅ 2$ share at least $1$ of the $p$'s in such a way that the remaining are also $p$'s? Assuming the Even Goldbach conjecture is true, it will mean that every even number greater than $2$ as $E$ can be represented as the sum of $2$ primes as $p$'s
Assuming the Odd Goldbach conjecture is true, it will mean that every odd number greater than $7$ as $O$ can be represented as the sum of $3$ primes as $p$'s
Combining all the possibilities, will all $O$ 's and $O ⋅ 2$ 's share at least $1$ of the $p$'s in such a way that the remaining are also $p$'s ? Will there be a way to prove it?
Examples:
$7 = 3 + 2 + 2$ and $14 = 3 + 11$ ($3$ in both)
$9 = 2 + 2 + 5$ and $18 = 13 + 5$ ($5$ in both)
$11 = 5 + 3 + 3$ and $22 = 3 + 19$ ($3$ in both)
$13 = 7 + 3 + 3$ and $26 = 7 + 19$ ($7$ in both)
$15 = 2 + 2 + 11$ and $30 = 11 + 19$ ($11$ in both)
$17 = 7 + 5 + 5$ and $34 = 5 + 29$ ($5$ in both)
$19 = 7 + 7 + 5$ and $38 = 31 + 7$ ($7$ in both)
$21 = 11 + 5 + 5$ and $42 = 11 + 31$ ($11$ in both)
$23 = 5 + 5 + 13$ and $46 = 41 + 5$ ($5$ in both)
$29 = 5 + 5 + 19$ and $58 = 53 + 5$ ($5$ in both)


text:
Q: How to inject an JDK Proxied class in Spring which has protected methods? I have a fairly odd set of circumstances.  I'm using Spring 3.0.6 with a bean which implements and interface.  So far, pretty normal stuff.  My bean also has some protected methods.  I'm using some AOP (JDK Proxies) and everything works fine.
My problem comes in when I want to inject this bean into another package class.  Under normal circumstances, I would be able to inject the implementation and get access to the protected methods.  Unfortunately, since it is JDK proxied, I can only inject based on the interface.
Since I need access to the protected methods, I cannot declare the methods in the interface, so I'm somewhat in a catch-22 situation.  I tried switching to CGLIB proxies, but they crash with other advisors advising beans with final methods, etc) so that isn't really a solution.
Any suggestions as to what I can do?  I've tried using a @PostConstruct method to retrieve the bean from the application context, but there too (not surprisingly) it is only able to retrieve the Proxied bean and consequently cannot cast it to the implementation required.
Any suggestions would be appreciated.
Thanks!
Eric

A: The solution I can think of is to fetch implementation from proxy object.
http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/
As given in above link "((Advised)proxy).getTargetSource().getTarget()" returns target implementation fro proxy object. Now you can cast this target object into the Impl class & then on that impl class you can call protected method.
See if this works.


text:
Q: Django - Integrity error when tried deleting a project I only have one model and that's the only one I need. How to design the model in a way that I don't get the foreign key constraint error?
Here's my model:
class Project(models.Model):
    STATUS = (
        ('Inititated', 'Inititated'),
        ('Paused', 'Paused'),
        ('In progress', 'In progress'),
        ('Aborted', 'Aborted'),
        ('Completed', 'Completed')
        )

    PHASE = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
        ('6', '6'),
        ('7', '7'),
        ('8', '8'),
        ('9', '9'),
        ('10', '10')
    )

    p_id = models.IntegerField(null=True)
    p_name = models.CharField(max_length=100, null=True)
    c_name = models.CharField(max_length=100, null=True)
    c_mail = models.CharField(max_length=100, null=True)
    init_date = models.DateField(null=True)
    ect = models.DateField(null=True)
    status = models.CharField(max_length=200,null=True, choices=STATUS)
    collabs = models.IntegerField(null=True)
    phase = models.IntegerField(null=True, choices=PHASE)

    def __str__(self):
        return self.p_name

    @property
    def phase_percentage(self):
        return self.phase * 10

A: Your problem is with phase = models.IntegerField(null=True, choices=PHASE). Because, as we can see it's an IntegerField, yet you are giving it choices with strings:
PHASE = (
    ('1', '1'),
    ('2', '2'),
    (...)
    ('10', '10')
)

Change it to:
PHASE = (
    (1, "1"),
    (2, "2"),
    ...
    (3, "3")
)

Because first value is the value actually passing to the field, and second is "human readable" value, that shows in rendered forms etc.
Before deleting you might need to change that field value in your objects.


text:
Q: How to make my python loop faster to deal with multiple rows I have below loop code and i have 60000 rows that is why my code is so slow. How can i make my code faster and more efficient?
My code :
import tensorflow as tf
from itertools import product
rst = []
for i, j in product(df2["Description"].to_list(), df1["Question"].to_list()) :
  inputs = tokenizer([i], [j], return_tensors="np", max_length=512)
  outputs = model(inputs)
  start_position = tf.argmax(outputs.start_logits, axis=1)
  end_position = tf.argmax(outputs.end_logits, axis=1)
  answer = inputs["input_ids"][0, int(start_position) : int(end_position) + 1]
  rst.append(tokenizer.decode(answer))

A: I looked into itertools.product()'s runtime. It seems it runs in O(n*m) In the worst case, this ends up being inefficient at O(n^2), should the two lists have the same length.
Assuming you're using something like Jupyter notebook, maybe you can create the product first in a separate cell above the loop? That may help speed up the loop's cell.
So something like this:
prd = product(df2["Description"].to_list(), df1["Question"].to_list())

followed by the next cell:
for i, j in prd :
...

Edit: Some more reasoning. I think it's the use of product() slowing your code down, and that's what you should focus on. If your 'Description' and 'Question' columns each have 60,000 rows and you apply product() using both of them as lists, it would return a list of 60,000 * 60,000 = 3,600,000,000 items.
3.6 billion items is a massive list for current-day computers to handle. If we try imitating this with the code below:
from itertools import product

a = [0] * 60000
b = [1] * 60000
c = product(a, b)

print(len(list(c)))

sure enough, my computer starts to struggle for memory space.
However, I think we can both agree my original solution isn't satisfactory, so I found this answer that better explains the difficulty of handling a list with several billion items and proposes a solution involving emulated lists. If you really need a list that big, I suggest looking into that or figuring out how to do it concurrently.


text:
Q: Derivative of definite integral using Taylor's theorem So I want to obtain the following form:
For $x, p \in R^n$
$$\nabla f(x+p) = \nabla f(x) + \int^1_0 \nabla^2 f(x+tp)p \,dt$$ for $f$ twice continuously differentiable and $t \in (0,1)$.
Taylor's theorem in integral form is:
$$f(x) = f(a) + \int^x_a \nabla f(t) (x-t)\,dt$$ from here: https://www.math.upenn.edu/~kazdan/361F15/Notes/Taylor-integral.pdf
My approach is:
$$f(x+p) = f(x) + \int^{x+p}_x \nabla f(t) (x+p-t)\,dt$$
Reformulated as:
$$f(x+p) = f(x) + \int^1_0 \nabla f(x+tp)(1-t)p\,dt$$
$$= f(x) + \int^1_0 \nabla f(x+tp) p \,dt  - \int^1_0 \nabla f(x+tp) t p \,dt$$
But I am not sure how to take the derivatives of the integrals with respect to x; am I at a dead end? Should I instead, just begin with $\nabla f(x)$ in place of $f(x)$ when I apply Taylor's theorem?

A: Okay, I figured out the problem.
Taylor's theorem in integral form is actually $$f(x) = f(a) + \int^x_a \nabla f(t) \,dt$$
From there, we have $$f(x+p) = f(x) + \int_0^1 \nabla f(x+tp)p\,dt$$
And we can substitute $\nabla f(x)$ for f(x) into the above statement.
EDIT:
The above is incorrect. Using https://www.math.washington.edu/~folland/Math425/taylor2.pdf (page 3), (with the same notation regarding $\alpha$)
$$f(x+p) = f(x) + \sum_{|\alpha| = 1} \frac{p^{\alpha}}{\alpha!} \int_0^1 \partial^{\alpha} f(x+pt) \,dt $$
$$f(x+p) = f(x) + \sum_{j=1}^n p_j \int_0^1 \partial_j f(x+pt) \,dt = f(x) + p \cdot \int_0^1 \nabla f(x+pt)\,dt $$
Taking the gradient of the above:
$$\frac{\partial}{\partial_i} f(x+p) = \frac{\partial}{\partial_i} f(x) + \frac{\partial}{\partial_i} p \cdot \int_0^1 \nabla f(x+pt) \, dt = \frac{\partial}{\partial_i} f(x) + p \cdot \int^1_0 \frac{\partial}{\partial_i} \nabla f(x+pt) \,dt $$
We have overall that
$$\nabla f(x+p) = \nabla f(x) + \int^1_0 \nabla^2 f(x+pt) p \, dt$$


text:
Q: Spring Default Profile Selection Based on Scope My application has an embedded database as a "test" dependency (Maven test), but this causes an exception when you want to start the application without any -D switches because the jdbc driver is declared in the application.yml (see below).
Is it possible to set the datasource based on the scope (i.e. runtime or test)? Or better yet can you change the default profile without any -D switches (e.g. -Dspring.profiles.active=test)?
This might seem trivial, but it's confusing for our team that you can successfully run tests in your IDE, but then when you try to "run the application" it fails unless you set the -D switch.
datasource:
  url: jdbc:h2

spring:
  profiles: profile1

datasource:
  url: jdbc:postgresql

A: If you use the embedded database only for tests, then you can place an application.properties (or .yml) in the folder src/test/resources/ where you put all properties for test running in. At least that works for me. So you don't need to put your production properties into a profile and they are used when you run your application.

A: *

*Move application.yml in src/test/resources/

*You can set the default profile with

    datasource.url=jdbc:h2  =>

    datasource:
      url: jdbc:h2
    ---

    spring:
      profiles: profile1

    datasource:
      url: jdbc:postgresql


text:
Q: How to disable ipython prompt blinking? When I run ipython (7.12.0, this is from the Anaconda distro) in an xterm, the In prompts blink. It's super irritating. How do I turn it off?
The only thing that blinks is the text of the input prompt "In [#]:' at the beginning of every ipython input line. Nothing else in the terminal window blinks. To be specific, I am not asking about the cursor. The cursor is not blinking.
Note, there is a previous question, How to disable ipython prompt blinking?, that purports to answer this exact question. However, it is out-of-date. The answer given there doesn't work. Also, I suspect the answer was meant for the jupyter notebook. I'm asking about the terminal version of ipython.

A: The blinking can be is suppressed by the xterm cm option.
xterm +cm &

produces an xterm that, when ipython runs in it, has color but no blinking text.

A: The blinking cursor is a feature of the terminal itself.
If you are using XTerm, you can disable the cursor:
setterm -cursor off

You can re-enable it with:
setterm -cursor on


text:
Q: replace strings with placeholders in python I am trying to replace the variables with placeholders like XXX. The words "hello" and "morning" are printed as-is because they appear in another list.  The following code works, but prints extra placeholders.
import re

mylist = ['hello', 'morning']
nm = [
    "Hello World Robot Morning.",
    "Hello Aniket Fine Morning.",
    "Hello Paresh Good and bad Morning.",
]

def punctuations(string):
    pattern = re.compile(r"(?u)\b\w\w+\b")
    result = pattern.match(string)
    myword = result.group()
    return myword

for x in nm:
    newlist = list()
    for y in x.split():
        for z in mylist:
            if z.lower() == punctuations(y.lower()):
                newlist.append(y)
            else:
                newlist.append("xxx")
    print(newlist)

Output:
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']

Expected output:
['Hello', 'xxx', 'xxx',  'Morning.']
['Hello', 'xxx', 'xxx',   'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']

A: You're reaching for python's vanilla string functions and regular expressions when actually your problem is better solved with formal parsing using Parsing Expression Grammar (PEP):
For example:
import pyparsing as pp

expr = pp.OneOrMore(pp.Word("hello") | pp.Word("world") | pp.Word(pp.alphas).setParseAction(pp.replaceWith("XXX")))

expr.parseString("hello foo bar world")

Yields:
(['hello', 'XXX', 'XXX', 'world'], {})

See module pyParsing and docs.

A: You have to break when you have found the word and only after checking all the elements in my_list evaluate if you have found something, and if not, append the placeholder
for x in nm:
    newlist = list()
    for y in x.split():
        for z in mylist:
            if z.lower() == punctuations(y.lower()):
                newlist.append(y)
                break
        else:
            newlist.append('xxx')
    print(newlist)


text:
Q: how to subtract only the time of datetime objects in python I want to subtract the time between 2 column: I have been using this:
row['window'] = datetime.datetime.strptime(row['Time'], '%H:%M:%S.%f') - datetime.datetime.strptime(row['announcement_time'], '%H:%M:%S')

This works and gives a result that look like this:
 window
-1 day, 23:29:00
-1 day, 23:29:05
-1 day, 23:29:10
-1 day, 23:29:15
-1 day, 23:29:20
-1 day, 23:29:25

However, I only want the time difference i.e. - 00:00:30. I have tried :
 row['window'] = datetime.datetime.strptime(row['Time'], '%H:%M:%S.%f').time() - datetime.datetime.strptime(row['announcement_time'], '%H:%M:%S').time()

But this gives an error :
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I have also tried .hour, .minute and .second but does not work very well.
Can someone please help.Thanks

A: Time objects don't have arithmetic that I'm aware of. For best practice you should use (datetime.datetime object - datetime.datetime object).days for example.
You can read more about it here.

A: -1 day, 23:29:25 is how negative timedeltas are printed. To get 00:00:30, use abs():
>>> from datetime import timedelta
>>> -timedelta(seconds=30)
datetime.timedelta(-1, 86370)
>>> str(-timedelta(seconds=30))
'-1 day, 23:59:30'
>>> str(abs(-timedelta(seconds=30)))
'0:00:30'

If timedelta() is more than a day, you could apply modulo arithmetic, to get  the time difference within a day:
>>> str(abs(-timedelta(days=10, seconds=30)))
'10 days, 0:00:30'
>>> str(abs(-timedelta(days=10, seconds=30)) % timedelta(days=1))
'0:00:30'

On Python 2, % timedelta() is not implemented. You could use .total_seconds() % 3600 instead or if you need only the whole number of seconds then just access .seconds attribute (it is always less than a day):
>>> abs(-timedelta(days=10, seconds=30)).seconds
30


text:
Q: Git how to forget branches so I am having trouble keeping my git tree clean.
First I am keeping branch for each new feature. Let's say that I create a branch called feature-1
git branch feature-1
git checkout feature-1
git push --set-upstream origin feature-1

Now I made a few commits and pushes and the feature 1 is complete and ready to be merged.
git checkout master
git merge feature-1

So currently feature 1 is merged into master. Now let's say that I screwed something up in the feature 1 without noticing and accidentaly merged it as shown above. And I need to erase every memory that feature 1 even existed.
But if I do
git reset --hard <last commit before branch merged>
git push --force
git branch -D feature-1 #deleting local and remote branch

# but now if I check if feature-1 is deleted
git checkout feature-1
some message like "set up to track remote branch feature-1"

git branch
*feature-1
master

As shown above, the branch feature-1 is still tracekd for some reason and its history with it.
Is there a series of command to prevent this behavior and to completely delete any signs that feature-1 and its commits ever were in the repo?
Thank you


text:
Q: Submit a form with a file using jQuery append I've a form where I have a table with 3 columns for simplicity:

*

*column 1 contains input field name

*column 2 contains multiple input fields colors

*column 3 contains multiple input file fields

I've a button to add a new row to my table
Also in each column 2 I've a button to add a new input text referred to the row. (COLORS)
Also in each column 3 I've a button to add a new input file referred to the row. (FILES)
For example:
<form id="form" action="" method="post">

    Name: <input type="text" class="name">

       Colors

         <input type="text" class="color">

       <button type="button" class="btn-addColor">Add new color</button>

       Attachments

         <input type="file" class="attachment">

       <button type="button" class="btn-addAttach">Add new file</button>

<button type="button" id="btn-addRow">Add new row</button>

<button type="button" id="btn-submit">Submit</button>

</form>

To add a new text input color:
$(".btn-addColor").on("click", function(e) {
   e.preventDefault();
   $(this).closest("td").find(".wrapperColor").append('<input type="text" class="color">');
});

To add a new file input:
$(".btn-addAttach").on("click", function(e) {
   e.preventDefault();
   $(this).closest("td").find(".wrapperAttach").append('<input type="file" class="attachment">');
});

Now, so all input fields are added dynamically and i don't know the number of rows and for each row the number of files
I use this method to post my data:
 $("#btn-submit").on("click", function(e) {
   e.preventDefault();

   var form = $('<form>', {
        'action': '',
        'method': 'POST',
        'target': ''
    });

    $("#mytable tr").each(function(index, element) {

       form.append($('<input>', {'name': 'mytable_rows['+index+'][Name]', 'value': $(this).find(".name").val(), 'type': 'hidden' }) );

        $(this).find(".color").each(function(indexColor, elementColor) {
             form.append($('<input>', {'name': 'mytable_rows['+index+'][Colors]['+indexColor+'][Color]', 'value': $(this).val(), 'type': 'hidden' }) );
        });

    });

    form.appendTo( document.body );

    form.submit();

 });

So on my destination page index.php I have this to retrieve data:
$array_rows = $_POST['mytable_rows'];
foreach ( $array_rows as $row ) {
    echo "NAME: " . $row['Name'];
    foreach ( $row['Colors'] as $color ) {
       echo "COLOR: " . $color['Color'];
    }
}

All this code is created to keep indexes of colors referred to each row. It work great but I don't understand how to apply same logic to my FILES input fields. Any suggest?


text:
Q: Set HTML content to the mail body of MFMailComposeViewController's view I'm using MessageUI framework to compose email in my app. I want set HTML content for the mail body.
So I refered Mugunthkumar's blog and I coded as follow,
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"Hello from California!"];

// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];

[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];

// Fill out the email body text
NSString *pageLink = @"http://mugunthkumar.com/mygreatapp"; // replace it with yours
NSString *iTunesLink = @"http://link-to-mygreatapp"; // replate it with yours
NSString *emailBody =
[NSString stringWithFormat:@"%@\n\n
Sent from MyGreatApp on iPhone. Download yours from AppStore now!
", @"title", pageLink, iTunesLink];

[picker setMessageBody:emailBody isHTML:YES];

[self presentModalViewController:picker animated:YES];
[picker release];

When I ran the app and go to the email compose view, I'm getting the following mail body,

I'm using XCode4 and iOS 4.3.
I can not see any issue with my code.
But I need to insert clickable URLs to my mail body.
please help !!

A: If you want to send an HTML-formatted email, it is wrong to escape the HTML tags in the email body. Use  instead of </a> etc.


text:
Q: UIView with self-contained UIGestureRecognizer code I have put together an UIView that incorporates pan, pinch and rotate gesture recognizers all completely within its own implementation code,  so that it'll work in any view controller even one with zero code (apart from turning off auto layout in Xcode).
#import "Subview.h"

@interface Subview () <UIGestureRecognizerDelegate>

@end

@implementation Subview

- (void)awakeFromNib
{
    [self addGestureRecognizer:[[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateView:)]];
    [self addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panView:)]];
    [self addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchView:)]];

    for (UIGestureRecognizer * gr in self.gestureRecognizers){
        gr.delegate = self;
    }
}

// delegate method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

// gesture actions:
- (void)rotateView:(UIRotationGestureRecognizer *)sender
{
    [self adjustAnchorPointForGestureRecognizer:sender];

    if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
        self.transform = CGAffineTransformRotate(self.transform, sender.rotation);
        sender.rotation = 0;
    }

}

- (void)panView:(UIPanGestureRecognizer *)sender
{
    [self adjustAnchorPointForGestureRecognizer:sender];

    if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [sender translationInView:self.superview];
        [self setCenter:CGPointMake(self.center.x + translation.x, self.center.y + translation.y)];
        [sender setTranslation:CGPointZero inView:self.superview];
    }
}

- (void)pinchView:(UIPinchGestureRecognizer *)sender
{
    [self adjustAnchorPointForGestureRecognizer:sender];

    if (sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged) {
        sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
        sender.scale = 1.0;
    }
}

- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateBegan) {
        CGPoint locationInView = [sender locationInView:self];
        CGPoint locationInSuperview = [sender locationInView:self.superview];

        self.layer.anchorPoint = CGPointMake(locationInView.x / self.bounds.size.width, locationInView.y / self.bounds.size.height);
        self.center = locationInSuperview;
    }
}

@end

It worked great so far and the compiler gives no warnings, but I'm not sure about a view setting its own frame and center, and being its own delegate. However it does help clean up the view controller and feels quite neat and portable. So is this actually causing any subtle bugs or breaking any best practice rules?


text:
Q: Controller and controller action not working after project name in Url I want url like localhost/projec_name/controller/controllerAction in yii2. But getting Object not found! screen if I use localhost/advanced/site/about in url (this controller and action is not deleted).
can you Guys please check the code? what I am doing wrong?
.htaccess in folder frontend/

.htaccess in folder advanced/ (root)

frontend/config/main.php

A: I got it what I was doing wrong.
I have added .htaccess file in folder frontend/
and now I have moved it in frontend/web and error is gone. :)


text:
Q: Jquery ajax post create a second form on form submit I have this form:
<form id='form'>
  Begin time<input id="begintime" type="text" name="begintime">

  End time<input id="endtime" type="text" name="endtime">

  <input name="submit" type="submit" value="Submit">
</form>

on my website it looks like this:

the thing is that I don't want the web page to refresh. so I made this ajax post:
      $(function () {

    $('#form').on('submit', function (e) {

      e.preventDefault();

      var begin = $("#begintime").val();
      var end = $("#endtime").val();

      $.ajax({
        type: 'post',
        url: '',
        data: {begin: begin, end: end},
        success: function (result) {
            $( result ).appendTo('p');
        }
      });

    });

    });

But every time is click on submit this happens:

also I use this to get the data:

<?php
$begin = $_POST['begin'];
$end = $_POST['end'];
?>

I have tried this:
   $('p').empty();

I put tihs inside of ajax code this is the result is the same. What am I doing wrong? please help. and thank you.

A: Try the code below instead. It will clear everything inside the p tag and append the form to i
success: function (result) {
    $('p').html(result);
}

A: You should just change the HTML, not append it like so
...
success: function (result) {
    $('p').html(result);
}
...


text:
Q: Is there a way to map an object graph with @Query? I'm am trying to migrate my SDN3 embedded configuration to using SDN 3.3.0 with a Neo4j instance in server mode (communicating via the REST API then).
When the DB was embedded making a lot of small hits to the DB was not a big deal as Neo4j is capable of handling this kind of queries super fast.
However now that I run my Neo4j separately from my application (ie. in server mode) making a lot of small queries is not advisable because of the network overhead.
User user = userRespository.findOne(123);
user.fetch(user.getFriends());
user.fetch(user.getManager());
user.fetch(user.getAgency());

This will trigger quite a few queries, especially if I want to get, not a single user, but a list of users.
Can I use the @Query annotation and fetch the user and the related entities and map it into an User object?
I was thinking of something like this:
@Query("MATCH (u:User)-[r:FRIEND]->(f) RETURN u,r,f"

Is such a thing possible with Spring Data Neo4j? Will it be possible with Spring Data Neo4j 4?

A: You can define a class for query result using the @QueryResult directive and let the method for the query return an object of that class, i.e.:
@QueryResult
public interface UserWithFriends {
    @ResultColumn("u")
    User getUser();

    @ResultColumn("f")
    List<User> friends();
}

@Query("MATCH (u:User)-[:FRIEND]->(f) WHERE u.name={name} RETURN u,f")
UserWithFriends getUserByName(@Param("name") String name);


text:
Q: Софт для удаленного управления Есть коммерческие Teamviewer и Anydesk, но там нехватает проброса консоли. Есть tmate, но там не хватает проброса портов. Nomachine - нужно знать ip:port которые прокинул клиент. А Гуакомоле бесполезен если машина и сервер в разных сетях.
tmate, но с пробросом туннелей отлично бы подошел.


text:
Q: Threading an endless while loop in Python 2 I'm not sure why this does not work. The thread starts as soon as it is defined and seems to not be in an actual thread... Maybe I'm missing something.
import threading
import time

def endless_loop1():
    while True:
        print('EndlessLoop1:'+str(time.time()))
        time.sleep(2)

def endless_loop2():
    while True:
        print('EndlessLoop2:'+str(time.time()))
        time.sleep(1)

print('Here1')
t1 = threading.Thread(name='t1', target=endless_loop1(), daemon=True)
print('Here2')
t2 = threading.Thread(name='t2', target=endless_loop2(), daemon=True)
print('Here3')
t1.start()
print('Here4')
t2.start()

Outputs:
Here1
EndlessLoop1:1446675282.8
EndlessLoop1:1446675284.8
EndlessLoop1:1446675286.81

A: You need to give target= a callable object.
target=endless_loop1()

Here you're actually calling endless_loop1(), so it gets executed in your main thread right away. What you want to do is:
target=endless_loop1

which passes your Thread the function object so it can call it itself.
Also, daemon isn't actually an init parameter, you need to set it separately before calling start:
t1 = threading.Thread(name='t1', target=endless_loop1)
t1.daemon = True


text:
Q: Replace characters in java string I am trying to replace the following text in some HTML:
[merchant]
I tried to use myString = myString.replace("\\[merchant\\]", "newText");
The string is not being replaced. Any ideas?

A: replace doesnt use a regular expression. Just use
myString = myString.replace("[merchant]", "newText");

A: Try this -
    String myString = "My Sampel String [merchant]. Another line with [merchant]";
    myString = myString.replace("[merchant]", "newText");

    System.out.println(myString);

You don't have to use \\ here.

A: String#replace uses string literals, not regexes, so you shouldn't escape any special characters like [ or ]:
myString = myString.replace("[merchant]", "newText");