text:
Q: How do I avoid changing a file's Linux permissions when saving over a samba connection? I have an Ubuntu development server and a Windows 7 workstation. I use Windows Gvim to edit files on the linux server, over a samba connection.
Saving files from Windows change the Linux permissions in weird way depending on the Windows app I'm using and also depending on whether there's a file extension or not.
Here are some tests
No extension; Notepad2: 644 to 764
matt@mattserver ~ % ls -l testfile
-rw-r--r-- 1 matt matt 0 2011-05-28 07:09 testfile
--- Save from Windows Notepad2 over network ---
matt@mattserver ~ % ls -l testfile
-rwxrw-r-- 1 matt matt 1 2011-05-28 07:09 testfile

No extension; Gvim: 644 to 760
matt@mattserver ~ % ls -l testfile
-rw-r--r-- 1 matt matt 0 2011-05-28 07:10 testfile
--- Save from Windows Gvim over network ---
matt@mattserver ~ % ls -l testfile
-rwxrw---- 1 matt matt 0 2011-05-28 07:11 testfile

Extension; Notepad2: 644 to 644 (good!)
matt@mattserver ~ % ls -l testfile.txt
-rw-r--r-- 1 matt matt 0 2011-05-28 07:13 testfile.txt
--- Save from Windows Notepad2 over network ---
matt@mattserver ~ % ls -l testfile.txt
-rw-r--r-- 1 matt matt 0 2011-05-28 07:13 testfile.txt

Extension; Gvim: 644 to 760
matt@mattserver ~ % ls -l testfile.txt
-rw-r--r-- 1 matt matt 0 2011-05-28 07:14 testfile.txt
--- Save from Windows Gvim over network ---
matt@mattserver ~ % ls -l testfile.txt
-rwxrw---- 1 matt matt 0 2011-05-28 07:14 testfile.txt

Here's the relavant portion of my smb.conf
[matt]
comment = Matt
path = /home/matt
public = yes
writable = yes
valid users = matt
create mask = 0771
directory mask = 0771
force user = matt
force group = matt

I want the permissions to not be affected at all when saving over the samba connection. How do I do that?

A: You can try setting in smb.conf the nt acl support to "no" :

This boolean parameter controls
  whether smbd will attempt to map UNIX
  permissions into Windows NT access
  control lists.
Default: nt acl support = yes
  Example: nt acl support = no

Another that might help is :

map archive = no

A: Try this: (smb.conf) store dos attributes = yes and (.vimrc) set backupcopy=yes
I just spent a few hours testing various options (using VIM 8.1.1 windows 32-bit), here's what I've found:
samba 3.6.23 x86_64 CentOS 6, ext4 w/extended attrs enabled
Everything mostly works correctly with all default options, assuming you have set backup copy = yes in VIM. map archive and store dos attributes don't make any difference. Vim's undo, swap and backup files are created with SMB's create mask, but the target file's permissions are preserved when overwriting.
The nt acl support option seems to break undo files, IF you set VIM's undo dir to some place outside of the Samba share (in Samba 3 only). So I guess it's better to set it to "no" in Samba 3.
samba 4.4.9 x86_64 CentOS 7, xfs w/extended attrs enabled
Same as Samba3, but you have to have store dos attributes set. However the backup file created by VIM in this configuration seems to always have group permissions set to rwx, no matter what I do, I don't know why. I disable VIM backups in my environment anyway, so it doesn't affect me. nt acl support doesn't make any difference w.r.t. UNIX permissions in Samba 4.
For completeness, my config files look like this (Samba 4):
smb.conf
    ...
    # Create new files with these permissions. Doesn't affect
    # old files being overwritten by VIM, only the new ones, as well
    # as swap & undo files.
    create mask = 0644

    # Used when creating directories over Samba
    directory mask = 0755

    # Seems to be necessary in Samba 4
    store dos attributes = yes

    # Seems necessary in Samba 3 with some VIM options
    #nt acl support = no
    ...

.vimrc
    ...
    # Don't leave backups behind when overwriting files
    set nobackup

    # Create a backup before overwriting a file, but delete it after
    # (makes overwriting files safer in some cases)
    set writebackup

    # When creating a backup, make a copy of the original file, then update
    # the original (this ensures that permissions on the original file
    # remain unchanged)
    set backupcopy=yes
    ...

A: I found that neither 'nt acl support = no' nor 'map archive = no' solved the problem.  My experience has been that Samba always applies file permissions defined by 'create mask' and 'directory mask', regardless of whether saving a new or existing file.


text:
Q: Can't get sqlite database working? I have  one table working(one called DATABASE_CREATE1) and that table still works but when i try to insert data into the second table i get this error no idea how to fix it tryed for ages on how to fix it but had no luck any ideas:
06-13 23:56:21.179: E/Database(8840): android.database.sqlite.SQLiteException: table quick_mute has no column named row_id_quick_mute: , while compiling: INSERT INTO quick_mute(row_id_quick_mute, alarm_id) VALUES(?, ?);
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1149)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1569)
06-13 23:56:21.179: E/Database(8840):   at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
06-13 23:56:21.179: E/Database(8840):   at com.seanoneill.android.SilentPhone.DatabaseStore.createQuickMuteEntry(DatabaseStore.java:316)
06-13 23:56:21.179: E/Database(8840):   at com.seanoneill.android.SilentPhone.HoldsEverything$1.onClick(HoldsEverything.java:163)
06-13 23:56:21.179: E/Database(8840):   at android.view.View.performClick(View.java:2485)
06-13 23:56:21.179: E/Database(8840):   at android.view.View$PerformClick.run(View.java:9080)
06-13 23:56:21.179: E/Database(8840):   at android.os.Handler.handleCallback(Handler.java:587)
06-13 23:56:21.179: E/Database(8840):   at android.os.Handler.dispatchMessage(Handler.java:92)
06-13 23:56:21.179: E/Database(8840):   at android.os.Looper.loop(Looper.java:123)
06-13 23:56:21.179: E/Database(8840):   at android.app.ActivityThread.main(ActivityThread.java:3729)
06-13 23:56:21.179: E/Database(8840):   at java.lang.reflect.Method.invokeNative(Native Method)
06-13 23:56:21.179: E/Database(8840):   at java.lang.reflect.Method.invoke(Method.java:507)
06-13 23:56:21.179: E/Database(8840):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
06-13 23:56:21.179: E/Database(8840):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
06-13 23:56:21.179: E/Database(8840):   at dalvik.system.NativeStart.main(Native Method)

code:
private static final String DATABASE_CREATE =
    "create table " + DATABASE_TABLE_QUICK + " ("
    + kEY_ROWID_QUICK_MUTE + "text not null, "
    + END_TIME_QUICK  + " text not null,"
    + ALARM_ID_QUICK + " text not null );";

private static final String DATABASE_CREATE1=
    "create table " + DATABASE_TABLE + " ("
    + kEY_ROWID + " integer primary key autoincrement, "
    + END_KEY_TIME  + " text not null,"
    + START_TIME_12_HOUR  + " text not null,"
    + END_TIME_12_HOUR  + " text not null,"
    + COVERT_DAYS + " text not null,"
    + KEY_STATE  + " text not null,"
    + MUTE_TITLE + " text not null, "
    + ALARM_MODE + " text not null, "
    +ALARM_ID+ " text not null,"
    + START_KEY_TIME  + " text not null  );";

creating database
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DATABASE_CREATE);
    db.execSQL(DATABASE_CREATE1);
}

here is code for insert into database
public void createQuickMuteEntry(String endTime, String alarmid) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(kEY_ROWID_QUICK_MUTE, endTime ); /
    initialValues.put(ALARM_ID, alarmid);
    databaseConnect.insert(DATABASE_TABLE_QUICK, null, initialValues);
}

Insert statment
getDatabaseInfo.createQuickMuteEntry("dfdf", "dfdf");

update:
//quick mute
public static final String END_TIME_QUICK = "quick_mute_end_time";
public static final String ALARM_ID_QUICK = "quick_mute_id";
public static final String kEY_ROWID_QUICK_MUTE = "row_id_quick_mute";

A: From the error message:
SQLiteException: table quick_mute has no column named row_id_quick_mute: , while compiling: INSERT INTO quick_mute(row_id_quick_mute, alarm_id) VALUES(?, ?);

you missed out column:
row_id_quick_mute

in table
quick_mute

Upon further inspection, this is caused by faulty CREATE syntax.
Take a look at this code:
private static final String DATABASE_CREATE =
    "create table " + DATABASE_TABLE_QUICK + " ("
    + kEY_ROWID_QUICK_MUTE + "text not null, "
    + END_TIME_QUICK  + " text not null,"
    + ALARM_ID_QUICK + " text not null );";

You should notice that in this line:
+ kEY_ROWID_QUICK_MUTE + "text not null, "

the text part is right next to ", without space between it.

A: Try putting a space before text...
kEY_ROWID_QUICK_MUTE + "text not null, "

redpajama_set_name: RedPajamaStackExchange


text:
Q: Color Tint shader for vector sprite Unity 2020.2.7
Vector Graphics 2.0.0 preview 14
My shader works like this: if color alpha is 255 - I can tint any color.
If color alpha is 0 - the original color.
It works great if the .svg generated asset type is a textured sprite.
But if I switch to the generated asset type - vector sprite, my shader doesn't work. How to fix it?
Thanks
Shader "Custom/TintSprite"{ Properties
{
    [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
    _Color("Tint", Color) = (1,1,1,1)
    [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
}

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Fog { Mode Off }
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile DUMMY PIXELSNAP_ON
            #pragma multi_compile_instancing
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = UnityObjectToClipPos(IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap(OUT.vertex);
                #endif

                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                fixed4 c = tex2D(_MainTex, IN.texcoord);
                fixed a = c.a;
                if (c.a >= 0.1) {
                    c = c + (IN.color - c) * IN.color.a;
                    c.a = a;
                }
                c.rgb *= c.a;
                return c;
            }
        ENDCG
        }
    }}

https://i.stack.imgur.com/H5W6J.png
https://i.stack.imgur.com/S1wpm.png
https://i.stack.imgur.com/0coZ9.png


text:
Q: Install spark on cloudera vm I tried to install ipython 1.2.1 using this command:
sudo easy_install ipython==1.2.1

but it failed with:

No local packages or download links found for ipython==1.2.1
  error: Could not find suitable distribution for
  Requirement.parse('ipython==1.2.1')

So I tried:
$ pip install IPython==1.2.1 --user

but it failed when I tried to open spark using this command:
PYSPARK_DRIVER_PYTHON=ipython pyspark
[cloudera@localhost ~]$ PYSPARK_DRIVER_PYTHON=ipython pyspark
bash: pyspark: command not found


text:
Q: How to check that the string is email? I use the following code currently:
regexp = re.compile(r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}', re.IGNORECASE)
email = regexp.findall(stext)
if email:
    email = email[0]

But it will work even when stext contains some other text as well besides e-mail (for ex., some text email@example.com some other text). When I would like to check if stext contains email@example.com only (ok, probably with leading or/and trailing spaces, no other characters).
PS. I also think that probably I should use mail.is_email_valid instead of regex, it will allow me to support long domains like .museam or local domains like .рф.

A: You need to add ^ in the start which means "text begins here" and $ in the end which is "no more text after here".
That would give:
r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$'

A: Use this regular expression :
\s?[A-Z0-9_-+%]+@[A-Z0-9_-+%]+\.[A-Z0-9]\s?

A: Why don't you use \b for word boundary before and after the email?


text:
Q: problem when using javax.validation.Validator and others I'm trying to validate something using the GWT BeanValidation but these two lines are giving me some trouble:
Validator validator=Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Contact>> violations = validator.validate(contact, Default.class);

The thing is, I have imported the corresponding classes:
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

But still, the Validator, Validation, ConstraingViolation and Default references in the code are underlined in red and the error they show is:
javax.validation.Validator can not be found in source packages. Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly.

I have checked that the necessary lib validation-api-1.0.0.GA.jar is in the classpath and everything seems normal.
Anyone happens to know what could be the problem?
thanks!!

A: I see only two possibilities

*

*Check the size of jar file , either in your local maven repository which your build path is pointing to or check that in your eclipse by browsing its source code to double check its there :)

*Have you inherited this is any awt module using ? Can you check its syntax or if it is really required?

A: Do you have validator-implementation in your classpath? AFAIK, javax.validation is only the API (interfaces), you'll need an actual validator-implementation to use it. See for example Hibernate Validator.


text:
Q: Add Data to Core Data from Array Swift 3 If I have an array of data for instance:
let  array = ["73", "24", "12", "62", "42"]

And I would like to loop through the array and add its number to my entity called Device with attribute asset_tag and then print out the values from my core data stack.
Currently my code is as follows:
 var data: [String] = ["53","35","26","42","12"]

   let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let task = Device(context: context)

        task.asset_tag = data

        (UIApplication.shared.delegate as! AppDelegate).saveContext()

        do {
            data = try context.fetch(Device.fetchRequest())
        }

        catch {
            print ("This did not work")
        }

        print (data)

but it doesn't look like you can just add an array as the source for data into an attribute.

A: Spent some time and finally figured it out. Code is as follows:
for device in data {

            let newArray = NSEntityDescription.insertNewObject(forEntityName: "Device", into: context)

            newArray.setValue(device, forKey: "asset_tag")
        }


text:
Q: Safe shell redirection when command not found Let's say we have a text file named text (doesn't matter what it contains) in current directory, when I run the command (in Ubuntu 14.04, bash version 4.3.11):
nocommand > text # make sure noommand doesn't exists in your system

It reports a 'command not found' error and it erases the text file! I just wonder if I can avoid the clobber of the file if the command doesn't exist.
I try this command set -o noclobber but the same problem happens if I run:
nocommand >| text # make sure noommand doesn't exists in your system

It seems that bash redirects output before looking for specific command to run. Can anyone give me some advices how to avoid this?

A: Actually, the shell first looks at the redirection and creates the file. It evaluates the command after that.
Thus what happens exactly is: Because it's a > redirection, it first replaces the file with an empty file, then evaluates a command which does not exist, which produces an error message on stderr and nothing on stdout. It then stores stdout in this file (which is nothing so the file remains empty).
I agree with Nitesh that you simply need to check if the command exists first, but according to this thread, you should avoid using which. I think a good starting point would be to check at the beginning of your script that you can run all the required functions (see the thread, 3 solutions), and abort the script otherwise.

A: This would write to file only if the pipe sends at least a single character:
nocommand | (
    IFS= read -d '' -n 1 || exit
    exec >myfile
    [[ -n $REPLY ]] && echo -n "$REPLY" || printf '\x00'
    exec cat
)

Or using a function:
function protected_write {
    IFS= read -d '' -n 1 || exit
    exec >"$1"
    [[ -n $REPLY ]] && echo -n "$REPLY" || printf '\x00'
    exec cat
}

nocommand | protected_write myfile

Note that if lastpipe option is enabled, you'll have to place it on a subshell:
nocommand | ( protected_write myfile )

At your option you can also just summon subshell on the function by default:
function protected_write {
    (
        IFS= read -d '' -n 1 || exit
        exec >"$1"
        [[ -n $REPLY ]] && echo -n "$REPLY" || printf '\x00'
        exec cat
    )
}

*

*() summons a subshell. A subshell is a fork and runs on a different process space. In x | y, y is also summoned by default in a subshell unless lastpipe option (try shopt lastpipe) is enabled.

*IFS= read -d '' -n 1 waits for a single character (see help read) and would return zero code when it reads one which bypasses exit.

*exec >"$1" redirects stdout to file. This makes everything that prints to stdout print to file instead.

*Everything besides \x00 when read is stored in REPLY that is why we do printf '\x00' when REPLY has null (empty) value.

*exec cat replaces the subshell's process with cat which would send everything that it receives to the file and finish the remaining job. See help exec.

A: Write to a temporary file first, and only move it into place over the desired file if the command succeeds.
nocommand > tmp.txt && mv tmp.txt text

This avoids errors not only when nocommand doesn't exist, but also when an existing command exits before it can finish writing its output, so you don't overwrite text with incomplete data.
With a little more work, you can clean up the temp file in the event of an error.
{  nocommand > tmp.txt || { rm tmp.txt; false; } } && mv tmp.txt text

The inner command group ensures that the exit status of the outer command group is non-zero so that even if the rm succeeds, the mv command is not triggered.
A simpler command that carries the slight risk of removing the temp file when nocommand succeeds but the mv fails is
nocommand > tmp.txt && mv tmp.txt text || rm tmp.txt

A: If you do:
set -o noclobber

then
invalidcmd > myfile

if myfile exists in current path then you will get:
-bash: myfile: cannot overwrite existing file

A: Check using "which" command
#!/usr/bin/env bash

command_name="npm2" # Add your command here
command=`which $command_name`

if [ -z "$command" ]; then #if command exists go ahead with your logic
        echo "Command not found"
else # Else fallback
        echo "$command"
fi

Hope this helps


text:
Q: derive MLE for $\theta$ I want to derive the MLE for theta given this equation
$f(x,\theta) = \frac{x}{\theta} \exp \left( - \frac{x^2}{2 \theta} \right)$
do i first take the log and then the derivative of theta?? I think im supposed to get something like this:
$\frac{x^{2}-2\theta}{2\theta^{2}}$

A: Usually the MLE is based on a random sample, i.e. $X_1,...,X_n$
Thus the loglikelihood is
$$l(\theta)=-nlog\theta-\frac{1}{2\theta}\Sigma_x x^2$$
derive respect to $\theta$, set =0, solve in $\theta$ getting
$$\hat{\theta}=\frac{\Sigma_x x^2}{2n}$$


text:
Q: My app closes when screen turns off I got a problem with my app when the screen turns off (because of system screen timeout) my application finishes.
I search but didn't find something helpful.
Is it a common problem or does it have a fix?

A: you shud not call finish() in onPause. it could be called for variety of reasons(check doc.). why you want to kill your activity when user switches app? its not recommended.
here are some posts, but there is no api available to detect app going in background.
How to detect when an Android app goes to the background and come back to the foreground
http://nathanael.hevenet.com/android-dev-detecting-when-your-app-is-in-the-background-across-activities/

A:
I want when the user leaves this activity to finish but not the screen thnx

Take finish() out of onPause(). Put it wherever the user leaves the Activity. So, assuming you have code that starts a new Activity, put finish() after startActivity().
You also could use the flag android:noHistory in your <activity> tag of your maifest.xml so that the Activity is removed from the stack whenever it starts a new Activity. Both of these methods do the same job it just depends on how you want/need to implement it.
The reason it closes when the screen turns off is because your app calls onPause() at that time so removing the call from that method would keep it from closing when the screen turns off.


text:
Q: what is the meaning of a double pointer of struct in C I have a problem understanding this structure , would love to get a clear explanation.
typedef struct exp{
   int x;
   struct exp *parent;
   struct exp **children;
}

what does it mean the parent and the children ?
"parent" is an array of this structure?
and what is the meaning of the children ? it's an array of arrays?!
I really can't understand..
and last thing, If I'm adding an element , it becomes a specific child of some parent, how can I reach all the children of a parent? shouldn't it be a structure "List" (using next etc .. ? )?
thank you!!

A: This image shows a possible scenario:

It was obtained using this code and DDD
#include <stdio.h>
#include <stdlib.h>

struct exp{
    int x;
    struct exp *parent;
    struct exp **children;
};

int main ()
{
    struct exp *x = calloc(1, sizeof(x[0]));
    x->x = 42;
    x->parent = calloc(1, sizeof(x[0]));
    x->children = calloc(5, sizeof(x->children[0]));
    x->children[0] = calloc(1, sizeof(x[0]));
    x->children[2] = calloc(1, sizeof(x[0]));
    x->children[3] = calloc(1, sizeof(x[0]));
    x->children[4] = calloc(1, sizeof(x[0]));
    return 0;
}

Basically, the children field is a vector of pointers to struct exp. You decide how many  elements to put there and the other things.
PS: Code is only a demo, it has not quite a good quality.

A: It's a pointer to a pointer, which in that case seems to be used as a list of struct exp.
Each struct exp has a reference to it's "parent", and a pointer to a list of children struct exp.
typedef struct exp{
    int x;
    struct exp *parent;
    struct exp **children;
} element;

// create ROOT elemnt
element * root = (element*) malloc(sizeof(element)); //alocate mem. for 1 element

Once we have a "root" we can add children, following is pseudo-code
for 1 to 10{
    child = new element;
    child->parent = root;                // tell the child who is his parent
    addToRoot( root , child);            // call a function that inserts elemnts to root

}

So now we should have root with a list of 10 elements:
_______________                                    _______________
|             | (children)                         |             | - (parent) points to struct exp, root
|     root    | - points to list of struct exp  -> |   child 0   |
|             |                                    |             | - (children) points to null; // if it's empty
_______________                                    _______________

                                                   _______________
                                                   |             | - (parent) points to struct exp, root
                                                   |   child 1   |
                                                   |             | - (children) points to null; // if it's empty
                                                   _______________

                                                   _______________
                                                   |             | - (parent) points to struct exp, root
                                                   |   child 2   |
                                                   |             | - (children) points to null; // if it's empty
                                                   _______________

                                                   _______________
                                                   |             | - (parent) points to struct exp, root
                                                   |   child 3   |
                                                   |             | - (children) points to null; // if it's empty
                                                   _______________

                                                         .
                                                         .
                                                         .

                                                   _______________
                                                   |             | - (parent) points to struct exp, root
                                                   |   child 9   |
                                                   |             | - (children) points to null; // if it's empty
                                                   _______________

Something like that... Did it help?

A: It's an array of pointers to child nodes- this looks like some kind of tree structure.
There is a parent node for each node, and each node has one or more children. You can travel from a parent to one of its children with
expInstance->children[i];

Where i is a number indicating one of the child nodes.  It's not really clear how many child nodes there are from this definition- it could be one, or two, or a million.  But given that information you could loop through them.  Either with
for(i=0; i<NUMBER_OF_CHILDREN_NODES;i++){
    expInstance->children[i];
}

if you know the length of the array in advance or the somewhat strange
while(expInstance.children[i++]){
    expInstance->children[i];
}

(There are a couple variously clever ways to do this, but there has to be the assumption built into the structure that there will be a null pointer in the last slot of this array in order to terminate it.)

A: It is hard to say without seeing more code. Are you trying to implement a tree? From this definition, this is what apparent to me:

*

*parent points to the parent node of this structure.

*children points to the array of pointers of all its child nodes.

A: First of all, remember that a structure cannot contain an instance of itself.  IOW, you cannot do something like
struct exp {
  int x;
  struct exp parent;
  ...
};

The main reason for this is that the struct type is not complete at the point where you try to declare the parent member; since you haven't finished describing the type yet, the compiler doesn't know how big the parent member should be.  Not to mention that the parent member would itself have a parent member of type struct exp, which would in turn have a parent member of type struct exp, which would in turn have a parent member of type struct exp, etc., etc., etc., etc.  You'd wind up with an object that required an infinite amount of storage.
So you cannot have a member of type struct exp.  However, you can have a pointer to an object of type struct exp; you can create pointers to incomplete types, and all struct pointer types have the same size and representation (IOW, struct foo *pf and struct bar *pb will have the same size, even if struct foo and struct bar do not).
So the parent member is (probably) only meant to point to a single instance of type struct exp (each instance of struct exp has one parent).  Likewise the children member is (probably) meant to be a single-dimensioned array of pointers to struct exp (each instance of atruct exp can have zero, one, or more children).


text:
Q: Parameterization of exponential family Let $\{\mathbb{P}_{\theta}\}_{\theta}$ be an exponential family of probability measures, all with finite mean.  Under what conditions is the parameterization map $\theta\mapsto \mathbb{P}_{\theta}$ continuous with respect to the Wasserstein-$1$ distance?

A: $\newcommand\om\omega\newcommand\Om\Omega\newcommand\ep\epsilon\newcommand\R{\mathbb R}$Let $(P_t)_{t\in T}$ be an exponential family over a separable complete metric space $(X,d)$, where $T$ is an open subset of $\mathbb R^k$ and $t=(t_1,\dots,t_k)$ is a natural parameter. So, for all $t\in T$, the density $p_t$ of $P_t$ with respect to Borel measure $\mu$ on $X$ is given by the formula
\begin{equation*}
    p_t(x)=c(t)\exp\{t\cdot U(x)\}\tag{1}
\end{equation*}
for all $x\in X$, where
$U\colon X\to\mathbb R^k$ is a Borel-measurable function, $\cdot$ denotes the dot product on $\mathbb R^k$,
\begin{equation*}
    c(t):=1/I(t),\quad I(t):=\int_X\mu(dx)\exp\{t\cdot U(x)\}\in(0,\infty). \tag{2}
\end{equation*}
Assume that, for some (and hence for all) $x_0\in X$, the "first moment"
\begin{equation}
    m_t(x_0):=\int_X P_t(dx)d(x_0,x)=\int_X \mu(dx)p_t(x)d(x_0,x)<\infty\tag{2a}
\end{equation}
for all $t\in T$.
Then the parameterization map $U\ni t\mapsto P_t$ is continuous with respect to the Wasserstein-1 distance $W_1$.
Indeed, by the penultimate paragraph of the introduction section, if suffices to show that for each $t\in T$
\begin{equation*}
    \int_X \mu(dx)p_s(x)f(x)\to \int_X \mu(dx)p_t(x)f(x)\tag{3}
\end{equation*}
as $s\to t$, where $f\colon X\to\mathbb R$ such that
\begin{equation*}
C:=\sup_{x\in X}|f(x)|/(1+d(x_0,x))<\infty  \tag{3a}
\end{equation*}
(for some (and hence for all) $x_0\in X$).
To verify (3), take any $t=(t_1,\dots,t_k)$ in the open set $T$. Take any real $\ep>0$ such that $t+\ep\om\in T$ for all $\om=(\om_1,\dots,\om_k)\in\Om:=\{-1,1\}^k$.
Take then any $s\in T$ such that $\max_{j=1}^k|s_j- t_j|\le\ep$ and any $u\in\R^k$. Then
\begin{align*}\exp\{s\cdot u\}/\exp\{t\cdot u\}&=\exp\{(s-t)\cdot u\} \\
&\le\max_{\om\in\Om}\exp\{\ep\om\cdot u\} \\
&\le\sum_{\om\in\Om}\exp\{\ep\om\cdot u\};
\end{align*}
the first inequality in the above display follows because the function $\exp$ is convex and the condition $\max_{j=1}^k|s_j- t_j|\le\ep$ implies that the point $s-t$ is in the convex hull of the set $\{\ep\om\colon\om\in\Om\}$. So, for all $x\in X$
\begin{equation*}
    \exp\{s\cdot U(x)\}\le g(x):=\sum_{\om\in\Om}\exp\{( t+\ep\om)\cdot U(x)\}. \tag{5}
\end{equation*}
Moreover, by (2),
\begin{equation*}
 \int_X\mu(dx)g(x)=\sum_{\om\in\Om}I(t+\ep\om)<\infty.
\end{equation*}
So, by the dominated convergence theorem, $I(s)\to I(t)$ and hence $c(s)\to c(t)$ as $s\to t$. So, choosing $\ep$ small enough, we have
\begin{equation*}
    c(s)\le 2c(t). \tag{6}
\end{equation*}
In view of (1) and (6), inequality (5) yields
\begin{equation*}
    p_s(x)\le c(s)\sum_{\om\in\Om}\frac{p_{t+\ep\om}(x)}{c(t+\ep\om)}
    \le K\sum_{\om\in\Om}p_{t+\ep\om}(x),
\end{equation*}
where
\begin{equation*}
    K:=2c(t)\max_{\om\in\Om}\frac1{c(t+\ep\om)}<\infty.
\end{equation*}
So, by (3a),
\begin{equation*}
    p_s(x)|f(x)|\le h(x):=KC\sum_{\om\in\Om}p_{t+\ep\om}(x)(1+d(x_0,x)).
\end{equation*}
Moreover, by (2a),
\begin{equation*}
    \int_X \mu(dx)h(x)=KC\sum_{\om\in\Om}(1+m_{t+\ep\om}(x_0))<\infty.
\end{equation*}
So, again by the the dominated convergence theorem, (3) follows. $\Box$


text:
Q: Animated splash screen in C# How can I have a Animated splash screen in C#
But I could still make a splash (Fixed)
private void SplashScreen()
{
    Application.Run(new Splash());
}

A: A few steps for WPF:
add a new window to your project and call it splash.
in the app.xaml remove the startupwindow, and register an event for startup.
in the app.xaml.cs add the following code.
    private void App_OnStartup(object sender, StartupEventArgs e)
    {
        var splash = new Splash();
        var mainwindow = new MainWindow();
        splash.ShowDialog();
        mainwindow.Show();
    }

Now the first window splash is opened and in that window you can do some animations.
After that window is closed (by the user or by using a timer and calling the close method.) the mainwindow will open.
A few notes you will have to set various properties in the splash window.
TopMost = true
StartupLocation = CenterScreen
WindowStyle = none
Play around with that window to get the desired effects.


text:
Q: Finding an object deep in a nested json object I have the nested json object in the snippet below and want to find all occurrences of '$schema' and save the whole object that contains that schema value into another object. I tried using lodash filter but, was unsuccessful. Does anyone have any recommendations.

{
  "element": "parseResult",
  "content": [
    {
      "element": "category",
      "meta": {
        "classes": [
          "api"
        ],
        "title": "Test"
      },
      "attributes": {
        "meta": [
          {
            "element": "member",
            "meta": {
              "classes": [
                "user"
              ]
            },
            "content": {
              "key": {
                "element": "string",
                "content": "FORMAT"
              },
              "value": {
                "element": "string",
                "content": "1A"
              }
            }
          }
        ]
      },
      "content": [
        {
          "element": "category",
          "meta": {
            "classes": [
              "resourceGroup"
            ],
            "title": "Questions"
          },
          "content": [
            {
              "element": "resource",
              "meta": {
                "title": "Questions"
              },
              "attributes": {
                "href": "/questions"
              },
              "content": [
                {
                  "element": "transition",
                  "meta": {
                    "title": "List All Questions"
                  },
                  "content": [
                    {
                      "element": "httpTransaction",
                      "content": [
                        {
                          "element": "httpRequest",
                          "attributes": {
                            "method": "GET"
                          },
                          "content": []
                        },
                        {
                          "element": "httpResponse",
                          "attributes": {
                            "statusCode": "200",
                            "headers": {
                              "element": "httpHeaders",
                              "content": [
                                {
                                  "element": "member",
                                  "content": {
                                    "key": {
                                      "element": "string",
                                      "content": "Content-Type"
                                    },
                                    "value": {
                                      "element": "string",
                                      "content": "application/json"
                                    }
                                  }
                                }
                              ]
                            }
                          },
                          "content": [
                            {
                              "element": "dataStructure",
                              "content": [
                                {
                                  "element": "Question List"
                                }
                              ]
                            },
                            {
                              "element": "asset",
                              "meta": {
                                "classes": [
                                  "messageBody"
                                ]
                              },
                              "attributes": {
                                "contentType": "application/json"
                              },
                              "content": "[\n  {\n    \"question\": \"Favourite programming language?\",\n    \"published_at\": \"2014-11-11T08:40:51.620Z\",\n    \"url\": \"/questions/1\",\n    \"choices\": [\n      {\n        \"choice\": \"Javascript\",\n        \"url\": \"/questions/1/choices/1\",\n        \"votes\": 2048\n      }\n    ]\n  }\n]"
                            },
                            {
                              "element": "asset",
                              "meta": {
                                "classes": [
                                  "messageBodySchema"
                                ]
                              },
                              "attributes": {
                                "contentType": "application/schema+json"
                              },
                              "content": "{\n  \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n  \"type\": \"array\"\n}"
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            },
            {
              "element": "resource",
              "meta": {
                "title": "Question"
              },
              "attributes": {
                "href": "/questions/{id}",
                "hrefVariables": {
                  "element": "hrefVariables",
                  "content": [
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "id"
                        },
                        "value": {
                          "element": "number",
                          "content": 1234
                        }
                      }
                    }
                  ]
                }
              },
              "content": [
                {
                  "element": "transition",
                  "meta": {
                    "title": "Retrieve Question"
                  },
                  "content": [
                    {
                      "element": "httpTransaction",
                      "content": [
                        {
                          "element": "httpRequest",
                          "attributes": {
                            "method": "GET"
                          },
                          "content": []
                        },
                        {
                          "element": "httpResponse",
                          "attributes": {
                            "statusCode": "200",
                            "headers": {
                              "element": "httpHeaders",
                              "content": [
                                {
                                  "element": "member",
                                  "content": {
                                    "key": {
                                      "element": "string",
                                      "content": "Content-Type"
                                    },
                                    "value": {
                                      "element": "string",
                                      "content": "application/json"
                                    }
                                  }
                                }
                              ]
                            }
                          },
                          "content": [
                            {
                              "element": "dataStructure",
                              "content": [
                                {
                                  "element": "Question"
                                }
                              ]
                            },
                            {
                              "element": "asset",
                              "meta": {
                                "classes": [
                                  "messageBody"
                                ]
                              },
                              "attributes": {
                                "contentType": "application/json"
                              },
                              "content": "{\n  \"question\": \"Favourite programming language?\",\n  \"published_at\": \"2014-11-11T08:40:51.620Z\",\n  \"url\": \"/questions/1\",\n  \"choices\": [\n    {\n      \"choice\": \"Javascript\",\n      \"url\": \"/questions/1/choices/1\",\n      \"votes\": 2048\n    }\n  ]\n}"
                            },
                            {
                              "element": "asset",
                              "meta": {
                                "classes": [
                                  "messageBodySchema"
                                ]
                              },
                              "attributes": {
                                "contentType": "application/schema+json"
                              },
                              "content": "{\n  \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n  \"type\": \"object\",\n  \"properties\": {\n    \"question\": {\n      \"type\": \"string\"\n    },\n    \"published_at\": {\n      \"type\": \"string\"\n    },\n    \"url\": {\n      \"type\": \"string\"\n    },\n    \"choices\": {\n      \"type\": \"array\"\n    }\n  },\n  \"required\": [\n    \"question\",\n    \"published_at\",\n    \"url\",\n    \"choices\"\n  ]\n}"
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        },
        {
          "element": "category",
          "meta": {
            "classes": [
              "dataStructures"
            ]
          },
          "content": [
            {
              "element": "dataStructure",
              "content": [
                {
                  "element": "object",
                  "meta": {
                    "id": "Question"
                  },
                  "content": [
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "question"
                        },
                        "value": {
                          "element": "string",
                          "content": "Favourite programming language?"
                        }
                      }
                    },
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "published_at"
                        },
                        "value": {
                          "element": "string",
                          "content": "2014-11-11T08:40:51.620Z"
                        }
                      }
                    },
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "url"
                        },
                        "value": {
                          "element": "string",
                          "content": "/questions/1"
                        }
                      }
                    },
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "choices"
                        },
                        "value": {
                          "element": "array",
                          "content": [
                            {
                              "element": "Choice"
                            }
                          ]
                        }
                      }
                    }
                  ]
                }
              ]
            },
            {
              "element": "dataStructure",
              "content": [
                {
                  "element": "object",
                  "meta": {
                    "id": "Choice"
                  },
                  "content": [
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "choice"
                        },
                        "value": {
                          "element": "string",
                          "content": "Javascript"
                        }
                      }
                    },
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "url"
                        },
                        "value": {
                          "element": "string",
                          "content": "/questions/1/choices/1"
                        }
                      }
                    },
                    {
                      "element": "member",
                      "attributes": {
                        "typeAttributes": [
                          "required"
                        ]
                      },
                      "content": {
                        "key": {
                          "element": "string",
                          "content": "votes"
                        },
                        "value": {
                          "element": "number",
                          "content": 2048
                        }
                      }
                    }
                  ]
                }
              ]
            },
            {
              "element": "dataStructure",
              "content": [
                {
                  "element": "array",
                  "meta": {
                    "id": "Question List"
                  },
                  "content": [
                    {
                      "element": "Question"
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

I tried this as a solution.
function getObject(theObject) {
        var result = null;
        if(theObject instanceof Array) {
            for(var i = 0; i < theObject.length; i++) {
                result = getObject(theObject[i]);
            }
        }
        else
        {
            for(var prop in theObject) {
                console.log(prop + ': ' + theObject[prop]);
                if(prop == '$schema') {
                    if(theObject[prop] == 'http://json-schema.org/draft-04/schema#') {
                        return theObject;
                    }
                }
                if(theObject[prop] instanceof Object || theObject[prop] instanceof Array)
                    result = getObject(theObject[prop]);
            }
        }
        return result;
    }

    var result = getObject(json);

A: Jacob,
The problem is in your JSON itself. Your json is a key/value pair.  Keys can be strings (surrounded with "quotes") to enable properties that have spaces or special characters. e.g.
var obj = { "my property": "my value" };
var val = obj["my property"] // "my value";

However your values should only have quotes around them if they are strings, otherwise it won't get parsed to an object - it will remain in string representation.
var obj = { "foo" : "{ \"bar\" : \"my value\" }" } // notice I had to escape the strings with backslashes \
var val = obj.foo.bar // error because foo is a string with the value "{ "bar" : "my value" }"

In your json, the value of the content property is a string:
"content": "{\n  \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n  \"type\": \"array\"\n}"

The fact that you needed to escape your quotes with \ tells you this as well.  If you expect the content to be parsed the first time, then it should look something like this:
"content": { "$schema": "http://json-schema.org/draft-04/schema#", "type": "array" }

If you can't change this, then you can call an eval() or a JSON.parse() on the content to parse the string to an object (this can be unsafe if your content is coming from the users).
Edit:
Because you cannot change the JSON coming in, I created a function called deepParseObject.  It's by no means error-proof, but I think it will work for your situation:
function deepParseObject(theObject) {
  for(var prop in theObject) {
      if(typeof theObject[prop] === "string" && (theObject[prop].indexOf('{') == 0 || theObject[prop].indexOf('[') == 0)) {
          theObject[prop] = JSON.parse(theObject[prop]);
      }
      if(theObject[prop] instanceof Object || theObject[prop] instanceof Array)
          deepParseObject(theObject[prop]);
  }
}

What it does is parse the content properties if their values are strings and start with a { or [.  After that you can call my original getObject function.  Here is the plunker.
https://plnkr.co/edit/h06wuAxZkxhwCAho3OK6
I call deepParseObject in the data.js and I'm only using AngularJS to output the results... and because I like Angular :).


text:
Q: Why is ESP masked with 0xFFFFFFF0? I have disassembled a program. I see at the beginning an AND instruction with ESP and 0xFFFFFFF0.
What is the meaning of this mask? Is it an alignment problem?
It is an ELF executable for 32bit x86.

A: gcc for i386 Linux defaults to -mpreferred-stack-boundary=4 (meaning 24 = 16 byte alignment).  (Other non-Linux systems also use ELF executables, but they also have the same stack-alignment defaults and SysV ABI.)
Unlike clang, gcc doesn't assume that the stack will be aligned on entry to main, so it uses an AND instruction to mask off the low bits of the stack pointer.  This is the cheapest way to reserve enough padding on the stack to reach the next alignment boundary.
Stack alignment is the same reason you'll see a function that calls another function reserve some space on the stack that it doesn't use for anything:
extern int bar(void);
int foo(int x) { return x+bar(); }

  gcc 5.3 -O3
    sub     esp, 12                   # align the stack for another call
    call    bar
    add     eax, DWORD PTR [esp+16]   # add our arg (from the stack) to bar()'s return value (in eax)
    add     esp, 12
    ret

See this on the Godbolt compiler explorer, where you can try different compilers and options.
-mincoming-stack-boundary=3 (or less) causes the stack-alignment boilerplate to be added to every function (not just main).  -mstackrealign and -mno-stackrealign has no effect on foo() or main(), with or without a small -mincoming-stack-boundary.  Based on the documentation in the gcc manual, I thought it would enable or disable the alignment stuff for functions other than main, or for main.

The 32bit x86 SysV ABI used to only guarantee 4-byte stack alignment, but the calling convention now guarantees 16-byte alignment of %esp before a call instruction.

Section 2.2.2 The Stack Frame
... In other words, the value (%esp + 4) is always
  a multiple of 16 when control is transferred to the function entry point.   (32 when a 32-byte ymm vector is passed by value)

So gcc's -mpreferred-stack-boundary=4 is not just a good idea, it's the law (on systems like Linux where the updated ABI version that includes this stronger guarantee is the official standard).  This makes it safe for functions other than main to omit that alignment step before using aligned SSE stores/loads to the stack.  Those instructions (like movaps) will fault on unaligned addresses.  So alignment is required for correctness, not just performance.

The AND instruction isn't actually needed these days
The current version of the 32bit ABI does guarantee that a freshly-execveed 32bit process will start with %esp 16-byte aligned.  (Section 2.3.1 Initial Stack and Register State, see the bullet point about the initial state of %esp itself, not the stack contents.)
This means that gcc's behaviour of aligning the stack at the start of main is now obsolete, assuming the CRT startup code that calls main doesn't misalign the stack.
clang does assume the stack is aligned at the start of main, like 64bit gcc does.
16B-alignment was part of the x86-64 SysV ABI from the start, not added later, so it was always a safe assumption and there are no old kernels that don't provide that at process startup.
The x86 tag wiki has links to other ABIs, and much more.


text:
Q: Create a file in every folder in a directory I have a directory with hundreds of folders and subfolders and subfolders within subfolders (in windows).
I'm just trying to create a small txt file with the word "test" in all of these folders.
I've tried something like this but can't get it to work properly:
for i in root_dir:
    filename = "test.txt"
    with open(filename, "w") as f:
        f.write("Test")

attempt2
#only makes one file in the root directory - no sub directories though
import os

root_path8 = r'C:\Users\max\Downloads\users_visual\mgr8\mgr7\mgr6'

for i in next(os.walk(root_path8))[1]:
#         print(j)
    print(i)
    root_dir = root_path8
    filename = "test.txt"
    filepath = os.path.join(root_dir, filename)
    if not os.path.exists(root_dir):
        os.makedirs(root_dir)
    f = open(filepath, "a")
    f.write("Test")
    f.close()

A: Use walk to get all subfolders and sub-subfolders etc. within your directory. This iteration returns 3 values (current folder, subfolders, files); pass the first value to open, using os.path.join to concatenate the folder name and the file name. E.g.
import os
folder_iter = os.walk(root_dir)
for current_folder, _, _ in folder_iter:
    filename = "test.txt"
    with open(os.path.join(current_folder, filename), "w") as f:
        f.write("Test")

BTW if it's the same file in every case, i.e. you don't need to CREATE each file separately, probably a more efficient way would be to create one file to begin with and then copy it to each folder in the iteration.


text:
Q: How to efficiently find correlation and discard points outside 3-sigma range in MATLAB? I have a data file m.txt that looks something like this (with a lot more points):
286.842995
3.444398
3.707202
338.227797
3.597597
283.740414
3.514729
3.512116
3.744235
3.365461
3.384880

Some of the values (like 338.227797) are very different from the values I generally expect (smaller numbers).

*

*So, I am thinking that
I will remove all the points that lie outside the 3-sigma range. How can I do that in MATLAB?

*Also, the bigger problem is that this file has a separate file t.txt associated with it which stores the corresponding time values for these numbers. So, I'll have to remove the corresponding time values from the t.txt file also.
I am still learning MATLAB, and I know there would be some good way of doing this (better than storing indices of the elements that were removed from m.txt and then removing those elements from the t.txt file)

A: @Amro is close, but the FIND is unnecessary (look up logical subscripting) and you need to include the mean for a true +/-3 sigma range. I would go with the following:
%# load files
m = load('m.txt');
t = load('t.txt');

%# find values within range
z = 3;
meanM = mean(m);
sigmaM = std(m);
I = abs(m - meanM) <= z * sigmaM;

%# keep values within range
m = m(I);
t = t(I);

A: %# load files
m = load('m.txt');
t = load('t.txt');

%# find outliers indices
z = 3;
idx = find( abs(m-mean(m)) > z*std(m) );

%# remove them from both data and time values
m(idx) = [];
t(idx) = [];


text:
Q: Error Code: 1824. Failed to open the referenced table 'receitas'. FK referencia tabela ainda não criada No meu banco de dados, tenho duas tabelas, Usuários e Receitas, e cada uma tem um FK da outra tabela, como a seguir
    CREATE TABLE Usuarios (
  idUsuario INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  Nome VARCHAR(255) NOT NULL,
  NomeTag VARCHAR(255) NOT NULL,
  Email VARCHAR(255) NOT NULL,
  Senha INTEGER UNSIGNED NOT NULL,
  Categorias_id INTEGER UNSIGNED NOT NULL,
  Foto BLOB NULL,
  Receitas_id INTEGER UNSIGNED NULL,
  PRIMARY KEY(idUsuario),
  FOREIGN KEY (Categorias_id) REFERENCES Categorias(idCategoria),
  FOREIGN KEY (Receitas_id) REFERENCES Receitas(idReceitas)
);

    CREATE TABLE Receitas (
  idReceita INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  Foto BLOB NOT NULL,
  Nome INTEGER UNSIGNED NOT NULL,
  Categorias_id INTEGER UNSIGNED NOT NULL,
  TempoPreparo INTEGER UNSIGNED NOT NULL,
  Porcoes INTEGER UNSIGNED NOT NULL,
  ValCaolorico VARCHAR(255) NULL,
  Passo LONGTEXT NOT NULL,
  Descricao VARCHAR(255) NOT NULL,
  Usuario_id INTEGER UNSIGNED NOT NULL,
  Ingredientes_id INTEGER UNSIGNED NOT NULL,
  Categoria_id INTEGER UNSIGNED NULL,
  Avaliacao_id INTEGER UNSIGNED NULL,
  Aproveitamento BOOL NULL,
  PRIMARY KEY(idReceita),
  FOREIGN KEY (Usuario_id) REFERENCES Usuarios(idUsuario),
  FOREIGN KEY (Ingredientes_id) REFERENCES Ingredientes(idIngredientes),
  FOREIGN KEY (Categoria_id) REFERENCES Categorias(idCategoria),
  FOREIGN KEY (Avaliacao_id) REFERENCES Avaliacoes(idAvaliacao)
  );

Mas ao execultar, ocorre um erro, pois uma tabela que esta sendo refenciada ainda não existe


text:
Q: Ubuntu 20.04 Booting Problem Due to some reasons, I've installed Windows 10 on hdd, while Ubuntu was already installed on ssd. Most of the time, I use Ubuntu but when I start my system, Windows is booted every time unless I press F9 and select Ubuntu from the boot menu. It's very annoying to open the boot menu every time I run my laptop. How can I set Ubuntu as the default OS?
Note: I've tried to set Ubuntu as the default OS in Startup and Recovery (Windows) and Grub Customizer (Ubuntu). These solutions didn't work for me.
Thank you!


text:
Q: Android, show dialog when ListPreference item is clicked Basically I have a ListPreference to allow a user to change the X position of some text on my Live Wallpaper.
It contains 4 entries: top, middle, bottom and manually input X. The first 3 options are no problem, I simply get the SharedPreferences in my WallpaperService class and check if they are top, middle or bottom and change the position corresponding to their choice.
However, the last option is proving more difficult, what I want to do is have an EditText alert box popup when the user clicks the "Manually input X" ListPreference item so they can enter a value for X. I just cant figure out how to make the alert popup from clicking that specific List element.

A: You probably want to create a custom ListPreference. Basically you want to extend from ListPreference (see original here), and provide a custom protected void onPrepareDialogBuilder(Builder builder), in which you provide the additional "custom" list item and the onclick to handle the selection of the "custom" entry.
Note that I keep saying "custom" because it would be a best practice to make this class as reusable as possible.

A: Override onPreferenceTreeClick() in your PreferenceActivity and compare the preference it gives to the one you want to do something for.


text:
Q: How to use Filename, modify date and publish date as a quick part in word app we want to insert filename, modify date and publish date in a word document template as quick part connected to sharepoint. These values should populate from sharepoint. For example when document name is changed, we should see new document name inside. We use office 365 solution.
May you help?
Thanks!

A: I think for this you should create a custom document template in SharePoint document library, in order to that follow the below steps:

*

*Navigate to the site where you want to create your library.

*Select Settings Gear shaped settings button , and then select Add an
App.

*Select Document Library.

*Select Advanced Options.

*Add a name, optional description, versioning, and if applicable,
whether you want the library to receive email.

*Select the default application file format and version from the
Document Template dropdown.

*Click Create.

Customize the default template for a document library
To customize the default template, follow these steps. There are two ways you can change the default template:

*

*If your document or form library has a default file template for a
program compatible with SharePoint, then you can edit the default
template.

*For other programs, you cannot directly edit the default template,
but you can copy a new template file to the Forms folder of the
library to specify a custom template.

Edit the default file template

*Navigate to the site where your library is located.

*In SharePoint Server, on the ribbon, select the Library tab, then select Library Settings.

*For SharePoint Online, select Settings Gear shaped settings button ,
and then select Library settings.

*Under General Settings, select Advanced settings.

*In the Document Template section, under the Template URL field,
select Edit Template. One of the following happens:

*If your site is a part of an Office 365 subscription, at this point,
you may be prompted to enter your Office 365 subscription username and password.

*Document library    The template opens in an app that is compatible
with SharePoint and that is associated with the file type of the
current template. For example, Word opens if the default template is
a Word template, or Excel opens if the default template is an Excel
worksheet.

*Form library    The template opens either in a program compatible
with SharePoint, either an XML-based form design program, such as
InfoPath, or an XML editor.

*Make the changes that you want, and then save the template. For
 SharePoint Online, save the template with a new filename. Close the program if you no longer need it open, or switch to your site.

*Depending on your form design program, you may need to republish
 the template to the library on your site from your program.

*In your site, at the bottom of the Document or Form Library
 Advanced Settings page, and select OK.
For details refer to the below MSDN article:
Set a custom template for a SharePoint library


text:
Q: JavaScript Errors After Changing Servers (Wordpress) I moved a Wordpress site to a new server.  I did this by directly copying the folder to the new server.  The web server is IIS 10.0 and the PHP version is 7.4.13.  When editing a Post, I noticed that I wasn't able to add an image from the Gallery.  I also a weird JavaScript error, which doesn't happen on the old server.  The error relates to thickbox.js:

The error in the console is
Uncaught SyntaxError: missing ) after argument list

The strange thing is that the original file doesn't contain &quot:

I've compared the IIS configurations and I don't see any difference.  Nothing else has changed, the wp-config.php file is the same as is the database.  Has anyone else experienced a similar issue?
I came across this question, however this relates to the content of the post - which isn't my issue.
Update 2021/08/19
Something that I didn't think could have caused this issue was a Cloudflare Worker active on the route.  Initially this was just to perform 301 redirects based on url's stored in KV.  Following the server change, I added some code to update some old url's and ensure https was used.  When I removed the Worker, the JavaScript errors disappeared.  I then tracked the issue to the HTMLRewriter I was using (code is below).  I just not sure why the replace method is causing the issue?
class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName
  }

  element(element) {
    const attribute = element.getAttribute(this.attributeName)

    if (attribute) {
      let newValue = attribute.replace(new RegExp(blogOriginUrl, 'g'), blogPublicUrl).replace(new RegExp(csOriginUrl, 'g'), csPublicUrl).replace(new RegExp(httpUrl, 'g'), httpsUrl)

      element.setAttribute(this.attributeName, newValue)
    }
  }
}

const urlRewriter = new HTMLRewriter().on('a', new AttributeRewriter('href')).on('img', new AttributeRewriter('src')).on('img', new AttributeRewriter('srcset'))

A: The problem is that your worker is using HTMLRewriter to rewrite resources that are not actually HTML. In this case, it is rewriting a JavaScript file. HTMLRewriter assumes whatever input you give it is HTML, and attempts to parse it as such. Here, it has seen the <img> tag appearing in your JavaScript, and it thinks that's an HTML tag. It has parsed the tag, then written it out again in a slightly different way, which is valid for HTML but not correct for JavaScript.
In your worker, you need to make sure that you only apply HTMLRewriter to responses that are actually HTML, based on Content-Type. Like:
if (response.headers.get("Content-Type").startsWith("text/html")) {
  // apply HTMLRewriter here
}


text:
Q: Can't indexing an array without using another var I think is something that I miss theoretically from the passing by reference topic but I can't find a way to read the ID without using the support networkInterfaceReference
package main

import (
    "context"
    "fmt"

    "github.com/Azure/azure-sdk-for-go/profiles/preview/resources/mgmt/resources"
    "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-03-01/compute"
    "github.com/Azure/azure-sdk-for-go/services/subscription/mgmt/2020-09-01/subscription"
    "github.com/Azure/go-autorest/autorest/azure/auth"
    "github.com/ktr0731/go-fuzzyfinder"
)

var selectedSub subscription.Model
var selectedRG resources.Group
var selectedVM compute.VirtualMachine

func main() {
    selectedSub = GetSubscription()
    selectedRG = GetResourceGroup()
    selectedVM = GetVM()

    fmt.Printf("Sub: %s\nRG: %s\nVM: %s\n", *selectedSub.DisplayName, *selectedRG.Name, *selectedVM.Name)

    // THIS WORK
    networkInterfaceReference := *selectedVM.NetworkProfile.NetworkInterfaces
    fmt.Printf("%s", *networkInterfaceReference[0].ID)

    // THIS DOESN'T WORK
    fmt.Printf("%s", *selectedVM.NetworkProfile.NetworkInterfaces[0].ID)
}

...
...
...

func GetVM() compute.VirtualMachine {
    vmClient := compute.NewVirtualMachinesClient(*selectedSub.SubscriptionID)
    authorizer, err := auth.NewAuthorizerFromCLI()
    if err == nil {
        vmClient.Authorizer = authorizer
    }
    vmList, err := vmClient.List(context.TODO(), *selectedRG.Name)
    if err != nil {
        panic(err)
    }

    idx, err := fuzzyfinder.Find(vmList.Values(), func(i int) string {
        return *vmList.Values()[i].Name
    })
    if err != nil {
        panic(err)
    }

    return vmList.Values()[idx]
}

Hovering to the error showed the following error message:
field NetworkProfile *[]compute.NetworkProfile
(compute.VirtualMachineProperties).NetworkProfile on pkg.go.dev

NetworkProfile - Specifies the network interfaces of the virtual machine.

invalid operation: cannot index selectedVM.NetworkProfile.NetworkInterfaces (variable of type *[]compute.NetworkInterfaceReference)compiler (NonIndexableOperand)

A: If you want the 2nd way to work:
// WORKS
networkInterfaceReference := *selectedVM.NetworkProfile.NetworkInterfaces
fmt.Printf("%s", *networkInterfaceReference[0].ID)

// THIS DOESN'T WORK
fmt.Printf("%s", *selectedVM.NetworkProfile.NetworkInterfaces[0].ID)

studying the compilation error you are getting (P.S. please don't post screen-shots of code/errors) - the error is failing because you are trying to index a pointer which is not allowed in Go. You can only index maps, arrays or slices.
The fix is simple, since you do two (2) pointer dereferences in the working version, you need to do two (2) same in the single expression - but also you need to ensure the lexical binding order so the indexing is done after the pointer dereference:
fmt.Printf("%s", *(*selectedVM.NetworkProfile.NetworkInterfaces)[0].ID)

Finally, there is no pass-by-reference in Go. Everything is by value. If you want to change a value, pass a pointer to it - but that pointer is a still just a value that is copied.


text:
Q: Dynamically create document chapters based on directory tree For creating document structure I usually use something like this:
\section{1}
  Text for chapter 1

\section{2}
  Text for chapter 2

  \subsection{2.1}
  Text for chapter 2.1

    \subsubsection{2.1.1}
      Text for chapter 2.1.1

      \paragraph{2.1.1.1}\mbox{}\\
      Text for chapter 2.1.1.1

Is it possible to automatically handle \section \subsection \subsubsection\paragraph ... based on directory structure? My idea is to have tree like directory structure which will serve as template for document creation. In this example desired text "Text for chapter ..." is inside chapter.tex files:
./1/chapter.tex
./2/chapter.tex
./2/2.1/chapter.tex
./2/2.1/2.1.1/chapter.tex
./2/2.1/2.1.1/2.1.1.1/chapter.tex

Following example is same as previous except desired text is contained in files which has different names (one file per each directory). This is better because in your editor you can see correct names of chapters instead of chapter.txt for each document section:
./1/1.tex
./2/2.tex
./2/2.1/2_1.tex
./2/2.1/2.1.1/2_1_1.tex
./2/2.1/2.1.1/2.1.1.1/2_1_1_1.tex

As a bonus I would also like automatic labeling of chapters under each \section \subsection \subsubsection\paragraph ..., something like \label{2.1.1} etc.
I guess that I need some kind of preprocessor which will first sort alphabetically resp numerically underlining directories and compose final document. I'm not sure if this LaTeX can do or some external tools are required. Multiplatform solution would be fine but my primary OS is Linux. Thank you.

A: This approach may not be a good idea, LaTeX is designed to take care of the numbering for you (for example when you decide later to add a section between 1 and 2).
If you want to do it anyway, a scripting language is probably the easiest way. Example in Perl:
use File::Find;
use Cwd;
# get working directory for script
$cwd1 = getcwd();

# find all tex files recursively, store the path relative to cwd1
find(sub{ push(@allfiles,substr(getcwd(),length($cwd1))."/".$_) if $_=~/tex$/; },'.');

# sort the file list to get the right order
# note: tex files are called 0chapter.tex for sorting purposes
foreach $file(sort @allfiles){
    # count the number of underscores minus 2 (/1/0chapter.tex is level 0)
    $strlevel = "sub" x (($file =~ tr#/#/#)-2);
    # read the file
    open(IN,"<$cwd1$file");
    chomp(@contents = <IN>);
    close(IN);
    # print the first line of the file as (subsubsub)section title and the rest as contents
    print "\\$strlevel"."section\{$contents[0]\}\n".join("\n",@contents[1..$#contents])."\n";
    close(IN);
}

Add in a \newcommand{\subsubsubsection}[1]{\paragraph{#1}\mbox{}\\} somewhere and you are set. Example output from this script, using your directory structure:
\section{Title of foo}
contents of foo
\section{Title of bar}
contents of bar
\subsection{Title of foobar}
contents of foobar
\subsubsection{Title of foobarbaz}
contents of foobarbaz
\subsubsubsection{Title of foobarbazqux}
contents of foobarbazqux

A: Here is a solution
Notes

*

*The solution use (la)TeX loop.

*File names changed 1_1_1 -->1+1+1 (this is easier)

\documentclass{article}
\usepackage{lipsum}

\setcounter{secnumdepth}{4}

\newif\ifmoreinput
\newcounter{sec}
\newcounter{ssec}[sec]
\newcounter{sssec}[ssec]
\newcounter{parg}[sssec]
\begin{document}
\loop
\stepcounter{section}%
\stepcounter{sec}%
\edef\mtpath{\thesection}%
\edef\mtfile{\thesec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\moreinputtrue%
\addtocounter{section}{-1}%
\let\SomeMagicCommandThatHoldsChapterNameGoesHere\section
\input{\mtpath/\mtfile.tex}%
{\loop
\stepcounter{subsection}%
\stepcounter{ssec}%
\edef\mtpath{\thesection/\thesubsection}%
\edef\mtfile{\thesec+\thessec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\moreinputtrue%
\addtocounter{subsection}{-1}%
\let\SomeMagicCommandThatHoldsChapterNameGoesHere\subsection
\input{\mtpath/\mtfile.tex}%
{\loop
\stepcounter{subsubsection}%
\stepcounter{sssec}%
\edef\mtpath{\thesection/\thesubsection/\thesubsubsection}%
\edef\mtfile{\thesec+\thessec+\thesssec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\moreinputtrue%
\addtocounter{subsubsection}{-1}%
\let\SomeMagicCommandThatHoldsChapterNameGoesHere\subsubsection
\input{\mtpath/\mtfile.tex}%
{\loop
\stepcounter{paragraph}%
\stepcounter{parg}%
\edef\mtpath{\thesection/\thesubsection/\thesubsubsection/\theparagraph}%
\edef\mtfile{\thesec+\thessec+\thesssec+\theparg}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\moreinputtrue%
\addtocounter{paragraph}{-1}%
\let\SomeMagicCommandThatHoldsChapterNameGoesHere\paragraph
\input{\mtpath/\mtfile.tex}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat

\end{document}

Update here a better way: we use makemymain.tex to produce mymain.tex
this new file will be well strectured and more helpfull with latex editor (I will try to explain as i can)
makemymain.tex
\documentclass{article}
\usepackage{lipsum}
\setcounter{secnumdepth}{4}
\newcommand{\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{{#1}}

\newread\mtread
\newwrite\mtwrite
\immediate\openout\mtwrite=mymain.tex

\newcommand{\mtadd}[1]{\immediate\write\mtwrite{\string#1}}
\newcommand{\mtinput}[1]{%
\moreinputtrue%
\openin\mtread=\mtpath/\mtfile.tex
\read\mtread to \myread
\closein\mtread
\immediate\write\mtwrite{\string#1\myread}
\immediate\write\mtwrite{\string\input {\mtpath/\mtfile.tex}}}

% creating preamble of mymain.tex
\mtadd{\documentclass{article}}
\mtadd{\usepackage{lipsum}}
\mtadd{\setcounter{secnumdepth}{4}}
\mtadd{\newcommand{\string\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{}}
\mtadd{\begin{document}}

\AtEndDocument{\mtadd{\end{document}}}

\newif\ifmoreinput
\newcounter{sec}
\newcounter{ssec}[sec]
\newcounter{sssec}[ssec]
\newcounter{parg}[sssec]
\begin{document}
\tableofcontents
\loop
\stepcounter{section}%
\stepcounter{sec}%
\edef\mtpath{\thesection}%
\edef\mtfile{\thesec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\section}%
{\loop
\stepcounter{subsection}%
\stepcounter{ssec}%
\edef\mtpath{\thesection/\thesubsection}%
\edef\mtfile{\thesec+\thessec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\subsection}%
{\loop
\stepcounter{subsubsection}%
\stepcounter{sssec}%
\edef\mtpath{\thesection/\thesubsection/\thesubsubsection}%
\edef\mtfile{\thesec+\thessec+\thesssec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\subsubsection}%
{\loop
\stepcounter{paragraph}%
\stepcounter{parg}%
\edef\mtpath{\thesection/\thesubsection/\thesubsubsection/\theparagraph}%
\edef\mtfile{\thesec+\thessec+\thesssec+\theparg}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\paragraph}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat

\end{document}

Update 2
To avoid problems of expansion (read--write)
\newcommand{\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{{#1}}

replaced with
\newcommand{\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{{\unexpanded{#1}}}

back to original convention of files names 2_1_1.tex:
\catcode`\_12\relax

add before first loop
makemymain.tex
\documentclass{article}
\usepackage{lipsum}
\newcommand{\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{{\unexpanded{#1}}}

\newread\mtread
\newwrite\mtwrite
\immediate\openout\mtwrite=mymain.tex

\newcommand{\mtadd}[1]{\immediate\write\mtwrite{\string#1}}
\newcommand{\mtinput}[1]{%
\moreinputtrue%
\openin\mtread=\mtpath/\mtfile.tex
\read\mtread to \myread
\closein\mtread
\immediate\write\mtwrite{\string#1\myread}
\immediate\write\mtwrite{\string\input {\mtpath/\mtfile.tex}^^J}}

% creating preamble of mymain.tex
\mtadd{\documentclass{article}}
\mtadd{\usepackage{lipsum}}
\mtadd{\setcounter{secnumdepth}{4}}
\mtadd{\newcommand{\string\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{}}
\mtadd{\begin{document}}

\AtEndDocument{\mtadd{\end{document}}}

\newif\ifmoreinput
\newcounter{sec}
\newcounter{ssec}[sec]
\newcounter{sssec}[ssec]
\newcounter{parg}[sssec]
\begin{document}
\tableofcontents
\catcode`\_12\relax
\loop
\stepcounter{section}%
\stepcounter{sec}%
\def\mtpath{\thesection}%
\def\mtfile{\thesec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\section}%
{\loop
\stepcounter{subsection}%
\stepcounter{ssec}%
\def\mtpath{\thesection/\thesubsection}%
\def\mtfile{\thesec_\thessec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\subsection}%
{\loop
\stepcounter{subsubsection}%
\stepcounter{sssec}%
\def\mtpath{\thesection/\thesubsection/\thesubsubsection}%
\def\mtfile{\thesec_\thessec_\thesssec}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\subsubsection}%
{\loop
\stepcounter{paragraph}%
\stepcounter{parg}%
\def\mtpath{\thesection/\thesubsection/\thesubsubsection/\theparagraph}%
\def\mtfile{\thesec_\thessec_\thesssec_\theparg}%
\IfFileExists{\mtpath/\mtfile.tex}{%
\mtinput{\paragraph}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat}}{\moreinputfalse}%
\ifmoreinput\repeat

\end{document}

mymain.tex
\documentclass{article}
\usepackage{lipsum}
\setcounter{secnumdepth}{4}
\newcommand{\SomeMagicCommandThatHoldsChapterNameGoesHere}[1]{}
\begin{document}
\section{chapter 1}
\input{1/1.tex}

\section{chapter 2}
\input{2/2.tex}

\subsection{chapter 2.1}
\input{2/2.1/2_1.tex}

\subsubsection{chapter 2.1.1}
\input{2/2.1/2.1.1/2_1_1.tex}

\paragraph{chapter 2.1.1.1}
\input{2/2.1/2.1.1/2.1.1.1/2_1_1_1.tex}

\subsection{chapter 2.2}
\input{2/2.2/2_2.tex}

\subsubsection{chapter 2.2.1}
\input{2/2.2/2.2.1/2_2_1.tex}

\end{document}


text:
Q: How would I speed up this program? I am currently attempting to solve a ProjectEuler problem and I have got everything down, except the speed. I am almost certain the reason the program executes so slowly is due to the nested loops. I would love some advice on how to speed this up. I am a novice programmer, so I am not familiar with a lot of the more advanced methods/topics.
public class Problem12 {

    public static void main(String[] args) {
        int num;

        for (int i = 1; i < 15000; i++) {
            num = i * (i + 1) / 2;
            int counter = 0;

            for (int x = 1; x <= num; x++) {
                if (num % x == 0) {
                    counter++;
                }
            }
            System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
        }
    }
}

EDIT : Below is the new code that is exponentially faster. Removed the constant line printing as well to speed it up even more.
public class Problem12 {

    public static void main(String[] args) {
        int num;

        outerloop:
        for (int i = 1; i < 25000; i++) {
            num = i * (i + 1) / 2;
            int counter = 0;

            double root = Math.sqrt(num);
            for (int x = 1; x < root; x++) {
                if (num % x == 0) {
                    counter += 2;
                    if (counter >= 500) {
                        System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
                        break outerloop;
                    }
                }
            }
        }
    }
}

A: For starters, when looking at divisors, you never need to go further than the root square of the number, because each divisor below the square root has an equivalent above.
n = a * b => a <= sqrt(n) or b <= sqrt(n)

Then you need to count the other side of the division:
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
    if (num % x == 0) {
        counter += 2;
    }
}

The square root is special because it counts only once if it is integer:
if ((double) ((int) root) == root) {
    counter += 1;
}

A: You just need to factorize the number. p^a * q^b * r^c has (a+1)*(b+1)*(c+1) divisors. Here is some basic implementation using this idea:
static int Divisors(int num) {
    if (num == 1) {
        return 1;
    }

    int root = (int) Math.sqrt(num);
    for (int x = 2; x <= root; x++) {
        if (num % x == 0) {
            int c = 0;
            do {
                ++c;
                num /= x;
            } while (num % x == 0);
            return (c + 1) * Divisors(num);
        }
    }

    return 2;
}

public static void test500() {
    int i = 1, num = 1;
    while (Divisors(num) <= 500) {
        num += ++i;
    }

    System.out.println("\nFound: [" + i + "] - " + num);
}


text:
Q: Conditional install/uninstall of Windows Service Using VS2008 TFS I have created a setup application that installs two Window Services.  The first service is always installed and uninstalled (and works fine--I'm using the installer class).  The second service is optional.  Depending a custom condition I set up determines whether the 2nd service is installed.  If requested the install works fine (using the installer class also).  However, I cannot get the service to uninstalled during the uninstall process.  The service exe is deleted, but the uninstall fails to uninstall the service.  I have set the Condition property on my assembly file (in the File System) and on all the custom actions associated with this assembly.  I suspect it is the custom action on the uninstall that is incorrect.  I am unable to remove the condition on the uninstall custom action--I get an error if I do (Unable to build custom action name  because it uses a conditionally installed file.)  I have tried other conditions but they too fail to uninstall the service.
To ensure my installer class is working okay, as a test, I removed all conditions and forced the 2nd service to install.  The install and uninstalled worked fine in this case.  Hope someone can help.  Thanks in advance.

A: Perhaps you can add an additional check in your condition, so that it only evaluates to true if the product is installed.  There is an Installed property that might give you what you need.


text:
Q: Entity Framework & ASP.NET MVC: can't get to the [HttpPost] on my controller from another one I'm trying to redirect the user from this view on the SolicitantesController to the one on the Create of ExpedientesController:
@model Entrega02Programacion03.Models.Solicitante

@{
    ViewBag.Title = "InformeSolicitante";
}

InformeSolicitante

Solicitante

Cedula:  @ViewBag.Cedula

 Nombre: @ViewBag.Nombre

Apellido: @ViewBag.Apellido

Email:  @ViewBag.Email

Tel: @ViewBag.tel

            <input type="submit" value="Crear Expediente" class="btn btn-default" />

This is the post on solicitantesController, but I can't get my button Crear Expediente to get there, any ideas of what I may be doing wrong? Thanks
[HttpPost]
public ActionResult InformeSolicitantes()
{
     return RedirectToAction("Expedientes", "Create");
}

A: i suggest two solutions to solve it:
1)replace submit html control with anchor link with InformeSolicitantes action url and remove [HttpPost]
for example replace
<input type="submit" value="Crear Expediente" class="btn btn-default" />

with

then remove
[HttpPost]
2)put input control into form control and set form action and controllers to hit InformeSolicitantes action.
for example replace

        <input type="submit" value="Crear Expediente" class="btn btn-default" />

with
<form action="action path/name" method="post">

        <input type="submit" value="Crear Expediente" class="btn btn-default" />

</form>


text:
Q: If keydown !== A,B or C in Javascript? I'm trying to trigger an event if any key is pressed except the arrows keys or the enter key on a text input field.
myinput.addEventListener('keydown', (e) => {
    if (e.keyCode !== 13 ||
        e.keyCode !== 37 ||
        e.keyCode !== 38 ||
        e.keyCode !== 39 ||
        e.keyCode !== 40 ) {
          console.log('foo');
    }
});

In the above example, my if is ignored and 'foo' appears for every key.
Any idea what I am doing wrong?


text:
Q: jQuery search not working with input type date? I am trying to use jQuery's search filter with my input type date but it's not working for me. It's working only for input type=text.
This is my markup and code:
function myFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  alert(input);
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("td");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";

    }
  }
}

Markup:
<input type="text" id="myInput" class="" onkeyup="myFunction()" placeholder="">

      Last Year Turnover
      Receipt
      Period

        <?php echo $data['company_analytics']['last_year_turnorder'];?>

        <?php echo $receipt;?>

        <?php echo $data['company_analytics']['period'];?>

I am getting dynamic data from database in table format. Now I want to add filter on that table on period column. So that I used above code but it's not working for me. I think I am using datepicker in search box that's why its not getting data. Is there any way to show data from table with search box with datepicker.
I refer this link to get data. But in my condition data is dynamic and coming in table format.
enter link description here


text:
Q: data.table cumulative stats of irregular observations with time window I have some transactional records, like the following:
library(data.table)
customers      <- 1:75
purchase_dates <- seq( as.Date('2016-01-01'),
                       as.Date('2018-12-31'),
                       by=1 )
n <- 500L

set.seed(1)

# Assume the data are already ordered and 1 row per cust_id/purch_dt
df <- data.table( cust_id   = sample(customers, n, replace=TRUE),
                  purch_dt  = sample(purchase_dates, n, replace=TRUE),
                  purch_amt = sample(500:50000, n, replace=TRUE)/100
                  )[, .(purch_amt = sum(purch_amt)),
                      keyby=.(cust_id, purch_dt) ]
df
# cust_id   purch_dt purch_amt
#       1 2016-03-20     69.65
#       1 2016-05-17    413.60
#       1 2016-12-25    357.18
#       1 2017-03-20    256.21
#       2 2016-05-26     49.14
#       2 2018-05-31    261.87
#       2 2018-12-27    293.28
#       3 2016-12-10    204.12
#       3 2018-09-21      8.70

I would like to know the prior transaction count and total amount, within a 365-day prior window (i.e., at d-365 through d-1 for a transaction on date d).
I thought of using a rolling join, but that would match to at most one prior purchase, and there could be multiple purchases.
I was able to get the desired result using a Cartesian self-join with a date filter (see answer below), but that's not a very memory-efficient approach.
Desired output:
 cust_id   purch_dt prior_purch_cnt prior_purch_amt purch_amt
       1 2016-03-20               0            0.00     69.65
       1 2016-05-17               1           69.65    413.60
       1 2016-12-25               2          483.25    357.18
       1 2017-03-20               3          840.43    256.21
       2 2016-05-26               0            0.00     49.14
       2 2018-05-31               0            0.00    261.87
       2 2018-12-27               1          261.87    293.28
       3 2016-12-10               0            0.00    204.12
       3 2018-09-21               0            0.00      8.70

A:
I would like to know the prior transaction count and total amount, within a 365-day prior window (i.e., at d-365 through d-1 for a transaction on date d).

I think the idiomatic way is:
df[, c("ppn", "ppa") :=
  df[.(cust_id = cust_id, d_dn = purch_dt-365, d_up = purch_dt),
    on=.(cust_id, purch_dt >= d_dn, purch_dt < d_up),
    .(.N, sum(purch_amt, na.rm=TRUE))
  , by=.EACHI][, .(N, V2)]
]

     cust_id   purch_dt purch_amt ppn    ppa
  1:       1 2016-03-20     69.65   0   0.00
  2:       1 2016-05-17    413.60   1  69.65
  3:       1 2016-12-25    357.18   2 483.25
  4:       1 2017-03-20    256.21   3 840.43
  5:       2 2016-05-26     49.14   0   0.00
 ---
494:      75 2018-01-12    381.24   2 201.04
495:      75 2018-04-01     65.83   3 582.28
496:      75 2018-06-17    170.30   4 648.11
497:      75 2018-07-22     60.49   5 818.41
498:      75 2018-10-10     66.12   4 677.86

This is a "non-equi join".

A: Here's the Cartesian self-join with date-range filter:
df_prior <- df[df, on=.(cust_id), allow.cartesian=TRUE
                ][i.purch_dt < purch_dt &
                    i.purch_dt >= purch_dt - 365
                  ][, .(prior_purch_cnt = .N,
                        prior_purch_amt = sum(i.purch_amt)),
                     keyby=.(cust_id, purch_dt)]

df2 <- df_prior[df, on=.(cust_id, purch_dt)]

df2[is.na(prior_purch_cnt), `:=`(prior_purch_cnt=0,
                                 prior_purch_amt=0
                                 )]
df2
# cust_id   purch_dt prior_purch_cnt prior_purch_amt purch_amt
#       1 2016-03-20               0            0.00     69.65
#       1 2016-05-17               1           69.65    413.60
#       1 2016-12-25               2          483.25    357.18
#       1 2017-03-20               3          840.43    256.21
#       2 2016-05-26               0            0.00     49.14

I'm concerned about how this could blow up prior to filtering on datasets where customers have many prior transactions.


text:
Q: ExpressionVisitor not visiting overridden property of a derived class I'm trying to use the ExpressionVisitor to get an overridden member of an expression but it's giving me the base one. What am I missing here?
The following example reproduces this behaviour:
Simple base and derived types:
class Base
{
    public virtual string Property { get; set; }
}

class Derived : Base
{
    public override string Property { get; set; }
}

I use this expression visitor:
internal class DemoVisitor : ExpressionVisitor
{
    private MemberInfo _member;

    public static MemberInfo GetMemberInfo(LambdaExpression expression)
    {
        var visitor = new DemoVisitor();
        visitor.Visit(expression);

        return visitor._member;
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        // invalid member here
        //node.Member.DeclaringType.Name.Dump();
        _member = _member ?? node.Member;

        return base.VisitMember(node);
    }
}

Calling it like that
void Main()
{
    var derived = new Derived();
    var expression = (Expression<Func<string>>)(() => derived.Property);
    DemoVisitor.GetMemberInfo(expression).DeclaringType.Name.Dump();
}

This returns Base instead of Derived. What do I have to do to get to the overridden member?
I need it because I'm reading its attributes later and it's currently giving me the attributes of the property on the base class instead of the derived one.

A: If you want to know the type of the class/struct of your member you need to look at the MemberExpression's Expression property which is the expression for the object containing the member - in your case the derived variable - and get its type.
Therefore your visitor needs to return both (here I used a ValueTuple):
internal class DemoVisitor : ExpressionVisitor
{
    private Type type;
    private MemberInfo _member;

    public static (Type, MemberInfo) GetMemberInfo(LambdaExpression expression)
    {
        var visitor = new DemoVisitor();
        visitor.Visit(expression);

        return (visitor.type, visitor._member);
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        if (_member == null)
        {
          _member = node.Member;
          type = node.Expression.Type;
        }

        return base.VisitMember(node);
    }
}

Regarding your other question about which member gets visited: all used members in your expression get visited, i.e. all methods, properties and fields, whereas node.Member returns either a MethodInfo, PropertyInfo or FieldInfo object, which all derive from MemberInfo.


text:
Q: No Display with Navi10 Gpu I have a Sapphire Radeon 5600XT which came out around a month or so ago. I am able to boot the live CD (18.04) sometimes and install ubuntu but after I reboot and start the freshly installed OS I see HDD activity but the screen either goes black or sticks at the loading ubuntu screen with the dots. When I press ctl-alt-del it does the shutdown process (I can see HDD activity) and then reboots.
After messing around I was able to figure out that using nomodeset in place of quiet splash in the grub kernel arguments can get me into the installed OS, but of course the resolution is locked at 1024x768 and I guess the GPU specific kernel modules are not being loaded.
A couple of times I was able to get to the lower run level screens that shows text output of what is going on and I can see messages like:
[drm:amdgpu_job_timedout [amdgpu]] *ERROR* ring gfx timeout

I've stumbled across some people running into this but not figured out a work around yet. I've also downloaded the amd linux drivers and installed them but it's not helped and also it shows some warnings at the end of the install (I think because I'm booted in with nomodeset).

A: Ok after some more trial and error and googling, I stumbled upon this reddit post: https://www.reddit.com/r/linux_gaming/comments/f52fnl/hardware_update_on_the_rx_5600_xts_performance_on/
Which mentions exactly the problem I was having albeit on another ubuntu-based OS. The OP mentions that he got it to work but had to do a few things:

*

*install the latest firmware

*install the latest mesa packages

*install the latest kernel

So I gave that a whack and it actually worked. Specifically do the following:

*

*Boot the 18.04 live cd, press e while try ubuntu without installing is selected. Replace the text quiet splash with nomodeset and press F10 to boot. You should be greeted by the desktop in all its 720P glory... Install ubuntu from there as normal

*Upon restart, when you get the grub menu, do the same thing again. With ubuntu highlighted, press e and replace quiet splash with nomodeset and press F10 to continue booting. Sometimes the grub menu is all purple with no boot options, press esc if this happens and then do the nomodeset trick as described.

*Once in you can use the following script to get the OS patched to boot properly with this card:

#!/bin/bash
set -e

#grab the latest navi10 firmware
sudo apt install git
git clone git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git
cd linux-firmware
git checkout $(git describe --tags)
sudo cp -rp amdgpu/* /lib/firmware/amdgpu/
#sudo update-initramfs -u #this happens when we install the new kernel below
cd -

#grab newest mesa drivers and update other packages...
sudo add-apt-repository ppa:paulo-miguel-dias/pkppa
sudo apt-get update
sudo apt-get upgrade #too lazy to list individual packages

#grab a newer kernel
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.5.6/linux-headers-5.5.6-050506_5.5.6-050506.202002240832_all.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.5.6/linux-headers-5.5.6-050506-generic_5.5.6-050506.202002240832_amd64.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.5.6/linux-image-unsigned-5.5.6-050506-generic_5.5.6-050506.202002240832_amd64.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.5.6/linux-modules-5.5.6-050506-generic_5.5.6-050506.202002240832_amd64.deb
sudo dpkg -i *.deb

That's it, reboot and let the OS start itself as normal. Your resolution should match whatever your display supports and your GPU should now be used properly. At the time of writing there are still some strange things going on. If you put the computer to sleep and wake it there is massive flickering even if you restart gdm, so I suppose we'll need to wait a bit for better drivers.