text:
Q: Is it possible to reference Git objects from a commit without adding them to the tree-object filesystem? I can add a file manually to the git object store using for example
echo "foo bar" | git hash-object -w --stdin

This will create a file in .git/objects with the content foo bar (plus some header) and name it by its SHA-1 (or SHA-256 depending on --object-type) hash.
However, that's a dangling object now. Next time git gc runs and my object is older than the set prune time (2 weeks I think by default), that file will be deleted. It also won't get pushed to the remote repository because it's not reachable yet by any pushable thing (branch or tag).
To reference it, I could either add it to a tree object that's referenced by a commit object or reference it in a tag.
However, adding it to a tree will add it to the file system represented by it (and it must be given a filename) and referencing it with a tag will not make it part of the merkle-tree of a commit (and it won't get pushed/pulled automatically hence).
I would like to add an object to the object store and have it be part of the merkle-tree of my commit (so that it gets pushed/pulled and is protected from garbage collection) but without giving it a filename (i.e. without it ever appearing in the staging area outside of the .git folder when checking out a commit that references it).
Is this possible somehow with vanilla Git?
Is it for example possible to add entries to a tree object without specifying a file-name for it? If so, how? (git write-tree takes the files from the staging area so they need to have filenames.)
Or is it maybe possible to reference the object hash from the commit message in a way that tells Git that this object is part of the commit and thus must be pushed/pulled with the commit?
Or can git update-index be used for this?

A: You can create a non-branch reference that does not share any history or name with the other branches and add the file there. Chances are you do need to track changes to the file at some point so this leaves you with the option to do that later.
For example:
git checkout --orphan temporary-branch
git reset --hard
git add the_file
git commit -m 'Add the file'
git update-ref refs/hook-metadata/foo temporary-branch
git branch -D temporary-branch

Reference:

*

*Remove/hide git branches without deleting commit histories

*How to create a new (and empty!) "root" branch?

A:
Is this possible somehow with vanilla Git? Is it for example possible to add entries to a tree object without specifying a file-name for it?

No.  Tree entries are <mode, name, hash> tuples.  The mode part must be one of Git's well-defined modes: 100644 for a non-executable file, 100755 for an executable file, 120000 for a symbolic link, 160000 for a gitlink.  (Mode 040000 represents a tree object and can only appear in another tree object.  As you noted, git write-tree turns the index into a tree, so normally you'd put these in the index ... which is what git add does.  The index cannot store a mode 40000 entry.  You can also use git mktree to make trees; this is how to add a subtree to a tree.)
The extraction code in Git comes in two parts, sort of: there's one part that reads a commit or tree into Git's index (git read-tree) and one part that reads Git's index and creates usable files from the various symlinks and blob objects in the index (git checkout-index).  A checkout or switch operation that switches from the current commit to a new commit simply rolls both of these into a single convenient (and useful) command.  Of course it turns out there is a ton of overlap, so that git read-tree can affect the working tree, and git checkout can read or fill in the index (though this functionality is now in git restore if you prefer to avoid lumping everything into git checkout by using the split-up switch-and-restore commands—this amounts to admitting well, it looked cleanly separable, but it turns out it wasn't...).

... I want to store some repository-wide metadata used with hooks (in particular certificate-chains for long-term-validation of signatures (not pgp) contained in commit messages) and there's 1. no reason for these files to be revisioned 2. It should not impose some folder structure onto projects using these hooks.

The confounding issues here, per point, are these:

*

*Git can't store files without versioning them.  Its underlying storage model is "revisions".

*Git can't really deal with files without also using the host OS to deal with files.  You can get arbitrarily close, using git hash-object -w and git cat-file -p and the like, but in the end, you almost certainly have to store that file data in, well, a file.  A host-OS file, that is.  It's the host that imposes folder structures on files in the first place, so there's no getting around that anyway.
You can try to be flexible about the host-OS-enforced structuring in point 2 so that projects can do things their own way.  You can simply store a single commit, under some known ref name, without any history (no parent for this commit, ever) in point 1, so that the versioned files "fall away" automatically.  But you'll still be versioning files that came from some sort of directory-and-file-tree structure.


text:
Q: Почему при создании токена jwt возникает ошибка - Unsupported media type? Отправляю через postman запрос на /api/auth/token/create/. В body указываю username и password. В headers установлен Content-Type:application/json и Accept:application/json.
В ответ получаю:

{"detail": "Unsupported media type \"multipart/form-data; boundary=--------------------------286954501919688601950776\" in request."}

urls.py:
urlpatterns = [
    ...
    path('api/auth/', include('djoser.urls')),
    path('api/auth/', include('djoser.urls.authtoken')),
    path('api/auth/', include('djoser.urls.jwt')),
    path('admin', admin.site.urls)]

settings.py:
INSTALLED_APPS = [
...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'rest_framework',
"rest_framework.authtoken",
'djoser',
'corsheaders',]

MIDDLEWARE = ['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]

REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',
            'rest_framework.parsers.FormParser',
                    'rest_framework.parsers.MultiPartParser'),
'DEFAULT_PARSER_CLASSES': ('rest_framework.parsers.JSONParser',),
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',
    'rest_framework.permissions.AllowAny',),
'DEFAULT_AUTHENTICATION_CLASSES': (# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication',)
}
CORS_ORIGIN_ALLOW_ALL = True

Установленные пакеты(сделал через pastebin потому, что много места здесь занимает)
Еще очень странная ошибка возникает, если удалить пакет "djangorestframework-simplejwt".
При запуске сервера, здесь:
path('api/auth/', include('djoser.urls.jwt')),

возникает ошибка:

No module named 'rest_framework_simplejwt'

хотя я использую "rest_framework_jwt", а не "rest_framework_simplejwt".
Ну а после установки simplejwt ошибки на сервере не возникает, но и токен не могу создать.

A: Написал данные не в form-data, а в raw(json формате) и все заработало.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function can't be unconditionally invoked because it can be 'null' I am building a profile page. But I am having some issues in retrieving name and mail from the firebase.
 firebase_auth: ^3.1.1
 firebase_core: ^1.6.0
 google_sign_in: ^5.1.0
 firebase_storage: ^10.0.3
 cloud_firestore: ^2.5.3
 firebase_analytics: ^8.3.2
 lottie: ^1.1.0
 image_picker: ^0.8.4

Above is my pubspec.yaml dependencies.
  Widget headerProfile(
  BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
  return SizedBox(
  height: MediaQuery.of(context).size.height * 0.26,
  width: MediaQuery.of(context).size.width,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Container(
        height: 150.0,
        width: 170.0,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: constantColors.transparent,
                radius: 38.0,
                backgroundImage: NetworkImage(
                    '${Provider.of<FirebaseOperations>(context).getInitUserImage}'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text(
                snapshot.data()['username'],
                style: TextStyle(
                    color: constantColors.whiteColor,
                    fontWeight: FontWeight.bold,
                    fontSize: 20.0),
              ),
            ),

Above is the profilehelpers.dart page.
 class Profile extends StatefulWidget {
 @override
 _ProfileState createState() => _ProfileState();
 }

class _ProfileState extends State<Profile> {
final ConstantColors constantColors = ConstantColors();
 @override
 Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    centerTitle: true,
    leading: IconButton(
      onPressed: () {},
      icon: Icon(EvaIcons.settings2Outline,
          color: constantColors.lightBlueColor),
    ),
    actions: [
      IconButton(
          icon: Icon(EvaIcons.logOutOutline,
              color: constantColors.greenColor),
          onPressed: () {
            Provider.of<ProfileHelpers>(context, listen: false)
                .logOutDialog(context);
          })
    ],
    backgroundColor: constantColors.blueGreyColor.withOpacity(0.4),
    title: RichText(
      text: TextSpan(
          text: 'My ',
          style: TextStyle(
            color: constantColors.whiteColor,
            fontWeight: FontWeight.bold,
            fontSize: 20.0,
          ),
          children: <TextSpan>[
            TextSpan(
                text: 'Profile',
                style: TextStyle(
                  color: constantColors.blueColor,
                  fontWeight: FontWeight.bold,
                  fontSize: 20.0,
                ))
          ]),
       ),
      ),
    body: SingleChildScrollView(
    child: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,

        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: FirebaseFirestore.instance
              .collection('users')
              .doc(Provider.of<Authentication>(context, listen: false)
                  .getUserUid)
              .snapshots(),
          builder: (BuildContext context,
              AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return new Column(
                children: [
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .headerProfile(context, snapshot),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .divider(),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .middleProfile(context, snapshot),
                  Provider.of<ProfileHelpers>(context, listen: false)
                      .footerProfile(context, snapshot)
                ],
              );
            }
          },
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.0),
            color: constantColors.blueGreyColor.withOpacity(0.6)),
      ),
    ),
     ),
    );
    }
    }

Above is the profile.dart file code.
I think the problem is somewhere with document and asyncsnapshot and 'snapshot.data()['username']'.If someone can point out my mistake it will be more helpful for me.
40:34: Error: 'data' isn't a function or method and can't be
  invoked.
                snapshot.data()['username'],
                             ^^^^

FAILURE: Build failed with an exception.

This is the error I am getting

A: Should be snapshot.data.data()['username'] not snapshot.data()['username'];
You may still get errors (like Object not being a subtype of Map) because of the way you wrote your code, in that case, use this (copy and paste into your code, I changed some things):
Widget headerProfile(
  BuildContext context, AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
  Map<String, dynamic>? map = snapshot.data!.data();
  return SizedBox(
  height: MediaQuery.of(context).size.height * 0.26,
  width: MediaQuery.of(context).size.width,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Container(
        height: 150.0,
        width: 170.0,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {},
              child: CircleAvatar(
                backgroundColor: constantColors.transparent,
                radius: 38.0,
                backgroundImage: NetworkImage(
                    '${Provider.of<FirebaseOperations>(context).getInitUserImage}'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text(
                map['username'],
                style: TextStyle(
                    color: constantColors.whiteColor,
                    fontWeight: FontWeight.bold,
                    fontSize: 20.0),
              ),
            ),

A: can you please try like "snapshot.data['username']"??
also refer to this post
link for fetching data from real time firebase DB


text:
Q: How do I find the data directory for MySQL Server 5.7 on Windows 10? I've been snooping around and I found that some people's MySQL Server 5.7 directory had a data directory within their MySQL Server 5.7 directory along with bin, lib etc. but mine doesn't. I've tried reinstalling multiple ways and I have concluded that the data directory is not there.
Upon launching the MySQL server I get ERROR:

failed to set datadir to C:\Program Files\MySQL\MySQL Server
  5.7\data\

By the way, I am using MySQL Server 5.7 connected to the NetBeans IDE 8.2, so I can't launch my PHP code.

A: Regarding to this documentation here https://dev.mysql.com/doc/refman/5.7/en/windows-installation-layout.html if you installed your MySQL using the installer, you could find data directory under %PROGRAMDATA%\MySQL\MySQL Server 5.7\
if you find your data directory there, you can send that location to mysqld using --datadir to let mysql server where to find data files.


text:
Q: Model Start Event Cascade through BPMN I'm trying to model the following (simplified) workflow. Each start event has a route to the Main Task as well as an alternative route which will trigger the "previous" start event.
My problem: if Start Event 2 is triggered through a path from Start Event 3 it should not be possible to trigger Start Event 1 any more (red path): 3->2 is ok, 2->1 is ok, but not 3->1!

What would be the "right" solution here? Should I create an alternative Start Event 2 when it's triggered through Start Event 3 (seem to be redundant). Or should I solve this somehow through a logic gate if triggered through Start Event 3 then ...  else ... (seems to be over complicated). Or is there a better solution?
PS. I tried to find a better stack exchange site for modelling but it seems 99% of the questions regarding BPMN are posted here. But I'm open for suggestions.

A: First of all, Start Events must not have an incoming Edge. It is not allowed by the BPMN standard. So you should replace your Start Events 2 and 3 within the process with intermediate Events.
The decission logic to skip or execute the Intermediate Event now representing the event of what was before Start Event 3 could be implemented in an Event Based Gateway, describing on the Edges which path to take under which condition.

A: Based on Simulat's answer I found a alternative solution which I think is the better fit. The red path should not be possible because of the logic gate with the red circle (the top path is only viable if Start Event 3 has not occurred).
The problem I have with Simulat's answer are the intermediate events and the event based gate. Since there are no "real" events on those points so I think they should be xor logic gates, but I'm not sure. Feedback is welcome:


text:
Q: Reading txt files in a choosen directory #include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      puts (ep->d_name);

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  return 0;
}

This code gives me all things in that directory. It works like "ls" command. For example let's say i have one folder which is name is "folder" and one .txt file which is name is "input" (names are could be different btw) , in that directory. I want to decide if it is folder or txt file.If it is txt file how can i read it?

A: ]You can use scandir() function to open and scan the entries in a directory.
The example comes from man 3 scandir
#define _SVID_SOURCE
/* print files in current directory in reverse order */
#include <dirent.h>

int
main(void)
{
    struct dirent **namelist;
    int n;

    n = scandir(".", &namelist, NULL, alphasort);
    if (n < 0)
        perror("scandir");
    else {
        while (n--) {
            printf("%s\n", namelist[n]->d_name);
            free(namelist[n]);
        }
        free(namelist);
    }
}

Note the struct dirent:
struct dirent {
    ino_t          d_ino;       /* inode number */
    off_t          d_off;       /* offset to the next dirent */
    unsigned short d_reclen;    /* length of this record */
    unsigned char  d_type;      /* type of file; not supported
                               by all file system types */
    char           d_name[256]; /* filename */
};

you can check if current entry is a regular file, directory or others by d_type field.
Available file types are :
#define DT_UNKNOWN       0
#define DT_FIFO          1
#define DT_CHR           2
#define DT_DIR           4   // directory type
#define DT_BLK           6
#define DT_REG           8   // regular file, txt file is a regular file
#define DT_LNK          10
#define DT_SOCK         12
#define DT_WHT          14

After checking the name and type of file, you can safely open it with open()(system call) or fopen()(glib function) and read the contents by read()(if you opened file via open() or fread()(fopen() counterpart).
DON'T forget to close file after read.
Besides, if you just want to check the existence and accessibility of a directory, access() is handle.
The code below tests if the dir exist.
int exist_dir (const char *dir)
{
    DIR *dirptr;

    if (access(dir, F_OK) != -1) {
        // file exists
        if ((dirptr = opendir(dir)) != NULL) {
            // do something here
            closedir (dirptr);
        } else {
            // dir exists, but not a directory
            return -1;
        }
    } else {
        // dir does not exist
        return -1;
    }

    return 0;
}

A: All information about a file except the contents can be get by calling function stat. stat has signature
int stat(const char *pathname, struct stat *buf);

and returns information about the file in the buffer pointed to by buf.
struct stat encodes information of file type and file permission in the field st_mode.
Some additional macros are defined to test the file type:

S_ISREG(m)  is it a regular file?
S_ISDIR(m)  directory?
S_ISCHR(m)  character device?
S_ISBLK(m)  block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m)  symbolic link?  (Not in POSIX.1-1996.)
S_ISSOCK(m) socket?  (Not in POSIX.1-1996.)

Here is a piece of sample code:
stat(pathname, &sb);
if (S_ISREG(sb.st_mode)) {
   /* Handle regular file */
}

As for reading, concatenate directory path and filename to get file path, using function sprintf, like this:
sprintf(file_path, "%s/%s", dir_path, file_name);


text:
Q: "Get {something} through to {somebody}" vs. "Get {something} across to {somebody}" How do these expressions differ?
Does one of them sound more forceful to you?
For instance, in the following sentence, does using each one make any change in meaning:

*

*What are you trying to get across to me?

*What are you trying to get through to me?

A:

*

*"Get {something} across to {somebody}"

means "Present {something} in a way that {somebody} can understand", or "Explain in a way that {somebody} shows they understand".  The phrasing assumes that the problem is a difference in language or assumptions.  For example, science teachers often have a hard time getting quantum mechanics concepts across to their students.

*"Get {something} through to {somebody}"

means "Force {somebody} to accept that {something} is true", or "Convince."  The phrasing assumes that {somebody} is resisting the idea of {something}.  For example, football coaches sometimes need to get through to their players that academics are important -- and that if a student doesn't earn good grades, the student won't be allowed to play football.
Thus, "get {something} through to {somebody}" is more forceful.


text:
Q: How to check if my model has changed on the view? I am trying to update a list of items. But I want to update only the items that have changed on my view.
For now, on my controller I have this code
foreach ( var item in items )
{
   update(item);
}

But I need to have something like that
foreach ( var item in items )
{
    if(ItemHasChanged(item))
    {
       update(item);
    }
}

I need to have this because I don't want to do any unnecessary updates and it's good for performance. Also I don't want to do a roundtrip to database to check if the item has changed.
Is it possible to check on the view if the item has changed ?
I am using asp.net mvc 4...

A: The below jQuery will do this job. As any of the input field is changed in the View this function would be triggered.
$('form :input').on('change input', function () {
    alert('changed'); //Your code..
});

A: Maybe you could cache your model before to send it to the view.
HttpContext.Current.Session["OldModel"] = yourModel;
And then compare the model you get in your POST action with the one is cached.
If you decide to do it by JavaScript I think you should take into consideration that a user could modify or disable the JavaScript on the browser.


text:
Q: Executing JPanelForm from Main class in java i am bit new in java what i want to achieve is, I have 2 java classes in same package.
CodeAnalyzer.java and CodeReader.java
CodeReader is the Jform class in which i have made JFileChooser, now i want to execute CodeReader with the execution of CodeAnalyzer.
Source code of CodeAnalyzer is Below
public class CodeAnalyzer {

public static void main(String[] args) {
    // TODO code application logic here
}

}

A: public class CodeAnalyzer {
CodeReader cr;
   public static void main(String[] args) {
     cr = new CodeReader();
   }
}

Just make an Object of your CodeReader and if it executes a Code which promts a Window it'll do it


text:
Q: Run multiple versions of Python with tox in Windows Could anyone point me to the best way to let Tox find multiple Python interpreters on a Windows system? I am not allowed to modify the tox.ini for my project. The tox.ini file contains:
envlist = py27,py37

I would like tox to be able to find the Python2 and Python3 interpreters. In Linux, I do this by setting multiple local versions of Python with pyenv (pyenv local 3.7.0, 2.7.15) but the Windows version does not appear to support multiple arguments. Does anyone have any ideas on the easiest way to do this for Windows, preferably without messing with my PATH?

A: There is also pyenv for Windows
https://github.com/pyenv-win/pyenv-win


text:
Q: how to show checkbox checked in laravel hi I am working on multiple checkbox and  the value of checkboxes is storing in this format in my database 2,3,4
code of my blade file:-

        @foreach($var as $vars)

                        <input type="checkbox" class="larger" name="process[]"  value=""  {{ ($vars->process == 1 ? 'checked' : '')}}>Cold/Hot Forging

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 2 ? 'checked' : '')}}>Injection Molding

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 3 ? 'checked' : '')}}>Precision Machining

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 4 ? 'checked' : '')}}>Sheet Metal Pressing

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 5 ? 'checked' : '')}}>Sub-assembly

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 6 ? 'checked' : '')}}>Surface tretment

                        <input type="checkbox" class="larger" name="process[]" value=""  {{ ($vars->process == 7 ? 'checked' : '')}}> Other

                  @endforeach

so this code is showing me only one checkbox checked whose value is 2
controller code:-
$processvalue = ProcessValue::where('company_basic_info_id','=',$id)->get();

A: First you make an array with all data
<?php
$all_processvalue = array();
foreach($processvalue as $pvalue){
     $all_data[] =  $pvalue->id;
}
?>

Now you create checkbox
@foreach ($vars as $var)
    {{ Form::checkbox('var[]', $var->id, in_array($var->id, $all_processvalue )) }}
    {{ Form::label('var', $var->name) }}

@endforeach

A: To make this happen,
First convert database value in array,
$var = '2,3,4';   // Your checkbox values in database
$allCheckboxValues = explode(",",$var);  // Convert it in array

Then put it in your checkboxes,

        <input type="checkbox" class="larger" name="process[]"  value="1"  {{ (in_array(1,$allCheckboxValues) ? 'checked' : '')}}>Cold/Hot Forging

        <input type="checkbox" class="larger" name="process[]" value="2"  {{ (in_array(2,$allCheckboxValues) ? 'checked' : '')}}>Injection Molding

        <input type="checkbox" class="larger" name="process[]" value="3"  {{ (in_array(3,$allCheckboxValues) ? 'checked' : '')}}>Precision Machining

        <input type="checkbox" class="larger" name="process[]" value="4"  {{ (in_array(4,$allCheckboxValues) ? 'checked' : '')}}>Sheet Metal Pressing

        <input type="checkbox" class="larger" name="process[]" value="5"  {{ (in_array(5,$allCheckboxValues) ? 'checked' : '')}}>Sub-assembly

        <input type="checkbox" class="larger" name="process[]" value="6"  {{ (in_array(6,$allCheckboxValues) ? 'checked' : '')}}>Surface tretment

        <input type="checkbox" class="larger" name="process[]" value="7"  {{ (in_array(7,$allCheckboxValues) ? 'checked' : '')}}> Other


text:
Q: What are the different ways of calling a component in JSX? If I call/invoke a component in jsx like so:
function arrow(){
  return (

Cool arrow

  )
}

return (

      {arrow()}

)

VS
const Arrow = () => {
  return (

Cool arrow

  )
}

return (

      <Arrow />

)

Are there any differences to be aware of? They are both components in the same file but I have noticed state behaves differently?

A: There are differences

function arrow(){
  return (

Cool arrow

  )
}

return (

    {arrow()}

)

Here arrow is not a React component, it is simply a function that returns some JSX. Because arrow is a function and not a React component it won't and can't have state or any lifecycle. The function is called each render and JSX computed and returned.

const Arrow = () => {
  return (

Cool arrow

  )
}

return (

    <Arrow />

)

Here Arrow is a React component. Use caution where you define it though. If you define Arrow within another React component then it will be recreated each time the outer component renders. Arrow would be remounted each render of the outer component, and thus may have some unintended side-effects because of this. If you do this, be sure to declare Arrow outside any other components.

They are both component's in the same file but I have noticed state
behaves differently?

I don't see any state used in either snippet so it's difficult to address this question, but I imagine any state issues may be related to the re-declaration/re-mounting issue described above. New component === new initial state when mounting.

What are the different ways of calling a component in JSX?

You don't call React components directly, you template them in JSX and React handles converting the JSX to callable functions and maintains the component lifecycle.


text:
Q: Share specific files in folder I have a folder of spreadsheets and I need to share specific spreadsheets with specific users and be able to replace the spreadsheets occasionally with files having the same name. I do not want the users to have access to the other files. Is there a way to keep the sharing function on when the files are replaced or would I need to reshare each one?
I also want to notify the users when their files are updated and  this process covers that by adding the naming Condition as outlined here: Send email when file of a specific name is created or modified.

A: Overwriting a file does not affect item permissions. Follow below steps:

*

*Create SharePoint group (SPGroup) from 'People/Groups' under site settings. Make sure not to assign access level yet

*Go to documents library and open item permissions of the documents that you want 'to restrict to' or 'provide access to' and break the inheritance

*Grant access to the newly created SPGroup with required access level (preferably Read)

*Open SPGroup and add the users who need to access the file

*Repeat steps 2 to 3 to document items that you want to limit access to

When your new file comes in with same name, it will just overwrite the existing file with no impact to the permissions. Thus making it always available to users in SPGroups and other users on the site.


text:
Q: Using scalar product to show that an angle is right The coordinates of the three points A, B, C are $\space$
$A=\begin{bmatrix}3 \\ -7.5 \\ 4.5\end{bmatrix}$
$B=\begin{bmatrix}5.5 \\ -2.5 \\ 5.5\end{bmatrix}$
$C=\begin{bmatrix}10.5 \\ -5 \\ 5.5\end{bmatrix}$.
I don't know the equation of the scalar product of three three dimensional vectors, but I assume is different than two dimensional vectors. And what does the scalar product of three three dimensional vectors represent ?.
Thanks in advance !.

A: The equation is actually the same: if you have two vectors $\vec{x}, \vec{y} \in \mathbb{R}^n$ then their scalar product is: $$\vec{x}\cdot\vec{y}=\sum_{i=1}^nx_iy_i$$ where $x_i,y_i$ are the components of the vectors.
The geometrical interpretation is the same regardless of the dimension of the space:
if one of your vectors, for instance $\vec{y}$, has lenght one then the product $\vec{x}\cdot\vec{y}$ is the lenght of the (orthogonal) projection of $\vec{x}$ over the line paralell to $\vec{y}$. If $\vec{y}$ has arbitrary lenght then $\vec{x}\cdot\vec{y}$ is the product of the lenght of the projection of  $\vec{x}$ over the line paralell to $\vec{y}$ times the lenght of $\vec{y}$


text:
Q: Obfuscating numbers in a string? I have a challenge that calls for obfuscating numbers in a string, such as a SSN, for example: XXX-XX-4430.  I've gotten pretty close:
def hide_all_ssns(string)
  string.scan(/\w{3}-\w{2}-\w{4}/)
  string.gsub('/\w{3}-\w{2}', 'XXX-XX')
end

but I get an error:
Error! hide_all_ssns obfuscates any SSNs in the string expected:
"XXX-XX-1422, XXX-XX-0744, XXX-XX-8762" got: "234-60-1422,
350-80-0744, 013-60-8762" (using ==)

I initially had the regular-expression (/\d{3}-\d{2}-\d{4}/) but thought that the problem was attempting to convert the integers in the string to X. Now I'm using \w, yet I am getting the same error.
Does anyone have any insight?  I'm a newbie to coding and have exhausted Ruby-doc, as well as any blogs I can find on regex/gsub, but I am getting nowhere.

A: You're mis-using gsub (your regular expression needs to be between forward slashes), but I still thing gsub! is what you want...
def hide_all_ssns(string)
  string.scan(/\w{3}-\w{2}-\w{4}/)
  string.gsub!(/\w{3}-\w{2}/, 'XXX-XX')
end

Working example:
1.9.3p448 :063 > string = "123-45-6789"
 => "123-45-6789"

1.9.3p448 :064 > def hide_all_ssns(string)
1.9.3p448 :065?>   string.scan(/\w{3}-\w{2}-\w{4}/)
1.9.3p448 :066?>   string.gsub!(/\w{3}-\w{2}/, 'XXX-XX')
1.9.3p448 :067?> end
 => nil

1.9.3p448 :068 > hide_all_ssns(string)
 => "XXX-XX-6789"

1.9.3p448 :069 > string
 => "XXX-XX-6789"

A: Why does it have to be so hard? All U.S. social security numbers are the same format, right? So, work from that point. Here's some variations on a theme, ordered by escalating obscurity:
ssn = '123-45-6789'   # => "123-45-6789"
ssn[0, 6] = 'XXX-XX'  # => "XXX-XX"
ssn                   # => "XXX-XX-6789"

Or:
numbers = ssn.scan(/\d+/)  # => ["123", "45", "6789"]
'XXX-XX-' + numbers.last   # => "XXX-XX-6789"

Or:
ssn = '123-45-6789'                    # => "123-45-6789"
ssn[0, 6] = ssn[0, 6].gsub(/\d/, 'X')  # => "XXX-XX"
ssn                                    # => "XXX-XX-6789"

Or:
ssn[0,6] = ssn[0, 6].tr('0-9', 'X')  # => "XXX-XX"
ssn                                  # => "XXX-XX-6789"

Or:
numbers = ssn.split('-')                                         # => ["123", "45", "6789"]
[*numbers[0, 2].map{ |s| 'X' * s.size }, numbers[-1]].join('-')  # => "XXX-XX-6789"

Or:
ssn[/(\d+)-(\d+)-(\d+)/]                                       # => "123-45-6789"
[$1, $2, $3]                                                   # => ["123", "45", "6789"]
[$3, *[$2, $1].map{ |s| s.gsub(/./, 'X') }].reverse.join('-')  # => "XXX-XX-6789"

Of course, using one of these would cheating, since you're supposed to figure the challenge out by yourself, but they're good food for thought and a decent starting point for your own solution.

A: Short and simple... You could maybe try something like this:
crypted = ('X' * 6) + "4543-2329-1354-1111".to_s[14..18]
=> "XXXXXX-1111"


text:
Q: PHP How to explode string using multiple regular expressions? I have a long string consisting of a series of segments separated by a single character ~.
Example:
ST*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~IT1*Any*Characters*are*allowed*here~optional*segment*~IT1*Any*Characters*are*allowed*here~IT1*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~TDS*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~

Notice that this is a single string with no new lines at all. I just formatted it for readability.
The output should be:
Array{
      [0]=>ST*Any*Characters*are*allowed*here~optional*segment*~optional*segment*

      [1]=>Array{
                 [0]=>IT1*Any*Characters*are*allowed*here~optional*segment*
                 [1]=>IT1*Any*Characters*are*allowed*here
                 [2]=>IT1*Any*Characters*are*allowed*here~optional*segment*~optional*segment*
                }

      [2]=>TDS*Any*Characters*are*allowed*here~optional*segment*~optional*segment*
}

How can this output be generated from the input string?
The thing is I can only guarantee that the beginnings of these segments (ST, IT1, TDS) as they are mandatory, but they may be followed by random number of optional segments.
Of course the separator ~ may only occur between segments and not inside them.
UPDATE: I need the string to be exploded into 3 parts:

*

*The string starting from ST till the first occurrence of IT1.

*The collection of strings starting by IT1 and ending by the next IT1.

*The final string starting by TDS till the end of the string.

A: Based on your updated question, I would use preg_split:
$var = '~' . "ST*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~IT1*Any*Characters*are*allowed*here~optional*segment*~IT1*Any*Characters*are*allowed*here~IT1*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~TDS*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~";

$split = preg_split('/~(ST|IT1|TDS)/', $var, -1, PREG_SPLIT_DELIM_CAPTURE);

$blocks = array('ST' => array(), 'IT1' => array(), 'TDS' => array());

for($i = 1; $i < count($split); $i+=2)
{
    $blocks[$split[$i]][] = $split[$i] . $split[$i+1];
}

var_dump($blocks);

Notes:

*

*I prepend ~ to make things easier on the split

*I start $i as 1 because the first split will be empty

Result
array(3) {
  ["ST"]=>
  array(1) {
    [0]=>
    string(70) "ST*Any*Characters*are*allowed*here~optional*segment*~optional*segment*"
  }
  ["IT1"]=>
  array(3) {
    [0]=>
    string(53) "IT1*Any*Characters*are*allowed*here~optional*segment*"
    [1]=>
    string(35) "IT1*Any*Characters*are*allowed*here"
    [2]=>
    string(71) "IT1*Any*Characters*are*allowed*here~optional*segment*~optional*segment*"
  }
  ["TDS"]=>
  array(1) {
    [0]=>
    string(72) "TDS*Any*Characters*are*allowed*here~optional*segment*~optional*segment*~"
  }
}


text:
Q: Java Lombok log4j use different appender How to use different appender just in one class with lombok.
I tried
@Log4j(topic = "myAppender")
@Service("myService")
public class DemoServiceImpl implements DemoService {
  ...
}

And log4j configuration
log4j.rootLogger=INFO, myConsoleAppender

# settings for the console appender
log4j.appender.myConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.myConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.myConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# settings for file appender
log4j.appender.myAppender=org.apache.log4j.FileAppender
log4j.appender.myAppender.File=mylog.log
log4j.appender.myAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.myAppender.layout.ConversionPattern=[%p] %d{DATE} %m%n

So I want to log everything in myConsoleAppender but all logs in DemoServiceImpl class want to save to file - use myApppender from log4j properties file.

A: I just resolved by myself
adding this to log4j properties
log4j.category.myAppenderLogger=INFO, myAppender
log4j.additivity.myAppenderLogger=false

and log4j anontation correction
@Log4j(topic = "myAppenderLogger")
@Service("myService")
public class DemoServiceImpl implements DemoService {
  ...
}


text:
Q: Jquery post - on a PHP include file Problem:
if on the jQuery I leave only the alert (the commented one on line 8) all goes well.
Question: why the post function is not working for the [x] anchor from the item list? see photo below for better understanding of the issue. cassetterecorder-museum.com/poze/explanations.jpg
Need:
I Have a list of items on the include file. Each element has an [x] as anchor to remove the respective item from list.
Note:
the jQuery post script below,meant to remove an item from list works in other cases -on the same site (where an include is not involved)
What should I do to make it work?
PHP file contains:
<?php include('includes/inc_menu_right.php');?>

and on the bottom
1. $("**#delete**").click(function(event) {
2.              $.post("includes/ajax-compare.php",
3.              {  id:'check-rem', cid:$cid },
4.              function(data){
5.                  $("#compare").html(data);
6.                  //alert (data);
7.          });
8.  //alert('adada');
9. });

inc_menu_right.php (extract from it)

        <?php
        // incarcare lista
        echo '
            Lista comparatii
                ';
                if (isset($_SESSION['cid'])) {
                echo count($_SESSION['cid'])."/4";
                } else echo "0/4";
                echo '

            ';
            foreach ($_SESSION['cid'] as $car){
            $q='SELECT * FROM car_tb WHERE c_id="'.$car.'"';
            $res=mysql_query($q);
            foreach($dbo->query($q) as $r){
            echo '

'.$r['c_denumire'].'  [x]

                ';
                }
                }
                echo '

Compara

';
        ?>

Thank you!

A: here is what you would do:
You first want to update your link to have a delete class and set the data-value property to your c_id:
 [x]

Then you want to update your JavaScript to select all ".delete" class elements then retrieve the id from the data-value property using $(this).data('value').
$('.delete').click(function() {
    var params = {
        id:'check-rem',
        cid: $(this).data('value')
    };
    $.post("includes/ajax-compare.php", params, function(data){
        $("#compare").html(data);
    });
    return false;
});


text:
Q: Convert SQL Query to LINQ in ASP.NET MVC I am new to LINQ and I have this query that I made in SQL
DELETE Inscriptions
FROM Inscriptions
INNER JOIN Students on Students.Id = Inscriptions.StudentId
where Inscriptions.StudentId = 149
 DELETE FROM[dbo].Certifications
Where StudentId = 149
DELETE FROM[dbo].Students
WHERE Id = 149

How can I convert this to LINQ ?

A: This code will be helpful to you,
YourDBDataContext db = new YourDBDataContext();

List<Inscriptions> inList = db.Inscriptions.Join(db.Students, ins => ins.StudentId,
                            std => std.Id, (ins, std) => new { ins, std }).
                            Where(x => x.ins.StudentId == 149).Select(x => x.ins).ToList();

db.Inscriptions.RemoveRange(inList);
db.SaveChanges();

Same coding style can be used for other delete query as well.


text:
Q: CUDA/C - Using malloc in kernel functions gives strange results I'm new to CUDA/C and new to stack overflow. This is my first question.
I'm trying to allocate memory dynamically in a kernel function, but the results are unexpected.
I read using malloc() in a kernel can lower performance a lot, but I need it anyway so I first tried with a simple int ** array just to test the possibility, then I'll actually need to allocate more complex structs.
In my main I used cudaMalloc() to allocate the space for the array of int *, and then I used malloc() for every thread in the kernel function to allocate the array for every index of the outer array. I then used another thread to check the result, but it doesn't always work.
Here's main code:
#define N_CELLE 1024*2
#define L_CELLE 512

extern "C" {

int main(int argc, char **argv) {
  int *result = (int *)malloc(sizeof(int));
  int *d_result;
  int size_numbers = N_CELLE * sizeof(int *);
  int **d_numbers;

  cudaMalloc((void **)&d_numbers, size_numbers);
  cudaMalloc((void **)&d_result, sizeof(int *));

  kernel_one<<<2, 1024>>>(d_numbers);
  cudaDeviceSynchronize();
  kernel_two<<<1, 1>>>(d_numbers, d_result);

  cudaMemcpy(result, d_result, sizeof(int), cudaMemcpyDeviceToHost);

  printf("%d\n", *result);

  cudaFree(d_numbers);
  cudaFree(d_result);
  free(result);
}

}

I used extern "C"because I could't compile while importing my header, which is not used in this example code. I pasted it since I don't know if this may be relevant or not.
This is kernel_one code:
__global__ void kernel_one(int **d_numbers) {
  int i = threadIdx.x + blockIdx.x * blockDim.x;
  d_numbers[i] = (int *)malloc(L_CELLE*sizeof(int));
  for(int j=0; j<L_CELLE;j++)
    d_numbers[i][j] = 1;
}

And this is kernel_two code:
__global__ void kernel_two(int **d_numbers, int *d_result) {
  int temp = 0;
  for(int i=0; i<N_CELLE; i++) {
    for(int j=0; j<L_CELLE;j++)
      temp += d_numbers[i][j];
  }
  *d_result = temp;
}

Everything works fine (aka the count is correct) until I use less than 1024*2*512 total blocks in device memory. For example, if I #define N_CELLE 1024*4 the program starts giving "random" results, such as negative numbers.
Any idea of what the problem could be?
Thanks anyone!

A: In-kernel memory allocation draws memory from a statically allocated runtime heap. At larger sizes, you are exceeding the size of that heap and then your two kernels are attempting to read and write from uninitialised memory. This produces a runtime error on the device and renders the results invalid.  You would already know this if you either added correct API error checking on the host side, or ran your code with the  cuda-memcheck utility.
The solution is to ensure that the heap size is set to something appropriate before trying to run a kernel. Adding something like this:
 size_t heapsize = sizeof(int) * size_t(N_CELLE) * size_t(2*L_CELLE);
 cudaDeviceSetLimit(cudaLimitMallocHeapSize, heapsize);

to your host code before any other API calls, should solve the problem.

A: I don't know anything about CUDA but these are severe bugs:

*

*You cannot convert from int** to void**. They are not compatible types. Casting doesn't solve the problem, but hides it.

*&d_numbers gives the address of a pointer to pointer which is wrong. It is of type int***.

Both of the above bugs result in undefined behavior. If your program somehow seems to works in some condition, that's just by pure (bad) luck only.


text:
Q: Memory Leak in my C program The following code is working, but I am getting a memory leak.
The program is using linked list and dynamic memory function.
The Program excepts a .txt file as a command line argument.
Example file:

Jacob Miller 832323244 21
  Tom Darren 8931701830 19
  Paul Mitchell 329797231 20
  Here the output from Valgrind

==5742== HEAP SUMMARY:
==5742==     in use at exit: 324 bytes in 9 blocks
==5742==   total heap usage: 11 allocs, 2 frees, 908 bytes allocated
==5742==
==5742== 52 bytes in 1 blocks are definitely lost in loss record 2 of 4
==5742==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==5742==    by 0x400A2C: student_record_allocate (new.c:106)
==5742==    by 0x4007EB: main (new.c:46)
==5742==
==5742== 272 (16 direct, 256 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4
==5742==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==5742==    by 0x400A1E: student_record_allocate (new.c:104)
==5742==    by 0x4008D1: parseFile (new.c:74)
==5742==    by 0x400803: main (new.c:47)
==5742==
==5742== LEAK SUMMARY:
==5742==    definitely lost: 68 bytes in 2 blocks
==5742==    indirectly lost: 256 bytes in 7 blocks
==5742==      possibly lost: 0 bytes in 0 blocks
==5742==    still reachable: 0 bytes in 0 blocks
==5742==         suppressed: 0 bytes in 0 blocks
==5742==
==5742== For counts of detected and suppressed errors, rerun with: -v
==5742== ERROR SUMMARY: 66 errors from 21 contexts (suppressed: 4 from 4)

There is some problem here code snippet.

    void parseFile(char* filename, struct student_record_node** head)
    {
    FILE *fp;
    student_record_node *sn;

    fp = fopen(filename, "r");
    if (!fp) {
        fprintf(stderr, "Can't Open file %s\n", filename);
        exit(EXIT_FAILURE);
    }

    while(!feof(fp)) {
        sn = student_record_allocate();

        fscanf(fp, "%20s", sn->record_->first_name_);
        fscanf(fp, "%20s", sn->record_->last_name_);
        fscanf(fp, "%d", &(sn->record_->student_id_));
        fscanf(fp, "%d", &(sn->record_->student_age_));

        appendNode(*head, sn);
    }

    fclose(fp);
    }

    void printNode(struct student_record_node* node)
    {
        printf("\nstruct student_record_node:\n");
        if (node) {
        printf("\tstudent first name: %s\n",node->record_->first_name_);
        printf("\tstudent second name: %s\n",node->record_->last_name_);
        printf("\tstudent id: %d\n", node->record_->student_id_);
        printf("\tstudent age: %d", node->record_->student_age_);

    }
    }

    struct student_record_node* student_record_allocate()
    {
    student_record_node *newNode=NULL;
    student_record *newRecord=NULL;

    newNode = (student_record_node *)malloc(sizeof(student_record_node));
    newRecord = (student_record *)malloc(sizeof(student_record));
    newNode->record_ = newRecord;
    newNode->next_ = NULL;

    return newNode;
    free(newNode->record_);
    }

    {
        free(node->record_);
    free(node->next_);

    }

I am freeing the above through this method
    void freeNodeList(struct student_record_node* head)
    {
    student_record_node *tmp;
     while(tmp != NULL) {
     tmp=head;
     head=head->next_;
     free(tmp);
    }
    head=NULL;
    }

Here is my full code

 #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    struct student_record
    {
    int student_id_;
    int student_age_;
    char first_name_[21];
    char last_name_[21];
    }s;

    struct student_record_node
    {
    struct student_record* record_;
    struct student_record_node* next_;
    };
    typedef struct student_record student_record;
    typedef struct student_record_node student_record_node;

    void parseFile(char* filename, struct student_record_node** head);
    void printNode(struct student_record_node* node);
    struct student_record_node* student_record_allocate();
    void student_record_node_deallocate(struct student_record_node* node);
    void sortByAge(struct student_record_node** recordsHead);
    void sortById(struct student_record_node** recordsHead);
    void swap(struct student_record_node** node1, struct student_record_node** node2);
    void freeNodeList(struct student_record_node* head);
    void appendNode(struct student_record_node* head, struct student_record_node* newNode);
    void printNodeList(struct student_record_node* head);
    int main(int argc, char **argv)
    {
    student_record_node *head;
    if (argc != 2) {
        fprintf(stderr, "Error: expected input file");
        exit(EXIT_FAILURE);
    }
    /*  student_record *newRecord=NULL;
    recordsHead->record_ = newRecord;
    recordsHead->next_ = NULL;
    */
    head = student_record_allocate();
    parseFile(argv[1], &head);
    printf("Before sorting...");
    printNodeList(head);
    printf("Sorting by age...");
    sortByAge(&head);
    printNodeList(head);
    printf("Sorting by id...");
    sortById(&head);
    printNodeList(head);
    freeNodeList(head);
    free(head);

    return 0;
    }

    void parseFile(char* filename, struct student_record_node** head)
    {
    FILE *fp;
    student_record_node *sn;

    fp = fopen(filename, "r");
    if (!fp) {
        fprintf(stderr, "Can't Open file %s\n", filename);
        exit(EXIT_FAILURE);
    }

    while(!feof(fp)) {
        sn = student_record_allocate();

        fscanf(fp, "%20s", sn->record_->first_name_);
        fscanf(fp, "%20s", sn->record_->last_name_);
        fscanf(fp, "%d", &(sn->record_->student_id_));
        fscanf(fp, "%d", &(sn->record_->student_age_));

        appendNode(*head, sn);
    }

    fclose(fp);
    }

    void printNode(struct student_record_node* node)
    {
        printf("\nstruct student_record_node:\n");
        if (node) {
        printf("\tstudent first name: %s\n",node->record_->first_name_);
        printf("\tstudent second name: %s\n",node->record_->last_name_);
        printf("\tstudent id: %d\n", node->record_->student_id_);
        printf("\tstudent age: %d", node->record_->student_age_);

    }
    }

    struct student_record_node* student_record_allocate()
    {
    student_record_node *newNode=NULL;
    student_record *newRecord=NULL;

    newNode = (student_record_node *)malloc(sizeof(student_record_node));
    newRecord = (student_record *)malloc(sizeof(student_record));
    newNode->record_ = newRecord;
    newNode->next_ = NULL;

    return newNode;
    free(newNode->record_);
    }

    {
        free(node->record_);
    free(node->next_);

    }

    void sortByAge(struct student_record_node **recordsHead)
    {
    int swapped, i;
    struct student_record_node *ptr1;
    struct student_record_node *lptr = NULL;

    do
    {
        swapped = 0;
        ptr1 = *recordsHead;

        while (ptr1->next_ != lptr)
        {
            if (ptr1->record_->student_age_ > ptr1->next_->record_->student_age_)
            {
                swap(&ptr1, &ptr1->next_);
                swapped = 1;
            }
            ptr1 = ptr1->next_;
        }
        lptr = ptr1;
    }
    while (swapped);
    }

    void sortById(struct student_record_node** recordsHead)
    {
    int swapped, i;
    struct student_record_node *ptr1;
    struct student_record_node *lptr = NULL;

    do
    {
        swapped = 0;
        ptr1 = *recordsHead;

        while (ptr1->next_ != lptr)
        {
            if (ptr1->record_->student_id_ > ptr1->next_->record_->student_id_)
            {
                swap(&ptr1, &ptr1->next_);
                swapped = 1;
            }
            ptr1 = ptr1->next_;
        }
        lptr = ptr1;
    }
    while (swapped);
    }

    void swap(struct student_record_node** node1, struct student_record_node** node2)
    {
    student_record_node *tmp, *n1, *n2;

    n1 = *node1;
    n2 = *node2;
    tmp->record_= n1->record_;
    n1->record_= n2->record_;
    n2->record_ = tmp->record_;

    }

    void freeNodeList(struct student_record_node* head)
    {
    student_record_node *tmp;
     while(tmp != NULL) {
     tmp=head;
     head=head->next_;
     free(tmp);
    }
    head=NULL;
    }

    void appendNode(struct student_record_node* head, struct
    student_record_node* newNode)
    {
    student_record_node *prev, *next;

    if(head == NULL) {
        head = newNode;
        return;
    }

    next = head;
    while(next != NULL) {
        prev = next;
        next = next->next_;
    }
    prev->next_ = newNode;
    }

    void printNodeList(struct student_record_node* head)
    {
    student_record_node *tmp = head;

    while(tmp != NULL) {
        tmp = tmp->next_;
        printNode(tmp);
    }

    }

A: This code does not initialize tmp:
void freeNodeList(struct student_record_node* head) {
    student_record_node *tmp;
    while(tmp != NULL) {
        tmp=head;
        head=head->next_;
        free(tmp);
    }
    head=NULL;
}

Consequently, you have undefined behavior when reading from an uninitialized variable.
You probably meant to use head != NULL as your while condition.

A: In freeNodeList, you only free the student record nodes, not the student records they contain, which means all of the records are still allocated at the end of your program, though they're unreachable since you destroyed the list.


text:
Q: Calling Alchemy API using ajax call I am trying to use ajax to call the Alchemy REST API, but I am getting an injector error which I have mentioned below. The following is the code in my HTML file. Looking for suggestions to solve the error.
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>

Alchemy trial

I am getting the following error in the console :-
[21:39:07.317] Error: [$injector:unpr] http://errors.angularjs.org/undefined/$injector/unpr?p0=AngularIssuesProvider%20%3C-%20AngularIssues
L/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6
Xb/l.$injector<@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:32
c@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:29
Xb/r.$injector<@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:32
c@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:29
d@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:30
Xb/f/<.instantiate@https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0

A: It might be that AlchemyAPI returns multiple CORS headers like this:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: *

Which is actually interpreted in the browser like this:
Access-Control-Allow-Origin: *, *

Which is invalid per the standard, and improperly interpreted by the browser.
That aside, you probably shouldn't be hitting AlchemyAPI directly.  Instead, you should be using a web server to proxy the API calls, and hitting that server with AJAX.  By putting the AJAX call to the API client-side, you're giving out your key to any person or device that uses it, and now, you've given it to anyone that views this question on Stack Exchange.


text:
Q: Display special page if website server is down. Is there a way to do this without nginx proxy? I want to display beautiful page (with excuses) to the users if my webserver is down.
How it is possible?
My first idea was to make VM in cloud and to setup nginx there, which will check if webserver is available, and display beautiful error page if it's not.
Is there another way to perform it (without nginx proxy)? (Maybe some magic with dns.. i don't know)
Thanks in advance!

A: With proxy, when you site is up, all traffic will pass through that proxy. Now, what will you do when the proxy is down ? - While trying to handle one point of failure you just introduce an additional one. Also, you site response time will be lower, and you will pay three times for your traffic (your website, VPS in and VPS out). Hence, proxy idea alone makes little sense.
What you can do is when your site is down, point DNS records for your site to some other location (like your VPS). You will need DNS provider which supports dynamic updates.
You may also have such DNS-based failover completely as a service - see dnshat.com, edgedirector.com and lots of others.


text:
Q: Symfony2 validation filters In my Symfony 2 application I need to filter input before passing it on to validation [1], however, I can't seem to find any system within Symfony to do this.
The type of filtering I looking for is e.g. to be able to filter a dash out of a specific field before validating it. E.g. users can enter 123-123 but the only accepted value is 123123. Just as I can set up validation rules with constraints, I'm looking for something similar for filters.
[1] http://symfony.com/doc/current/book/validation.html

A: Nifr's answer is good but is missing of an important alternative that, if I understand correctly your question, seems to fit perfectly your needs.
You can use a hook that is pretty much an event listener: if something happens or is going to happen, it intercepts the event and redirect it to your function.
In this case, you need a PRE_BIND hook (is deprecated since 2.3 version, now it's called PRE_SUBMIT)
Read this if you need help about

A: Either write your own Validation Assert to filter and then proxy the other validators for this purpose ...
... or one or multiple Regex Asserts.
... or use a DataTransformer to transform/filter the input.
With the DataTransformer involved you could aswell consider creating a new FieldType which renders two inputs with a seperator like the date form-field does. ( if not not used with widget => single_text )


text:
Q: HTML - Can't resize video properly I'm trying to do pretty simple thing: resize video to 100% of screen width and 100% of screen height. However, when I set width to 100%, height seems to be automatically adjusted.
Here is my HTML:
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles/index.css">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="screen_container">
            <video autoplay="autoplay" class="cover_vid" loop>
                <source src="videos/boats.mp4" type="video/mp4" />
            </video>
            <input type="button" id="back_abt" class="gen_design" value="Leave">
        </div>
        <script src="scripts/specific1.js"></script>
    </body>
</html>

CSS:
#screen_container
{
    width:100%;
    height:100%;
    position:absolute;
    left:0;
    top:0;
}

.cover_vid
{
    width:100%;
    height:100%;
    position:absolute;
    left:0;
    top:0;
}

I'm trying to avoid using JavaScript if possible. I even tried passing screen resolution from PHP to width and height attribute of video element, but result was the same. Video seems to do whatever it wants.

A: My understanding is that video will maintain aspect ratio. You specify the width and set the height to auto.
An exception would be iframe elements. Here you should specify width and height (or it will use a default height of 150px)

Try this link for some additional information: https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php


text:
Q: MongoDB with spark gives null values in Dataframe I am trying to connect to mongoDB using spark. When I try to read the data from MongoDB by inferring the schema automatically I see all the values.
However I face issues when I try to explicitly specify the schema and when try to see the values in Dataset it gives me nulls.
I am using Java  and created java class to define the schema.
Please could someone help me troubleshoot the issue

below the code snippet :-

    public class MVTest {

    public static void main(final String[] args) throws InterruptedException {

        SparkSession spark = SparkSession.builder().appName("Test")
                 .master("local[2]")
         .config("spark.mongodb.input.uri", "mongodb://localhost/mongoFocusDump.PositionResultDocuments")
         .config("spark.mongodb.output.uri","mongodb://localhost/mongoFocusDump.PositionResultDocuments").getOrCreate();

        JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());

            Dataset<MongoSchema> df = MongoSpark.load(jsc).toDS(MongoSchema.class);

        df.printSchema();

        df.select("simulationScenario").show();
       jsc.close();
    }
}

Output :-

+------------------+
|simulationScenario|
+------------------+
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
|              null|
+------------------+


text:
Q: is serializer necessary in Django RestFramework when operating with external db I have requirement where in, I am suppose to build REST API, Database that i have to use is MongoDB and is not a part of the current Django project, it is managed and handled by some other team.
For current Django project, I use MySQL. below is how i write API's with current Django project with MySQL
views.py
class UserViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

serilaizers.py
class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'

but for MongoDB new requirement, i use PyMongo to interact with MongoDB
views.py
import pymongo

class EmpViewSet(viewsets.ViewSet):

    def list(self, request):
        myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = myclient["external_database"]
        mycol = mydb["employee"]

        result = mycol.find_one({'emp_id': 123})
        return Response({"result": result}, status=status.HTTP_200_OK)

it is working fine with above code(it is not the exact code, similar implemention).
i need to do all CRUD operation on MongoDB. I am unaware that serialzers is needed for this or not?
if needed then, how will i write the serializer for it, since the result from the MongoDB query may give dynamic schema.
any help will be greatly appreciated!
Thanks in advance!
got the answer here
Can I drop Serializers from DRF completely?
will go without serializers.

A: You should use django-mongodb-engine or similar to allow ORM to communicate to the DB so that you can reap the benefits of the django magic. Otherwise you should manually create helper_functions and subclass serializers to add your own custom logic to them.


text:
Q: Using Java 8 Stream Reduce to return List after performing operation on each element using previous elements values I'm new to Streams and Reduce so I'm trying it out and have hit a problem:
I have a list of counters which have a start counter and end counter. The startcounter of an item is always the endcounter of the previous. I have a list of these counters listItems which I want to loop through efficiently, filter out inactive records and then reduce the list into a new List where all the StartCounters are set. I have the following code:
List<CounterChain> active = listItems.stream()
                .filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
                .reduce(new ArrayList<CounterChain>(), (a,b) -> { b.setStartCounter(a.getEndCounter()); return b; });

But it doesn't really work and I'm kind of stuck, can anyone give me a few suggestions to help me get this working? Or is there an equally efficient better way to do this? Thanks!

A: A Reduction reduces all elements to a single value. Using a reduction function of the (a,b) -> b form will reduce all elements to the last one, so it's not appropriate when you want to get a List containing all (matching) elements.
Besides that, you are performing a modification of the input value, which is violating the contract of that operation. Note further, that the function is required to be associative, i.e. it shouldn't matter whether the stream will perform f(f(e₁,e₂),e₃)) or f(e₁,f(e₂,e₃)) when processing three subsequent stream elements with your reduction function.
Or, to put it in one line, you are not using the right tool for the job.
The cleanest solution is not to mix these unrelated operations:
List<CounterChain> active = listItems.stream()
    .filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
    .collect(Collectors.toList());
for(int ix=1, num=active.size(); ix<num; ix++)
    active.get(ix).setStartCounter(active.get(ix-1).getEndCounter());

The second loop could also be implemented using forEach, but it would require an inner class due to its stateful nature:
active.forEach(new Consumer<CounterChain>() {
    CounterChain last;
    public void accept(CounterChain next) {
        if(last!=null) next.setStartCounter(last.getEndCounter());
        last = next;
    }
});

Or, using an index based stream:
IntStream.range(1, active.size())
    .forEach(ix -> active.get(ix).setStartCounter(active.get(ix-1).getEndCounter()));

But neither has much advantage over a plain for loop.

A: although the solution with plain for loop provided by @Holger is good enough, I would like to recommend you try third-party library for this kind of common issues. for example: StreamEx or JOOL. Here is solution by StreamEx.
StreamEx.of(listItems).filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
        .scanLeft((a,b) -> { b.setStartCounter(a.getEndCounter()); return b; });


text:
Q: What is the difference between AopTestUtils and AopProxyUtils? What is the difference between AopTestUtils and AopProxyUtils?
As far as I understand, AopTestUtils calls AopProxyUtils.
But I didn't understand why it was needed then?
In which cases what should I use. I will be glad to have a detailed answer

A: AopTestUtils
It is a collection of AOP-related utility methods for use in unit and integration testing scenarios.

AopProxyUtils
It provides utility methods for AOP proxy factories. Mainly for internal use within the AOP framework.
For more detailed information you can refer to the documentation
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/AopTestUtils.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/framework/AopProxyUtils.html


text:
Q: Panorama Solution for a Camera Application Is there a panorama open-source solution for the Android camera app?
I came across these options:

*

*panoramagl-android

*WideAnglePanoramaModule.java
but they look a little old and have no support, is there anything newer?
I also came across this page:
But there is not much documentation about it that I could find.
I would like to get a full solution including capturing the images, stitching and displaying.

A: Look at this article:
https://itnext.io/android-360-panorama-cedbfb47a9e
The thing that i dont like is that all images are from assets. I did it with image from firebase:
add dependancy:
  dependencies {
  /*
  * Google VR SDK
  * Release version: https://github.com/googlevr/gvr-android-sdk/releases
  * */
  implementation 'com.google.vr:sdk-panowidget:1.180.0'
  implementation 'com.github.silvestrpredko:dot-progress-bar:1.1'
  }

add class
public class SimpleVrPanoramaActivity extends Activity {

@BindView(R.id.progressBar2)
DotProgressBar dotProgressBar;

@BindView(R.id.pano_view)
VrPanoramaView panoWidgetView;

private String bar_panorama1;
private String mPost_key = null;
private Bitmap[] bitmaps = new Bitmap[1];
private DatabaseReference databaseReference;
private VrPanoramaView.Options panoOptions = new VrPanoramaView.Options();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_panorama);

    ButterKnife.bind(this);

    if (getIntent().getExtras() != null) {
        mPost_key = getIntent().getExtras().getString("bar_id");
    }

    panoOptions.inputType = VrPanoramaView.Options.TYPE_MONO;

    databaseReference = FirebaseDatabase.getInstance().getReference().child("bars").child(mPost_key).child("pano");

    fetchPanorama();
}

private void fetchPanorama() {

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            bar_panorama1 = dataSnapshot.child("i1").getValue(String.class);

            glideImage(bar_panorama1);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            Toast.makeText(SimpleVrPanoramaActivity.this, "Проверьте подключение к интернету!", Toast.LENGTH_LONG).show();
        }
    });
}

public void glideImage(String bar_panorama) {

    Glide.with(SimpleVrPanoramaActivity.this)
            .asBitmap()
            .load(bar_panorama)
            .into(new CustomTarget<Bitmap>() {
                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {

                    dotProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                    bitmaps[0] = resource;

                    panoWidgetView.loadImageFromBitmap(bitmaps[0], panoOptions);

                    dotProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {
                }
            });
}

@Override
protected void onPause() {
    panoWidgetView.pauseRendering();
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    panoWidgetView.resumeRendering();
}

@Override
protected void onDestroy() {
    // Destroy the widget and free memory.
    panoWidgetView.shutdown();

    super.onDestroy();
}

}

add xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/colorPrimary"
tools:context=".aktau.panorama.PanoramaGLActivity">

<include
    android:id="@+id/toolbar_pano"
    layout="@layout/toolbar_pano"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" />

<View
    android:id="@+id/yellow_layer"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/colorOrange"
    android:layout_below="@+id/toolbar_pano"
     />

<com.google.vr.sdk.widgets.pano.VrPanoramaView
    android:id="@+id/pano_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/yellow_layer"/>

<com.github.silvestrpredko.dotprogressbar.DotProgressBar
    android:id="@+id/progressBar2"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:layout_below="@+id/toolbar_pano"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="0dp"
    android:layout_marginBottom="0dp"
    app:amount="3"
    android:layout_centerHorizontal="true"
    app:animationDirection="right"
    app:duration="@android:integer/config_shortAnimTime"
    app:endColor="@color/colorPrimaryDark"
    app:startColor="@color/colorLightBlue" />

</RelativeLayout>


text:
Q: How to properly update user information in firebase? I have a code that is a form, basically is suppose to update the user information.
According to Firebase documentation manage user but for some reason I'm getting this errors

This is what I have I don't think I'm missing anything is pretty much the same
The only difference is that on my firebase.js I made new cons to make codes shorter but that shouldn't affect at all.
firebase.js
const db = firebase.firestore();
const auth = firebase.auth();
const storage = firebase.storage();

export {db, auth, storage};

Code
import {auth} from "./firebase"

const authUser = auth.currentUser
    const update = (e) => {
        e.preventDefault();
        authUser.updateProfile({
                displayName: {fullName}
        })
    }

I just wanted to test it on the user name first and then do all the others but I don't understand why is not working is super simple.
Update

A: authUser is undefined. This means that auth.currentUser was undefined at the time when it was assigned to authUser. This probably means that the user is not logged in. You will need to handle the case when the user is not logged in, like
import {auth} from "./firebase"

const authUser = auth.currentUser
    const update = (e) => {
        e.preventDefault();

        if (authUser) {
            authUser.updateProfile({
                displayName: fullName
            })
        } else {
            //User is not logged in, handle that case here
        }
    }

A: import {auth} from "./firebase";
const authUser = auth.currentUser;
const update = (e) => {
    e.preventDefault();
    authUser?.updateProfile({
        displayName: fullName
    });
}


text:
Q: Reduce degree of each vertex by at least $1$ but keep minimum degree large? Let $G=(V,E)$ be a graph with minimum degree $\delta_G>10$.
Can we always remove some edges to get a graph $G'$ with minimum degree at least $\delta/2$, but $\deg_{G'}(v) \leq \deg_{G}(v)-1$ for all $v\in V$?
This is not an exercise problem, but it was motivated from an exercise problem, in Chapter 1 of Alon and Spercer's The Probabilistic Methods.
I guess I am supposed to show what I have tried, but sadly I have little idea on how to start... Any hints or reference will be good.

A: The following will do what you ask if $G$ has minimum degree $\delta(G)\ge4.$
Theorem. Given a graph $G$ with no isolated vertices, we can find a spanning subgraph $H,$ with minimum degree $\delta(H)\ge\delta(G)-2,$ such that $\deg_H(v)\lt\deg_G(v)$ for each vertex $v.$
Proof. Let $\delta=\delta(G).$ First, suppose $G$ is $\delta$-regular. By Vizing's theorem, $G$ has a proper edge coloring with $\delta+1$ colors. Choose such a coloring, and then remove all edges of two chosen colors, resulting in a spanning subgraph $H.$ Since each vertex is incident with one or two edges of the chosen colors, $H$ has the desired properties.
Now suppose $G$ has vertices of degree greater than $\delta.$ Let $v$ be such a vertex. Choose some edge incident with $v,$ say $e=uv,$ and temporarily detach it from $v,$ leaving it attached to $u.$ (If you don't like half-edges, create a new vertex $v'$ and replace the edge $uv$ with $uv'.$) Repeat this procedure as needed, until there are no vertices of degree greater than $\delta.$ Now apply Vizing's theorem as before, to get a proper edge coloring with $\delta+1$ colors; then restore the graph to its original state and remove all edges of two chosen colors.


text:
Q: Detecting the visitor's browser by JAVASCRIPT or PHP? I am curious to know if detecting the visitor browser with client-side script is more reliable than server-side script?
It is easy and popular to get the visitor browser both by PHP and Javascript. In the former one, we analyze $_SERVER['HTTP_USER_AGENT'] sent by the header array. However, header is not always reliable. Can Javascript be more reliable as it get the visitor browser from the visitor's machine?
I mean is it possible to miss the USER AGENT in header and get the browser by javascript?
UPDATE: Please do not introduce methods such as jQuery as I am familiar with them. I just want to know if it's possible for header's user agent to fail when javascript still can detect browser? Comparison of client-side and server-side methods.

A: The User-Agent can be tested server side or client side, either way it can be spoofed.
You can finger print the browser with JavaScript (seeing what methods and objects the browser provides) and use that to infer the browser, but that is less precise and JavaScript can be disabled / blocked / edited by the client.
So neither is entirely reliable.
It is generally a bad idea to do anything based on the identify of the browser though.

A: OK. So User-Agent header is not required by RFC

User agents SHOULD include this field with requests.

https://www.rfc-editor.org/rfc/rfc2616#section-14.43
Which means the server side detection is not guaranteed.
Similarly client side detection typically relies on navigator.userAgent but that is also provided by the user agent (browser or what not) and similarly cannot be guaranteed.
Thus the answer to your question is 50/50 :)
Now, if you are trying to figure out how to handle different browsers - feature detection is your safest bet here - but that's a different question ;)

A: I would just use the server side detection.
If a user wants to mask their browser, their browser will likely be masked on both ends.
If you want to find out their browser for HTML compatibility, they should be expecting mildly broken pages if they've masked their browser (but you should always try your best not to have browser specific HTML). If it's for javascript compatibility, they should also be expecting some broken javascript.

A: Take a look at $.browser() in jquery

A: A different angle: why do we want to detect the browser?
In the case of analytics, there isn't much you can do really. Anyone that does a little research can send whatever user agent string they like, but who's going to go through all the trouble ;)
If we're talking about features to enable/disable on a website, you should really be going for feature detection. By focusing on what the browser can/can't do, instead of what it calls itself, you can generally expect that browser to perform whatever action reliably if the feature you need is present.
More info: http://jibbering.com/faq/notes/detect-browser/

A: One big advantage to use client-side javascript is that you can get much more information about the browser.
Here is an interesting example: https://panopticlick.eff.org/


text:
Q: Converting "-" to a "0" in R I have a column Apps in dataframe dframe
that looks like this:
    Apps
1    31
2    12
3    10
4    33
5    -

I need the column to be type int instead of String so I need to convert the 5th row to a 0.
    Apps
1    31
2    12
3    10
4    33
5    0

A: dframe$Apps[dframe$Apps == "-"] <- "0"
dframe$Apps <- as.integer(dframe$Apps)

A: You can do it with ifelse and the tidyverse approach:
require(tidyverse)

df %>%
  mutate(Apps = ifelse(Apps == "-", 0, Apps))

  Apps
1    4
2    3
3    2
4    5
5    0

Dataset:
df <- read.table(text = "    Apps
1    31
2    12
3    10
4    33
5    -", header = TRUE)

A: dframe$Apps <- as.integer(gsub("-", "0", dframe$Apps, fixed = TRUE))

will give you an integer column as I suspect you want.


text:
Q: Maier's theorem I have some questions with Maier's theorem

*

*If $1 < \lambda < 2$, then what?

*If $x+(\log x)^\lambda = x^{1+1/\pi(x)}$, then what?

*In particular, if $\lambda = 0.525\log x/(\log\log x)$, then what?
(see
A result, due to Baker, Harman and Pintz in 2001, shows that θ may be taken to be 0.525. )


text:
Q: How do I check if a class is in included in the manifest classpath? I have some jars being referenced by classpath JVM arg (-cp) and other referenced by a pathing jar that includes additional jars via a Manifest file.
At runtime, how can I check the presence of a class  that scans the -cp jars as well as those referenced by the pathing jar? This is required for some initialization task that scans classes for a particular annotation.

A: try {
    Class.forName("com.some.Class");
}
catch (ClassNotFoundException e) {
    // Specified class not found
}

Note, from the Class.forName documentation:

A call to forName("X") causes the class named X to be initialized.


text:
Q: Datastax DSE 5.0.x broken behavior on detecting existing vertex by Text() property value when a search index exists on that field Hi I made this failing Test - I have set the mode to be Production and allow_scans to true. I have also set a materialized index and a search index on property value:
schema.propertyKey("value").Text().create()
schema.vertexLabel("Number").properties("value").create()
schema.vertexLabel('Number').index('byValue').materialized().by('value').add()
schema.vertexLabel('Number').index('search').search().by('value').asString().add()

I am using DSE 5.0.7 with
<dependency>
   <groupId>com.datastax.dse</groupId>
   <artifactId>dse-java-driver-graph</artifactId>
   <version>1.2.3</version>
</dependency>

public class DatastaxTransactionTest {

    private GraphTraversalSource g;

    public GraphTraversalSource getGraph() {
        DseCluster dseCluster = DseCluster.builder()
                .addContactPoint("192.168.1.24")
                .build();

        DseSession dseSession = dseCluster.connect();
        return DseGraph.traversal(dseSession, new GraphOptions().setGraphName("test"));
    }

    @Before
    public void setUp() {
        g = getGraph();
        g.V().drop().iterate();
    }

    @After
    public void clean() {
        g.V().drop().iterate();
    }

    @Test
    public void testTransactions() {
        GraphTraversalSource g = getGraph();
        g.V().drop().iterate();
        for (int i=0; i<100; i++) {
            boolean exists = g.V().has("Number", "value", "32").count().next().intValue() > 0;
            // this works: boolean exists = g.V().count().next().intValue() > 0;
            if (!exists) {
                g.addV("Number").property("value","32").next();
                report();
            }
        }
        Assert.assertEquals(1, g.V().count().next().intValue()); //this is 100
        Assert.assertEquals(1, g.V().has("Number", "value", "32").count().next().intValue()); // this is 0!!
    }

    public void report() {
        int vCount = g.V().count().next().intValue();
        int numberCount = g.V().hasLabel("Number").count().next().intValue();
        int number32Count = g.V().has("Number", "value", "32").count().next().intValue();
        System.out.println("added Number (Total Vs: "+vCount+ ", Number Vs: "+numberCount + ", Number 32 Vs: "+number32Count );
    }
}

This is trying to insert a Number vertex only if it doesn't exist.. existence over pure count of vertices works fine but doesn't work through indices.. I had huge problems on some of my tests that they were passing only through debugging but not run.. It is as if the indices are not bound to transaction but are eventually updated sometime later.. if that is the case it is a very bad behavior..
Here is the output:
added Number (Total Vs: 1, Number Vs: 1, Number 32 Vs: 0
added Number (Total Vs: 2, Number Vs: 2, Number 32 Vs: 0
added Number (Total Vs: 3, Number Vs: 3, Number 32 Vs: 0
added Number (Total Vs: 4, Number Vs: 4, Number 32 Vs: 0
added Number (Total Vs: 5, Number Vs: 5, Number 32 Vs: 0
added Number (Total Vs: 6, Number Vs: 6, Number 32 Vs: 0
[...]
added Number (Total Vs: 97, Number Vs: 97, Number 32 Vs: 0
added Number (Total Vs: 98, Number Vs: 98, Number 32 Vs: 0
added Number (Total Vs: 99, Number Vs: 99, Number 32 Vs: 0
added Number (Total Vs: 100, Number Vs: 100, Number 32 Vs: 0

java.lang.AssertionError:
Expected :1
Actual   :100
 <Click to see difference>

    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:645)
    at org.junit.Assert.assertEquals(Assert.java:631)
    at com.xxxx.DatastaxTransactionTest.testTransactions(DatastaxTransactionTest.java:53)
[...]

Thanks!


text:
Q: How should I get ALAssetURL by UIImagePickerController delegate? When I use an ImagePicker by sourceType.camera, I want to get AssetUrl in order to get a PHAsset object. I called Info[UIImagePickerControllerReferenceURL], but it's always nil. Is there any way to resolve this? or some other ways replaced? I use Xcode 8.3 and Swift 3.1
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    //
    if info[UIImagePickerControllerReferenceURL] != nil{
        let imageAssetUrl: URL = (info[UIImagePickerControllerReferenceURL] as? URL)!
        print("\(imageAssetUrl)")

        let allPhotosOptions = PHFetchOptions()
        // sort by create
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        //OriginalImage
        allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

        let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [imageAssetUrl], options: allPhotosOptions)

        if fetchResult.count > 0 {

            let asset = fetchResult.firstObject

        }
    }

    picker.dismiss(animated: true) {
        //
    }
}


text:
Q: Numbered list in Winter Bash blog post isn't working correctly The list at the bottom of the Winter Bash blog post has four steps, all numbered 1.:

Whether you're new to Winter Bash or need a quick refresher, here's how it works:
1. Ask, answer, vote, edit, and chat to unlock fun hats and accessories you can wear on your avatar when you complete challenges on participating sites.
1. Once you complete a challenge, a hat will appear on your profile.
...


text:
Q: Desarrollo de clases Java Estoy intentando hacer el ejercicio que nos han mandado en clase, os pongo el enunciado.
En la clase Corredor:
Atributos(privados)
nombre: nombre del socio (cadena)
nif: nif del socio (cadena)
edad: edad del corredor (valor numérico entero)
numDorsal: número de corredor (valor numérico entero). Atributo estático.
dorsalActivo: que indica si el dorsal esta activo (variable booleana)
numMinutos: número de minutos que ha tardado el corredor en realizar la maratón. Al crear el cada objeto de este tipo se inicializará a 0. A lo largo del programa se tendrá en cuenta que el tiempo no puede ser menor que 0 ni la maratón durará más de 12 horas.
Métodos (a los que se tenga acceso desde un mismo paquete)
·         Constructor de objetos Corredor sin parámetros.
·         Constructor de objetos Constructor con tres argumentos que de valor a los primeros atributos.
·         Constructor de objetos Corredor con dos argumentos, nif y edad, que siempre asigne por nombre "Invitado".
·         Constructor Copia de objeto Corredor.
Mi pregunta: ¿Tengo que hacer cuatro constructores 3 de corredor y otro de constructor? ¿Cómo consigo hacer las cuatro opciones, sabiendo que no puedo hacer varios constructores con paramentros? Al menos el programa me da fallo.
Os dejo mi código:
public class Corredor {
    private String nombre;
    private String nif;
    private int edad;
    private static int numDorsal;
    private boolean dorsalActivo;
    private int numMinutos;

    public String getNombre(){
        return nombre;
    }
    public void setNombre(String nombre){
        this.nombre=nombre;
    }
    public String getNif(){
        return nif;
    }
    public void setNif(String nif){
        this.nif=nif;
    }
    public int getEdad(){
        return edad;
    }
    public void setEdad(int edad){
        this.edad=edad;
    }
    public int getNumdorsal(){
        return numDorsal;
    }
    public void setNumdorsal(int numDorsal){
        this.numDorsal=numDorsal;
    }
    public boolean getDorsalActivo(){
        return dorsalActivo;
    }
    public void setDorsalActivo(boolean dorsalActivo){
        this.dorsalActivo=dorsalActivo;
    }
    public int getNumMinutos(){
        return numMinutos;
    }
    public void setNumMinutos(int numMinutos){
        this.numMinutos=numMinutos;
    }
    //sin argumentos
    public Corredor(){

    }
    //con argumentos
    Corredor(String nombre, String nif, int edad, int numDorsal, boolean dorsalActivo, int numMinutos){
        this.nombre=nombre;
        this.nif=nif;
        this.edad=edad;
        this.numDorsal=numDorsal;
        this.dorsalActivo=dorsalActivo;
        this.numMinutos=numMinutos;
    }

    //con los tres primeros arguemntos y aqui es donde me da fallo dado que la clase corredor está declarada
    public Corredor(){
        nombre="Pepe";
        nif="740325679E";
        edad=57;
    }
}

A: Hola amigo tu error esta en que quieres tener dos constructores vacíos lo cual no es posible, te recomiendo que le des una vista al tema de sobrecarga de constructores, ya que es el tema que necesitas para solucionar el error.
Recuerda que si se puede tener varios constructores siempre y cuando los parámetros sean diferentes.
Por ejemplo tu primer constructor esta bien.
   public Corredor() {

}

En el caso del segundo también está bien dado que los parámetros son diferentes, lo que cumple con los principios de la sobrecarga de constructores.
Pero deacuerdo a lo solicitado quedaria algo asi.
   public corredor(String nombre, String nif, int edad) {
        this.nombre = nombre;
        this.nif = nif;
        this.edad = edad;
    }

Pero el error esta en el tercer constructor que intentas realizar, el cual no puede ser definido dado que ya tienes un constructor vació que es es el primero.
Y en tu enunciado dice `

Constructor de objetos Corredor con dos argumentos, nif y edad, que
  siempre asigne por nombre "Invitado".

Por lo que tiene que quedar algo asi.
 public Corredor(String nif, int edad) {
        this.nombre = "Invitado";
        this.nif = nif;
        this.edad = edad;
    }

Y si con el ultimo constructor y con en base a la documentación que te sugiero puedes realizarlo sin ningún problema.
Saludos


text:
Q: JNI proguard obfuscation I have problem with obfuscation. For a better imagination:
JAVA CODE
class JniTest...

public void test()
{
    //some code
}

public void runJniCode()
{
    //here I call native code
}

NATIVE CODE
JNIEXPORT void JNICALL
Java_path_to_class_test(JNIEnv* env, jobject  obj)
{
    //here I call test method from Java

}

Everything works fine until I want to release an obfuscated version. The name of the Java class (JniTest for example) and method test in this class are renamed by proguard to "a" and "a()" (this may not be always same), but in native code the original name of the method and class remain, because it's hardcoded as a string, like:
jmethodID mid = env->GetMethodID(cls, "test", "someSignature");

... is there any way to set the method name dynamically?

A: Building upon AndrewJC's answer, if your application is in Kotlin, you can also use the @JvmName annotation instead of using a wrapper method, example:
object Native {
    @JvmName("a")
    private external fun rotateRGBA(rgb: Int, w: Int, h: Int): Int
}

// rotateRGBA
extern "C" int Java_mypackage_Native_a(JNIEnv *env, jclass, int rgb, int w, int h);

Now you can call your JNI method in Kotlin with Native.rotateRGBA(0, 200, 400) but when compiled, Kotlin will automatically rename your method call to: Native.a.

A: JNI supports two ways of binding native methods. The simple one is done by name, and cannot be used for obfuscated class and method names.
The other way involves calling RegisterNatives from JNI_OnLoad() in your library. You must prepare a table of native methods for each class for this technique:
java:
package a.b;

public class C {
    public native int nativeMethod();
}

c++:
static jint cnm(JavaEnv*, jobject) {
    return 42;
}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env;
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return JNI_FALSE;
    }

    std::string className = "a/b/C"; // may be changed by ProGuard
    std::string methodName = "nativeMethod"; // may be changed by ProGuard

    jclass cls = env->FindClass(className.c_str());

    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        return JNI_ERR;
    }
    assert(cls);

    JNINativeMethod C_methods[] = {
      { methodName.c_str(), "()I", reinterpret_cast<void*>(&cnm) }
    };

    env->RegisterNatives(cls, C_methods, sizeof(C_methods)/sizeof(C_methods[0]);
    return JNI_VERSION_1_6;
}

This small snippet shows that you can actually replace the names with actual obfuscated ones, generated by ProGuard. The easy way is to trust that ProGuard obfuscation is deterministic, and manually copy the names from the mapfile after the release Java build is over. Automation may require tweaking the gradle build, because normally C++ is compiled before Java, but this is possible.
If the obfuscated method refers to some classes that undergo obfuscation, too - the task becomes more challenging.
The big advantage of RegisterNatives() for obfuscation is that not only it lets you change the class and method names, but also the native method implementations are not visible from outside your native library. E.g. in the example above, cnm is static and is not easily discoverable.

A: While researching this exact same problem I came across a solution which I think is reasonable. Unfortunately, the solution does not automatically obfuscate the native Java code and JNI methods as requested, but I still thought it would be worth sharing.
Quote from the source:

I present here a simple trick which allows obfuscation of the JNI layer, renaming the method names to meaningless names on both the Java and native side, while keeping the source code relatively readable and maintainable and without affecting performance.
Let's consider an example, initial situation:

class Native {
    native static int rotateRGBA(int rgb, int w, int h);
}

extern "C" int Java_pakage_Native_rotateRGBA(JNIEnv *env, jclass, int rgb, int w, int h);

In the example above Proguard can't obfuscate the method name rotateRGBA, which remains visible on the Java side and on the native side.
The solution is to use directly a meaningless method name in the source, while taking care to minimally disrupt the readability and maintainability of the code.

class Native {
    private native static int a(int rgb, int w, int h); //rotateRGBA

    static int rotateRGBA(int rgb, int w, int h) {
        return a(rgb, w, h);
    }
}

// rotateRGBA
extern "C" int Java_pakage_Native_a(JNIEnv *env, jclass, int rgb, int w, int h);

The JNI method is renamed to a meaningless a. But the call on the Java side is wrapped by the meaningfully named method rotateRGBA. The Java clients continue to invoke Native.rotateRGBA() as before, without being affected at all by the rename.
What is interesting is that the new Native.rotateRGBA method is not native anymore, and thus can be renamed by Proguard at will. The result is that the name rotateRGBA completely disappears from the obfuscated code, on both Dalvik and native side. What's more, Proguard optimizes away the wrapper method, thus removing the (negligible) performance impact of wrapping the native call.
Conclusion: eliminated the JNI method name from the obfuscated code (both Dalvik bytecode and native library), with minimal impact to readability and no performance impact.

Source: Obfuscating the JNI surface layer
I'm still on the hunt for a tool which can obfuscate native Java code and the associated JNI automatically.


text:
Q: MikTeX fails to find a font installed in Windows10 (in XeLaTeX) I have problem using some open type fonts in Windows 10 with
XeLaTeX in MikTeX. I downloaded a Malayalam language font, "Gayathri" and tried to use it in XeLaTeX. This font is clearly listed in the Font catalague accessible from Control Panel.  The Font catalogue lists it as "Gayathri Regular".  But when I use them in XeLaTeX with the command
     \newfontfamily{\mal}[Script=Malayalam]{Gayathri Regular}
MikTeX complains it cannot find the font and starts building 'tfm's
with the following Error message.
  Package fontspec Error: "Gayathri Regular" cannot be found.

I had the same problem with many other fonts in many other languages too.
I guess it must be a  problem related to the way MikTex identifying the fonts in the operating system.
Another Malayalam language font "Kartika" that comes with Windows 10 works fine in XelaTeX.
Any help will be appreciated.