text:
Q: Merging partitions in Debian I have recently inherited someone else's problem with a linux server. This is one of those all in one debian based lamp setups. It recently ran out of storage and no one seems to know anything about linux in general here. I have managed to expand the drive in VMWare and created the partition as seen in the image below. The challenge is to merge the root partition /dev/sda1 with /dev/sda4.
Note: the Start - End blocks are not back to back and I can't afford much downtime on this server. /dev/sda3 can probably be merged too but not important.

UPDATED: df -h output

UPDATED 2: fdisk -l output

A: I have no idea as to what sort of setup you have on your end. Maybe you use RAID or not, SAN, NAS or not as each of these would complicate things.
For now, I'm assuming you are using a single traditional hdd having partitions.
There's usually a reason why people have different partitions, for instance some people might think or have rationale to have databases for different datasets for security purposes and alike. I would urge you to research a bit more before taking a course of action and if possible to talk to the people why they did what they did beforehand.
Having said the above and assuming you have good reasons to do the changes, what I would do is backup all the data to an external drive, use a Debian Live CD or whatever you can get hands on, use gparted and do the partitions as you like, slip/copy the data making sure that any hard links or symlinks which might be pointing to the different partitions are linked correctly on a spare server with the same configuration excuding the hdd but have the filesystem if possible. I do hope you have some sort of tests to tell if things are working correctly.
If everything goes smoothly, just shut down the server, put the new disk in with the data and put it to live service.
It usually is a good idea to update Debian and whatever applications are being used when you are doing this but that would entail some time kept aside for testing how the data performs as kernel updates, security patches make the whole thing better.
I would also urge you to do some documentation so you can refer notes in case somthing does go wrong down the line as memory tends to become blurred over period of time as well as put the reasons as to why you are doing what you are doing.
All of these are just pointers to what good practices are and what you should be aware of. I, for one have never been in favor of in-situ repartitioning as any damage costs are simply not worth it.

A: /dev/sda1 is a primary partition, and /dev/sda4 is a logical partition locate in an extended partition. Besides they are non-contiguous which would make a merge operation problematic. Maybe you could create a clean slate by deleting /dev/sda3 and /dev/sda4 (after having backup the data) and then with gpart merge the now unallocated space with the /dev/sda1.  Maybe it would be necessary to remove the whole extended partition in order to create such clean slate of unallocated space.
After a second glimpse, I noted that that extended partition is only 1046529 blocks which means that /dev/sda4 is a primary partition. But that does not really matter. Mainly in order to extend sda1 you would need contiguous unallocated space. Instead of gpated you could use fdisk to delete and recreate the partition: fdisk /dev/sda -u (-u shows sizes of partition tables in sector for uniformity), and then use resize2f in order to resize to a  new size.

A: Right all you need is 1GB of space to get a day (you say that in a comment)?
Easy way (i think) is to clear your old logs, if they are not important by:
cd /var/log/
rm *.gz
cd /var/log/apache2
rm *.gz
(etc)

Or just moving your old logs to another place
mkdir /mnt/pendrive
mount /dev/sdc1 /mnt/pendrive
cd /var/log/
mv *.gz /mnt/pendrive
cd /var/log/apache2
mv *.gz /mnt/pendrive/myfunnyapache2folder
(etc)

Or if for some unknow reason, you dont want to do it, we can try moving /var/log to another partition until you get everything fine!
First stop your services: service rsyslog stop; service apache2 stop ; service mysql stop, etc
fdisk /dev/sda (change sda to your disk device or pendrive)
n (using n command create your 1GB partition and save fdisk with w command, and just quit fdisk)
Check with fdisk -l (L lowercase) what partition device your 1gb partition assumed, for example /dev/sda5
Now, mount /dev/sda5 or your partition number (created by fdisk) as your new /var/log...
mkdir /tmp/log
mkfs.ext4 /dev/sda5 - Assumed /dev/sda5 as the new empty partition. This will destroy all that in /dev/sda5 if you select the wrong partition, this is the empty partition you created in fdisk!
mount /dev/sda5 /tmp/log
mv /var/log/* /tmp/log
umount /tmp/log
mount /dev/sda5 /var/log
ls /var/log     - Now you have time to think again...

After that you will be able to restart your services: service rsyslog start; service apache2 start; service mysql start, etc...
Yes it can be dangerous if you dont pay attention in what you are doing, but less than trying to resize or merge partitions on a running system.
If you really dont have any more space on your hard drive, create a ramdisk partition (you can found how to do that in google), but you will lost your log data if the server restarts....
You can compress non-rotated log data too, with gzip, like that gzip filename, and other text files, that you probably will not need right now!


text:
Q: empty buffer when using readFile on a USB device This code should read in some data from sector zero off of a USB flash drive, then print out some of the data.  However when I run it there is nothing that was put in the buffer.
int _tmain(int argc, _TCHAR* argv[])
{
    int ReadSect = 0;
    char diskname[60];
    sprintf_s(diskname, "\\\\.\\K:", 'K');

    HANDLE DiskHandle = CreateFile((LPCTSTR) diskname , GENERIC_READ,FILE_SHARE_READ,     NULL, OPEN_EXISTING, 0, NULL);
        // set up the offsets for the addresses passed to setFilePointer, and ReadFile
    long lo_offset, hi_offset;
    LPDWORD temp = 0;
    lo_offset = ReadSect << 9;
    hi_offset = ReadSect >> 23;
    (void) SetFilePointer( DiskHandle, 0, &hi_offset, FILE_BEGIN);

    char buf[1024];
    for(int i = 0; i<512;i++) {
        buf[i]='X';
    }

    if (! ReadFile(DiskHandle, buf, 512, (LPDWORD)&lo_offset, NULL) )  {
        printf("error reading sector %ld\n", ReadSect);
    CloseHandle(DiskHandle);
    }
    for(int i = 0; i<512;i++) {
        cout<<(char)buf[i];
    }
    cout<<endl<<endl<<endl;
    getchar();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install Bcrypt on a 64bit Raspberry PI? I recently built a web application which needs to run bcrypt and mongodb over a raspberry pi 4 model b.

*

*Mongodb require a 64 bit OS.

*Bcrypt succeed installation only with 32 bit OS.

I used Ubuntu 20.04 for 64 bit OS and the latest version of raspbian 32 bit.
I searched in the npm bcrypt package documentation and I found out that they only support pre-built binaries for:

*

*Windows x32 and x64

*Linux x64 (GlibC targets only). Pre-built binaries for MUSL targets
such as Apline Linux are not available.

*macOS

Therefore, I have those options:

*

*Find another package (bcrypt like) which is functionnal for 64 raspberry pi's os

*Find a way to install bcrypt on armv7l 64 bit OS

*Downgrade mongo with an old version who support 32 bits and use Raspbian

I documented compiled all the logs in this post.
I'm sure someone already faced this issue and knows how to deal with this. Or even, if you know another alternative, I'll be glad to hear! Thank you


text:
Q: Why is there no definition for std::regex_traits (and thus no std::basic_regex) provided? I would like to use regular expressions on UTF-32 codepoints and found this reference stating that std::regex_traits has to be defined by the user, so that std::basic_regex can be used at all. There seems to be no changes planned in the future for this.

*

*Why is this even the case?

*Does this have to do with the fact that Unicode says combined codepoint have to be treated equal to the single-code point representation (like the umlaut 'ä' represented as a single codepoint or with the a and the dots as two separate ones) ?

*Given the simplification that only single-codepoint characters would be supported, could this trait be defined easily or would this be either non-trivial nevertheless or require further limitations?

A: *

*Some aspects of regex matching are locale-aware, with the result that a std::regex_traits object includes or references an instance of a std::locale object. The C++ standard library only provides locales for char and wchar_t characters, so there is no standard locale for char32_t (unless it happens to be the same as wchar_t), and this restriction carries over into regexes.

*Your description is imprecise. Unicode defines canonical equivalence relationship between two strings, which is based on normalizing the two strings, using either NFC or NFD, and then codepoint-by-codepoint comparing the normalized values. It does not defined canonical equivalence simply as an equivalence between a codepoint and a codepoint sequence, because normalization cannot simply be done character-by-character. Normalisation may require reordering composing characters into the canonical order (after canonical (de)composition). As such, it does not easily fit into the C++ model of locale transformations, which are generally single-character.
The C++ standard library does not implement any Unicode normalization algorithm; in C++, as in many other languages, the two strings L"\u00e4" (ä) and L"\u0061\u0308" (ä) will compare as different, although they are canonically equivalent, and look to the human reader like the same grapheme. (On the machine I'm writing this answer, the rendering of those two graphemes is subtly different; if you look closely, you'll see that the umlaut in the second one is slightly displaced from its visually optimal position. That violates the Unicode requirement that canonically equivalent string have precisely the same rendering.)
If you want to check for canonical equivalence of two strings, you need to use a Unicode normalisation library. Unfortunately, the C++ standard library does not include any such API; you could look at ICU (which also includes Unicode-aware regex matching).
In any case, regular expression matching -- to the extent that it is specified in the C++ standard -- does not normalize the target string. This is permitted by the Unicode Technical Report on regular expressions, which recommends that the target string be explicitly normalized to some normalization form and the pattern written to work with strings normalized to that form:

For most full-featured regular expression engines, it is quite difficult to match under canonical equivalence, which may involve reordering, splitting, or merging of characters.… In practice, regex APIs are not set up to match parts of characters or handle discontiguous selections. There are many other edge cases… It is feasible, however, to construct patterns that will match against NFD (or NFKD) text. That can be done by:

*

*Putting the text to be matched into a defined normalization form (NFD or NFKD).

*Having the user design the regular expression pattern to match against that defined normalization form. For example, the pattern should contain no characters that would not occur in that normalization form, nor sequences that would not occur.

*Applying the matching algorithm on a code point by code point basis, as usual.

*The bulk of the work in creating a char32_t specialization of std::regex_traits would be creating a char32_t locale object. I've never tried doing either of these things; I suspect it would require a fair amount of attention to detail, because there are a lot of odd corner cases.

The C++ standard is somewhat vague about the details of regular expression matching, leaving the details to external documentation about each flavour of regular expression (and without a full explanation about how to apply such external specifications to character types other than the one each flavour is specified on). However, the fact that matching is character-by-character is possible to deduce. For example, in § 28.3, Requirements [re.req], Table 136 includes the locale method responsible for the character-by-character equivalence algorithm:

Expression: v.translate(c)
     Return type: X::char_type
     Assertion: Returns a character such that for any character d that is to be considered equivalent to c then v.translate(c) == v.translate(d).

Similarly, in the description of regular expression matching for the default "Modified ECMAScript" flavour (§ 28.13), the standard describes how the regular expression engine to matches two characters (one in the pattern and one in the target): (paragraph 14.1):

During matching of a regular expression finite state machine against a sequence of characters, two characters c and d are compared using the following rules:

*

*if (flags() & regex_constants::icase) the two characters are equal if traits_inst.translate_nocase(c) == traits_inst.translate_nocase(d);

*otherwise, if flags() & regex_constants::collate the two characters are equal if traits_inst.translate(c) == traits_inst.translate(d);

*otherwise, the two characters are equal if c == d.

A: I've just discovered a regex implementation which supports char32_t: http://www.akenotsuki.com/misc/srell/en/
It mimics std::regex API and is under BSD license.


text:
Q: Применение css стиля в зависимости от переданного пропса Всем привет. У меня есть метод highLightText и в зависимости от значения передаваемого параметра readonly  false или true  используется тот или иной стиль. Если readonly true то применяется два стиля.  У меня метод написан с ошибкой но идея ясна. Помогите в реализации с применением двух стилей и передачей их в div
highLightText = (value, showTime, readonly) => {
        const className = readonly ? 'text-control text-control--readonly--highlight' : 'text-control text-control--readonly';
        return (
            <div className={className}>
                {convertDate(value, showTime)}
            </div>
        );
    };

Стили из класса scss
div.text-control {
  line-height: ($inputHeight - 2px);
  &--readonly {
    background: $disabled_background;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: not-allowed;
    a {
      cursor: pointer;
    }
  }
  &--textarea {
    margin-bottom: 0;
    line-height: 0.5*$inputHeight;
    white-space: normal;
    overflow-y: auto;
    text-overflow: clip;
  }
  &--highlight {
    color: #009c0e;
  }
}


text:
Q: Wrong encoding between Spring and PostgreSQL I have a Spring Boot (version 1.3) Web application, all in UTF-8, and a PostgreSQL server with server encoding UTF-8 and client encoding WIN1252.
The problem is that when I save in the DB something with special characters manually, the encoding is right, but from JDBC the string is saved wrong.
In the same way, when I have a string saved with special characters and I make a SELECT query to read manually, the encoding is right, but from JDBC the string is read wrongly.
Dropping the database and creating again is not a choice for the moment, so I have been trying a lot of things with poor result. Is there any solution for me?
PD: I have put all these properties in my application.properties file:
spring.datasource.sql-script-encoding = UTF-8
spring.http.encoding.charset = UTF-8
spring.http.encoding.enabled = true
spring.http.encoding.force = true
spring.mandatory-file-encoding = UTF-8
server.tomcat.uri-encoding = UTF-8
spring.messages.encoding = UTF-8

A: I had a similar problem. I use Spring Boot 1.5.9 and postgres 9.6, data.sql with inserts. Encoding on data.sql was UTF-8, but after start of application, in DB was special symbols instead russian letters.
spring.datasource.sql-script-encoding= UTF-8

This property in application.properties has helped.
All properties responsible for DB:
spring.datasource.jndi-name=java:/PostgresDS
spring.jpa.properties.hibernate.default_schema=my_scheme_name
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = false
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.datasource.continue-on-error=true
spring.datasource.sql-script-encoding= UTF-8

A: Where you define the datasource URL, try adding ?characterEncoding=UTF-8 to the end of the URL

A: In my case the problem was on JVM side.
After I added:
-Dfile.encoding=UTF8

as VM option - problem was resolved

A: Now the correct option is:
spring.sql.init.encoding = UTF-8


text:
Q: MVC pattern. "Could not find the connection string with the name ... in the application configuration file" My WinForm app realizes MVC pattern and consists of two projects. The first one contains View and Controller layers and the second one- Model layer(class library).
The application has to get information from database (I use MS SQL Server).
In the second project (Model layer) i have ADO.NET model, methods to work with the database and appropriate connection string in app.config. But when i run the app and it tries to make a query to the database the error "Could not find the connection string with the name ... in the application configuration file" appears.
I guess that when Controller call a Model's method to make a query to the database app tries to find connection string in App.config file of the main project and can't find it there. I think it's not right to create a connection string in the project with Controller and View.
How can i solve the problem in the right way?

A: The App.config (or Web.config where appropriate) belongs to the application, not to any class libraries.
If your Controller/View layers are a Windows Forms project and your Model layer is a Class Library project then the App.config belongs in the Windows Forms project.

I think it's not right to create a connection string in the project with Controller and View.

It has nothing to do with the Controllers and Views.  The App.config isn't part of the MVC pattern.  It has everything to do with the configuration of an application for an environment.  Any given class library should be portable across applications and environments.  Any given application should be configured to execute in the environment to which it's deployed.

Basically, put your App.config values in the application's App.config.


text:
Q: Однотабличные запросы , SQL . Имеется часть вот такой БД :
3 таблицы
По заданию запрос должен быть без всяких Join-ов .
Само задание : выбрать [name_groups] из таблицы [groups] для которых [id_student] == k .
Что получилось у меня :
SELECT [name_group] FROM [group] WHERE EXISTS(SELECT [student_group].* FROM [student_group]
WHERE [student_group].[id_group] = [group].[id_group] AND [student_group].[id_student] = 24)

/* или можно так */

SELECT [name_group] FROM [group] WHERE [id_group] =
(SELECT [student_group].[id_group] FROM [student_group] WHERE
[student_group].[id_student] = 24)

Можно ли как-то сделать этот запрос более простым и не делать через подзапросы ?
Заранее спасибо.
A: Просто
select group.name_group from group, student_group where student_group.id_student = 24 and student_group.id_group = group.id_group

Конечно, это синтаксически другая форма JOIN, но по другому (без соединения таблиц) просто нелепо.


text:
Q: Change number of decimals in Woocommerce cart, checkout and my account Would it be possible to have a php code to insert in my child theme capable of passing my site to two decimal places after the comma for all the basket information subtotal total VAT Shipping the same for the checkout but also in the customer area
I would like to keep only the product to three decimal after the decimal point but the total rounded up to two decimal after the decimal point
can you help me
I am using Change number of decimals in Woocommerce cart totals answer code, for the cart and the checkout pages. It works perfectly but I am missing an info for it to work in the my order account tab.
screenshot

A: For my account section use the conditional tag is_account_page(), so in the code:
add_filter( 'wc_get_price_decimals', 'change_prices_decimals', 20, 1 );
function change_prices_decimals( $decimals ){
    if( is_cart() || is_checkout() || is_account_page() )
        $decimals = 2;
    return $decimals;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.
Related: Change number of decimals in Woocommerce cart totals


text:
Q: Junit 5 test, getting java.lang.IllegalStateException: Test classes cannot include @Bean methods @ContextConfiguration(classes = ConfigureCustomConfigurationModelProviderTest.class)
    public class ConfigureCustomConfigurationModelProviderTest extends AbstractContextTest {
        @Bean(name = "smth")
        public static ConfigurationModelProvider get() {
            return AnnotationConfigurationModelProvider.getInstance();
        }
        /*...*/
    }

I'm getting this error since migrating from junit4 to junit5. Why?

A: You should move every beans to @Configuration class for example TestConfig:
@Configuration
public class TestConfig {

    @Bean(name = "smth")
    public static ConfigurationModelProvider get() {
        return AnnotationConfigurationModelProvider.getInstance();
    }
}

and import it via @Import:
@Import({TestConfig.class})
@ContextConfiguration(classes = ConfigureCustomConfigurationModelProviderTest.class)
public class ConfigureCustomConfigurationModelProviderTest extends AbstractContextTest {
}

A: To add to Amir's answer: if you only need the bean for some tests you can omit the @Configuration annotation at the top.


text:
Q: Does not load .Armodel file in camera only display white screen in kudan i used xcode 8.0 and os version 9.3.5
when i use this demo i am unable to open camera.
first i put object this screen is work properly but when click done button than after display white screen.nothing display in this screen.
i used this Demo
https://github.com/kudan-eu/GPSSample-iOS
here is my screenshot

here is my code
mapViewcontroller.m
- (IBAction)progressButton:(id)sender
{
    if (self.touchPin) {
        [self performSegueWithIdentifier:@"showGPSDemo" sender:self];
    }
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showGPSDemo"]) {
        // Set model coordinate to position of the map pin.
        CameraViewController *viewController = [segue destinationViewController];

        CLLocationCoordinate2D touchPinCoordinate = self.touchPin.coordinate;

        viewController.objectCoordinate = [[CLLocation alloc] initWithLatitude:touchPinCoordinate.latitude longitude:touchPinCoordinate.longitude];
    }
}

CameraViewController.com
- (void)setupContent
{
    // Initialise and start the GPS Manager.
    ARGPSManager *gpsManager = [ARGPSManager getInstance];
    [gpsManager initialise];
    [gpsManager start];

    // Initialise a GPSNode with coordinate provided from the map.
    ARGPSNode *gpsNode = [[ARGPSNode alloc] initWithLocation:self.objectCoordinate];

    // Point the GPS Node due east.
    [gpsNode setBearing:90];

    // Must add GPSNode as a child to the GPS Manager world.
    [gpsManager.world addChild:gpsNode];

    // Import the model.
    ARModelImporter *modelImporter = [[ARModelImporter alloc] initWithBundled:@"bloodhound.armodel"];

    // The ARModel node represents all external contents relating to the model e.g.animations, textures.
    ARModelNode *modelNode = [modelImporter getNode];

    // Add the modelNode as a child to the GPSNode.
    [gpsNode addChild:modelNode];

    // Add the texture to the 3D model.
    ARTexture *modelTexture = [[ARTexture alloc] initWithUIImage:[UIImage imageNamed:@"bloodhound.png"]];

    // Setup the object material.
    ARLightMaterial *modelMaterial = [[ARLightMaterial alloc] init];
    modelMaterial.colour.texture = modelTexture;
    modelMaterial.ambient.value = [ARVector3 vectorWithValuesX:0.5 y:0.5 z:0.5];
    modelMaterial.diffuse.value = [ARVector3 vectorWithValuesX:0.5 y:0.5 z:0.5];

    // Apply to the model.
    for (ARMeshNode *meshNode in modelNode.meshNodes) {
        meshNode.material = modelMaterial;
    }

    // Scale the model to the correct height of Big Ben from model height. Units of the GPSManager world are meters, model is 11008 units high in object space.
    [modelNode scaleByUniform:(96.0 / 11008.0)];

    self.gpsNode = gpsNode;
}

here is my log
Could not find file for texture Big_Ben_spec.png
2016-12-13 16:40:37.546 GPS Sample[13723:834618] RootNode ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]   Big_Ben_001 ARVector3(0.001160, -0.000000, 0.001221)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:37.547 GPS Sample[13723:834618]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:39.877 GPS Sample[13723:834618] generated main fbo 2
2016-12-13 16:40:39.885 GPS Sample[13723:834618] created main FBO with width 1536 and height 2048
2016-12-13 16:40:40.281 GPS Sample[13723:834682] camera dimensions: 480.000000 x 640.000000
2016-12-13 16:40:40.282 GPS Sample[13723:834682] camera aspect ratio: 0.750000
2016-12-13 16:40:40.282 GPS Sample[13723:834682] framebuffer aspect ratio: 0.750000
2016-12-13 16:40:40.288 GPS Sample[13723:834682] rotating to orientation 1
2016-12-13 16:40:40.444 GPS Sample[13723:834682] WARNING: Could not find file for texture Big_Ben_diffuseShade.png
2016-12-13 16:40:40.444 GPS Sample[13723:834682] WARNING: Could not find file for texture Big_Ben_spec.png
2016-12-13 16:40:40.461 GPS Sample[13723:834682] RootNode ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:40.461 GPS Sample[13723:834682]   Big_Ben_001 ARVector3(0.001160, -0.000000, 0.001221)
2016-12-13 16:40:40.462 GPS Sample[13723:834682]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:40.462 GPS Sample[13723:834682]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:40.462 GPS Sample[13723:834682]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:40.462 GPS Sample[13723:834682]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:40.462 GPS Sample[13723:834682]     Big_Ben_001 ARVector3(0.000000, 0.000000, 0.000000)
2016-12-13 16:40:49.263 GPS Sample[13723:834618] Error while getting core location : (null)

A: i used different ARAPIKey but finally i got right ARAPIKey
 [[ARAPIKey sharedInstance] setAPIKey:@"sVmoznmKZ+4nFEHD6HoslwpC26PNuBZGHrikUwyon2BKSvza1yu2CqbSrae+pHPr1NHjhsf5pHQOZn8IEqXlqXFodGsrOJhxJANbMOdvnRLUi9/QWGqyRL9FViDmyohw6e5R7U4Ex8H7d7spLLvhfp5HFv56DgLr8c8sC2ipDtv9g1IjOTaY7UGxata3eulG2A/UkIdRv2NcotZXqan01xQUWFAislEwlGguParEYiwu11T4mqtU3dQBbfxpvxbczjdYz493YG3rAO2RHgT+5M5TJShJsz2irkNo71JD2Fzqf4AR2b4+7t1c55zKjegXzGS6Xa/rpNn9yiXUn7rUYIHNvN3cEQa9HsZiVxAV4vJgxFS+T/AxfWqKrEg1uj6xF5MsodZ2EkZ8mqliYIsxZqnFz+Re2HeWG8wvrEob0ZwRIO0TxppAemZc3HChTAPLcNt5gzeBk0oRP4wnrFAFFBDi8XjDocwTSVw++hWZb1qNHzt6bKLsMDRT057UVuuZB6M8f7EOQD79Oah0Vrx/3DUK6e9BEV8oGFNHtk1wyYEkg0i6RLhVSokGx//Qj36A4gCz3h1OjtfB0OuukbNq7xI1L/FcNQLmGYNGZwszARjGr9ESw1gVAkbQMxaV27uo/KoIq4+nR7RL8iT7t7NAaXCFIi24RR+7WGjTvKqWYjA="];

if this ARAPIKey is expired than get new key https://wiki.kudan.eu/Development_License_Keys


text:
Q: Distributionally Robust Optimization: how to know distributions in ambiguity set? In distributionally robust optimization, it is said that ambiguity sets are created from empirical sample distribution such that the distributions within the ambiguity set 'Q' are at certain divergence  from the empirical distribution P. The divergence is calculated using mechanisms like φ-divergence or Wasserstein or others. But how do we really come up with such distributions 'Q'. How do we form their density functions or generate samples associated with the Q distributions?
Furthermore, are moment-based DRO ambiguity sets Borel distributions that satisfy certain constraints?
Please feel free to provide helpful resources.
Thanks!


text:
Q: Question about association classes in UML class diagram So I need to model the situation where we have a collection of people who are members of a federation. You can either be an active member or an inactive member of the federation. If you're inactive, you're not a member of any club. If you're an active member, you are a main member to exactly one club and can have any number of clubs that you're an internal member of.
My current UML model does not enforce that every active player should have exactly one main membership so I'm wondering how I can fix this. I personally think that I can solve this by drawing a regular association between 'Main' and 'Active' but I don't really know if this is allowed or if there are any other solutions to my problem.

A: Although not necesarrily wrong, you might be overusing Generalization
A Generalization is a is a relationship, and where I can follow if you say

*

*a Player is a Person
but I'm having a harder time understanding

*

*a Active is a Player is a Person
It seems to make more sense to model Active or NotActive as values of the Status of a Player.
Here's how the most basic model to express those requirements could look like.

Some pointers

*

*Player becomes a role played by Person, not the same object. So if a Player is deleted, the Person object can live on. In the other direction I have modelled it using compositions. So if a Person is deleted, it's Player role is deleted, and also it's Memberships

*Using Composition over Inheritance is a known software engineering principle

*I've used a constraint with natural language to express the Active member should have one main membership requirement. If you like (or need) it to be more formal you could use OCL as well. An alternative option might be to add another association with [0..1] multiplicity for the main Membership. You could add a constraint there that says it's only for Memberships with property IsMainMembership = True, and that it is mandatory for Players with Status = "Active"

*In order to insure consistency between Player.Status, and the existence of a main Membership, you could also opt to make the Player.Status derived. You could then derive the Status by checking the existence of an association to a main Membership.

*In most implementations an instance cannot change classes. So if your Active where to become NotActive you would have to delete the Active object and create a new NotActive object. Having Active/Notactive as a status would allow you to use the same object and simply change it's status. How these statusses can be changed could be modeled using a State Machine.

*Most OO languages also don't support multiple inheritance, so you should be careful about choosing a Generalization. If you choose to make Player a Person, you might get into trouble if you later need players that are not Persons, such as computers, or organisations, or teams. UML does support multiple inheritance, but in most organisations I've worked so far the guidelines forbid the use of multiple inheritance.

*In this case I even did away with the association-class in favor of a regular class with regular associations. Association classes make your model harder to understand for the less UML savvy

I'm not saying this model is better or worse than your model, but it's worth think about the other end of the complexity spectrum, and where you want your model to end up at.

A: Main is an instance of a UML Association Class because its superclass is Membership. That means Main can specialize the association (which requires another dashed line) and can subset one or both association ends. When you say
isMemberOf { subsets isMemberOf } 1

on the left end of the new association line, that means every active player must participate in exactly one Main membership, plus any number of other kinds of memberships.
You should consider renaming the subsetting and / or subsetted properties for clarity, but UML does not require it. For example,
isMainMemberOf { subsets isMemberOf } 1

(Although that name implies a person is the Main member of a club, which is not quite right.)


text:
Q: Let $I = n\mathbb{Z}$ , $J = m\mathbb{Z}$. Does $I+J = I \cap J = IJ = I/J = d\mathbb{Z}$???
Problem: Let $I = n\mathbb{Z}$ , $J = m\mathbb{Z}$. Find $I+J, I \cap J, IJ, I/J$

My question: If we let $d = \gcd(n,m)$, does $I+J = I \cap J = IJ = I/J = d\mathbb{Z}$???
$a \in I \cap J \Rightarrow$ both $a \in I$ and $a \in J$. $d\mathbb{Z} \in I$ and $d\mathbb{Z} \in J \Rightarrow d\mathbb{Z} = I \cap J$. With $I + J, IJ, I/J$ we have a similar proof.
Anything wrong here? Thank all!

A: $\mathbb{Z}$ is a principal ideal domain, so the idea of having one element spanning each of the ideals(are all of them ideals?) is correct. But for example the intersection is spanned by the $\text{lcm}(n,m)$ not the $\text{gcd}(n,m)$.
$$x\in I\cap J \Rightarrow (n|x) \wedge (m|x) \Rightarrow l=\text{lcm}(n,m)|x$$
So $I\cap J \subseteq (l)$.
For the other direction suppose $x\in (l)$ but not in either, derive a contradiction.
For $I+J$ consider  the $\text{gcd}(n,m)$.
For $IJ$ check if its included in one of the previous two.


text:
Q: Export a global function in webpack.config.js to be used in a typescript New to webpack. I want to export a global function (similar to exporting variables through webpack.EnvironmentPlugin) to be used in a  typescript
I tried something like below just to see the the behavior.
module.exports = [{
  ...
  ...
  plugins: [
    new webpack.EnvironmentPlugin({
     env_func: function bindObj() {
        console.log("In plugin");
       }
    })
  ]
}]

It gives me an error (as below) when accessed as envFunc = process.env.env_func; envFunc.bindObj()

TypeError: Cannot read property 'bindObj' of undefined

Is there a way or any plugin (similar to EnvironmentPlugin) I can export a function in webpack config that can be used from the typescript?

A: webpack.EnvironmentPlugin is a shorthand notation for DefinePlugin which you can use to define a function. To make Typescript compiler accept it you need to declare the function e.g. include some .d.ts file into the project:
xxx.d.ts
--------
declare function bindObj(): void;
declare function fun1(abc: string): number;


text:
Q: How to execute and apk file on my phone? I have an .apk application for android which has been compiled and packed with "Mono for Android" , When i copy it on my SD and install it works fine but when i execute it it gives me an error
app_vercode:1
device_model:ace
build_version:1.12.23
condition:1
processName:MonoAndroidApplication1.MonoAndroidApplication1
pid:24897
uid:10070
tag:null
shortMsg:android.content.pm.PackageManager$NameNotFoundException
longMsg:android.content.pm.PackageManager$NameNotFoundException: Mono.Android.DebugRuntime
stackTrace:java.lang.RuntimeException: Unable to get provider mono.MonoRuntimeProvider: java.lang.RuntimeException: Unable to find application Mono.Android.DebugRuntime or Mono.Android.Platform.ApiLevel_10!
at android.app.ActivityThread.installProvider(ActivityThread.java:3577)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:3329)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3285)
at android.app.ActivityThread.access$2200(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:969)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Unable to find application Mono.Android.DebugRuntime or Mono.Android.Platform.ApiLevel_10!
at mono.MonoRuntimeProvider.attachInfo(MonoRuntimeProvider.java:30)
at android.app.ActivityThread.installProvider(ActivityThread.java:3574)
... 12 more

do i have to install anything before executing apk file packed with mono ?

A: In order to facilitate a fast change and deploy cycle, your .apk by default does not contain everything needed to run on device.  The IDE will take care of installing everything needed for you application to run.
If you do not want to use an IDE, the easiest thing is to compile your app in Release mode, which is fully self contained.
Package details:
http://docs.xamarin.com/android/tutorials/Application_Package_Sizes

A: You can create a release configuration in your project that will include the Mono runtime with your .apk rather than using the shared runtime. Note that Use shared Mono runtime is unchecked in the screen shot below.


text:
Q: Removing battery and watch icon from iPad status bar I need to remove the battery and watch icons from the status bar in an iPad application. How can I do this?

A: No, you can't do this. You can only remove the complete status bar.
I don't know why one would want to remove clock and battery but leave the bar, anyway.

A: You can use a UIWindow subclass that is laid out as an opaque view copying the status bar appearance. You can set its frame accordingly so that it only blocks off the portions of the status bar that you need to hide. Then you set the windowLevel property to something like UIWindowLevelStatusBar + 1.0f. Hope this helps!
EDIT
I came up with some basic sample code. This should only be considered a proof of concept. There are many considerations in an attempt worthy of production code, such as rotation, different status bar styles (I'd say translucent would be impossible to do actually), and
different layouts of the items in the status bar.
The UIWindow subclass:
@interface StatusBarMask : UIWindow

@end

@implementation StatusBarMask

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.windowLevel = UIWindowLevelStatusBar + 1.0f;
        self.backgroundColor = [UIColor greenColor];
        self.hidden = NO;
    }
    return self;
}

@end

And a view controller that instantiates it:
@interface ViewController ()

@property (nonatomic, strong) StatusBarMask *mask;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect appStatusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
    appStatusBarFrame.size.width = 384.0f;
    appStatusBarFrame.origin.x = 384.0f;
    self.mask = [[StatusBarMask alloc] initWithFrame:appStatusBarFrame];
}

@end

This will mask off the right side of the status bar with a bright green rectangle. Adjust colors and sizes as needed, and consider all the gradients, curved edges, and so forth. With careful consideration of the various edge cases, you should be able to accomplish your goal.

A: You can hide the top status bar with the following code
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];


text:
Q: How to change value at address from mmap without malloc? Having this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main (void) {

    int fd = open("./sometext.txt", O_RDONLY);
    struct stat sb;

    if(fstat(fd,&sb)) perror("in function fstat");

    printf("file size is %ld bytes\n\n",sb.st_size);
    char* file_p = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

    printf("printing file as an array of chars \n\n");
    for(int i =0; i<sb.st_size ; i++){
        if(file_p[i]=='a') //cannot do this
            file_p[i]='5'; //string/char is read-only, but then how?
        printf("%c",file_p[i]);
    }

    munmap(file_p, sb.st_size);
    close(fd);

    return 0;
}

As I found from other questions, to change string literal, which is read-only by defaul, I have to either have array storage (char arr[] = "sometext_to_change_in_loop") or make another pointer, malloc need space and then copy the first address of the string that pointer from malloc. But how to change the string "in-line" without doing either of those?
EDIT:
Yes, the main issue was I did not bitwise ORed the int prot argument in mmap call. However, how it possible that only that is sufficient?
1) - I do not change int flags in open call, so why does it work when opened with O_RDONLY and not with O_RDWD which makes the same file writeable as well (which I am doing by file_p[i] = '5': writting).
2)How can be actually changes saved when in mmap I have in argument int flags MAP_PRIVATE, but I want to save changes, so I should have MAP_SHARED? according to this tutorial : enter link description here where both - the open flag and the mmap flag were changed as I write. I need to explain this as well.
EDIT2:
from the tutorial. It is indeed needed in case of different writing to the file:
for(int i =0; i<sb.st_size ; i++){
        file_p[i] = toupper(file_p[i]);
        printf("%c",file_p[i]);
    }

This will REQUIRED to have set open flag to O_RDWR and mmap flag to MAP_SHARED. But WHY? Why is one change to file file_p[i]='5' different in another change file_p[i]=toupper(file_p[i])? Why does not one change requires to set the two flags (the first case), but the other does require it (second case)? It is confusing for me now.

A: Try changing
char* file_p = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

to
char* file_p = mmap(0, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);

A: You seem to ask two completely different questions, one about mmap() and one about string literals.  Taking the latter first:

to change string literal, which is read-only by defaul, I have to
  either have array storage (char arr[] = "sometext_to_change_in_loop")
  or make another pointer, malloc need space and then copy the first
  address of the string that pointer from malloc. But how to change the
  string "in-line" without doing either of those?

Echoing my comments on the question, there is no defined way to modify a string literal.  Any attempt to do so produces undefined behavior.  Many strings are not literals, however, and if they have elements of modifiable type and are stored in writable storage then they can be modified via various string and I/O functions and by ordinary accesses to the arrays in which they reside.  In particular, the contents of a string literal can be copied into such a space, and the resulting separate string then modified.

As for the mmap() question(s), the overarching one seems to be how to map a file so that the contents can be modified via the mapping.  That is already addressed by your other answer, which observes that the allowed accesses to the mapping are controlled by the bitmask passed as mmap()'s third argument, as described by POSIX.  There are separate bits for read, write, and execute access to the contents of the mapping.
You go on to ask for clarifications:

1) - I do not change int flags in open call, so why does it work when
  opened with O_RDONLY and not with O_RDWD [sic] which makes the same file
  writeable as well

I can understand how that observation might come as a surprise.  The mapping established by mmap() does not access the underlying object via the provided file descriptor, so the descriptor's mode is irrelevant.  The file descriptor serves only as (partial) identification of the data to be mapped.  Permissions for access via the mapping are defined by the arguments to mmap() alone, and the mmap() call will fail if the process does not have sufficient privilege on the mapped object to access it in the requested modes.

How can be actually changes saved when in mmap I have in argument int flags MAP_PRIVATE, but I want to save changes, so I should have MAP_SHARED?

You are conflating two different things.  The access modes already discussed determine whether you can write to the mapping.  MAP_PRIVATE vs. MAP_SHARED controls whether other processes can see such writes, either in their own copy of the mapping or in the underlying file.  POSIX expresses this as being about the disposition of writes to the mapping.  With MAP_SHARED, they modify the underlying object.  With MAP_PRIVATE, they do not modify the underlying object, and they are visible only to the process that performed the write.
It's not entirely clear what you are asking about in the second edit, but I think it's about writing to the underlying object via the file descriptor and trying to observe the changes via the mapping.  Naturally, the file descriptor needs to be open in a mode that permits writing if you want to use it to write to the file.  Furthermore, however, to see the changes via an already-established memory mapping, that mapping should be configured as a shared one.
As POSIX puts it: "It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping is established are visible through the MAP_PRIVATE mapping."  This is pretty much the flip side of the already-discussed semantics of MAP_PRIVATE: not only are writes to the mapping not reflected in the underlying object, but modifications to the underlying object may not be visible through the mapping, either.  Remember, again, that he mapping established by mmap() does not access the underlying object via the provided file descriptor.


text:
Q: Priority queue constructor java with lambda expression I am trying to create a priority queue for a class Student with some order using lambda expression comparator of java 1.8.
But I am getting error Cannot infer type arguments for PriorityQueue<>
class Priority
{
    PriorityQueue<Student> priorityQueue = null;
    public Priority()
    {
        priorityQueue = new PriorityQueue<>(
            (Student s1,Student s2)->{
                int cmp = 0;
                if (s1.cgpa !=s2.cgpa)
                {
                    return ( s2.cgpa - s1.cgpa);
                }
                else if (s1.name.compareTo(s2.name) != 0)
                {
                    return s1.name.compareTo(s2.name);
                }
                else
                {
                    return (s1.id - s2.id);
                }
        });
    }
}


text:
Q: SQL Server Query Performance Test I have 2 severs which have SQL server installed and the exact same database. The database has a store procedure which on Server A takes 35 minutes but on server B tables 9 hours. The procedure mainly updates a few tables but the data is the exact same so I don't understand why the time difference is so huge
Can someone advise me a dummy query which I can run on both servers (not relating to current data) to compare the performance. e.g. inserting 5 million rows and then update them all.
Just for information, the server B spec is a higher spec, the indexing is the same on the relevant tables, there is no blocking while server B SP is executing

A: There are a alot of possibilities, but if the data and hardware ought to be similar in the two environments, then perhaps its parameter sniffing going on?
Basically it means that the first time the procedure is run, a plan is made with the current parameters, and this plan is saved with the procedure. The next time you run the procedure it reuses the old plan, which might be very bad for the new parameter.
You can try adding "WITH RECOMPILE" to see if that drastically changes the performance
ALTER PROCEDURE <procedure>
<Parameters>
WITH RECOMPILE
AS


text:
Q: How to insert data into a SharePoint multi-select field? I have a form that has a few multi-select choice fields.  When I try to add an item, I get an unusual error below.  I am using the Vue.js framework.

"value: "A node of type 'StartArray' was read from the JSON reader when trying to read a value of a property; however, a 'PrimitiveValue' or 'StartObject' node was expected."

Here's the code and the fields that are multi-select.
 $.ajax({
url: fullUrl,
method: "POST",
data: JSON.stringify({
  '__metadata': { 'type': 'SP.Data.RegistryListItem' },
  'Register': that.register,
  'RiskRegister': that.nextIndex,
  'Reopen': that.formatDate(that.reopen),
  'RiskOrIssue': that.riskOrIssue,
  'Status': that.status,               //<---multi-select choice field
  'ProblemT': that.probTitle,
  'ProblemStatement': that.problemStatement,
  'TaskOwner': that.taskOwner,
  'RiskOwner': that.riskOwner,
  'ResponseOwner': that.responseOwner    //<--- multi-select choice field
}),
headers: {
  "accept": "application/json;odata=verbose",
  "content-type": "application/json;odata=verbose",
  "X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(){
  alert("Item Added!");
},
error: function(data){
  console.log(data);
}
});

How can I solve this issue?
Thank you!

A: Here is an working example to set value of a Multi-select Choice field. Insert it in a Script Editor and test :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  SetMultiChoice();
});
function SetMultiChoice() {

var listName = "ListTitle";

 var itemDetails = {
    "__metadata": { "type": 'SP.Data.GZTickerListItem' },
    "Column_Internal_Name":{"results": ['A', 'B']}  // Multi Choice Column where A & B are the choices selected

};
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(itemDetails),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data) {

        //Perform Some Actions
    },
    error: function (data) {
        console.log(data);
    }
});
}

</script>

To get the _metadata value specific to your list use the below URL in your browser and search for ListItemEntityTypeFullName:
https://site-url/_api/web/lists/GetByTitle('ListName')/?$select=ListItemEntityTypeFullName

Let me know if this helps.

A: Try to set your multi-select choice fields in below format:
'Status': {'__metadata': {'type': 'Collection(Edm.String)'}, 'results':['Status 1', 'Status 2', 'Status 3']}

OR Simply try using:
'Status': { 'results':['Status 1', 'Status 2', 'Status 3'] }

Check my answer given at SharePoint Multiselect Choice field Saving using PnPjs for easy format.
Similar Questions:

*

*SP 2013 - Updating a multi-value lookup field via the REST API

A: Sample test script:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function() {
CreateNew();
function CreateNew() {
    var listName = "11/25";

    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, function () {
        alert("New Item has been created successfully.");
}, function () {
     alert("Ooops, an error occured. Please try again.");
});
}

function CreateListItemWithDetails(listName, webUrl,  success, failure) {

    var item = {
        "__metadata": { "type": 'SP.Data.1125ListItem' },
        "OData__x0063_1":{"results": ['t1', 't2']}

    };

    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {

            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

})
</script>


text:
Q: Django: could not parse the remainder (media i.e. image) I am developing a WebApp using Django.I m a newbie, I have this html file which contains image, i did go through this "link", but now i am getting an error as in parsing the Media Url. Could any let me know what is wrong? I have checked the permissions, even they are correct. !!
This is that image which i am including -
<img border="2" src="{{ MEDIA_URL }}samplelogo.jpg" alt="logo here"/>

This is the urls.py -
from django.conf.urls.defaults import patterns, include, url
import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^gharnivas/$', 'gharnivas.views.index'),
    url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
)

This is the settings.py with media url and root :
MEDIA_ROOT = '/home/nagaraj/ghar/templates/media'
MEDIA_URL = 'http://localhost:8000/media/'

ghar is the django project and gharnivas is the app
Update :
Now I have removed the error of TemplateSyntaxError by replacing Media url to '/media/' as suggested by @Torsten below. But still not getting the image !!
Another query , is it correct that i am using MEDIA_ROOT And MEDIA_URL ? Because some place i even see that they have STATIC_URL and STATIC_ROOT !!

A: MEDIA_URL = '/media/' instead of MEDIA_URL = 'http://localhost:8000/media/'

A: {{ MEDIA_URL }} outputs empty string? Make sure that
1). 'django.core.context_processors.media' is in TEMPLATE_CONTEXT_PROCESSORS
2). You pass RequestContext in your template (by passing context_instance=RequestContext(request) in render_to_response or by using direct_to_template instead).
From Django 1.8 'django.core.context_processors.media' was moved to
'django.template.context_processors.media'


text:
Q: Entry level  hell(p) I'm having some trouble with this code.  I am trying to write a function that allows a user to input a string (of multiple words) and then returns the 1st word.  A simple task with Python but C++ baffels me yet again.  I'm part way there and realize I need to still add the implementation for 1st token but in incremental debugging I've run into some snags.  Questions I'm after are:

*

*Why, when I enter integers, does the function print those on the console?  Shouldn't entering ints cause the cin stream to fail and therefore repromt the user for another entry?

*How can I get the window to pause (maybe waiting for an "enter" from the user) before returning?  It prints and returns so fast it's hard to see what it does.

Here's the code:
/*
* Problem 1: "Extract First String"
* Takes a user string and extracts first token (first token can be a whole word)
*/

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void ExtractFirstToken();

int main()
{
    ExtractFirstToken();
    return 0;
}

/*
* Trying to create a function that will allow a user to enter a string of words and
* then return the first word
*/
void ExtractFirstToken()
{
    cout << "Please enter a string (can be multiple words): ";
    string stringIn;
    while (true)
    {
        cin >> stringIn;
        if (!cin.fail()) break;
        cin.clear();
        cout << "not a string, please try again: ";
    }
    cout << stringIn;
}

A: 1) No. Numbers are perfectly valid as strings.
First write a function that determines if a string is a word, by your definition.  Something like this:
bool IsWord(const std::string & str)
{
    return str.find_first_of("0123456789 \t\n") == std::string::npos;
}

Then:
std::string word;
while(std::cin >> word)
{
    if (IsWord(word)) break;
    cout << "not a word, please try again: ";

}
std::cout << word;

2) Just run your program from the command line.

A: *

*because a string is perfectly capable of holding "12345". Why would it fail?

*I'd say something like std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
 (heh, amusing that my answer is exactly like Benjamin Lindley's, right down to using numeric_limits and streamsize)
This will wait for input until you hit enter.

A: Here's the standard formatted I/O idiom:
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string line;

    std::cout << "Please enter some text: ";
    while (std::getline(std::cin, line))
    {
        std::istringstream iss(line);
        std::string word;

        if (iss >> word)
        {
            std::cout << "You said, '" << line << "'. The first word is '" << word << "'.\n";
            std::cout << "Please enter some more text, or Ctrl-D to quit: ";
        }
        else
        {
             // error, skipping
        }
    }
}

You cannot fail to read a string other than through reaching the end of the input stream, which the user has to signal with Ctrl-D or something like that (Ctrl-Z on MS-DOS). You could add another break condition, e.g. if the trimmed, downcased input string was equal to "q" or so.
The inner loop uses a string stream to tokenize the line. Typically you would process each token (e.g. convert to numbers?), but here we just need one, namely the first word.

A: All printable characters are valid string elements, including digits. So if you want digits to be interpreted as invalid input, you'll have to do the work yourself. For example:
if (stringIn.find_first_of("0123456789") != stringIn.npos)
    cout << "not a valid string, please try again: ";

A: You got a lot of answers for the first part, so I'll help with the second:
system("pause");


text:
Q: How do I query DataDog for a phrase in the stack trace? DataDog is so useless in its querying and its intuitiveness ... I'm looking for a custom exception in the stack trace. I found individual log entries in the last 18 hours that contain my exception class name, but attempting to write a log query that will find me all the occurrences is returning nothing. E.g.:
environment:prod @thrown.extendedStackTrace:UserDoesNotExistException
I'd like to include more words in the query, but even reducing down a single word fails to find anything. I've looked at their documentation, which is zero help.

A: The following worked for me (where my stacktrace is in a stack_trace attribute) after reading the doco and trial and error:
@stack_trace:*the?quick?brown?fox*
i.e. to search on a phrase (multiple words), don't use quotes (so leading/trailing wildcards work) and replace spaces with ?

A: Try adding wildcards on either side of your search query.
For example:
environment:prod @thrown.extendedStackTrace:*UserDoesNotExistException*

Make sure the query value itself (i.e. the value after the colon) isn't wrapped in quotes, as wildcards do not work within quotes since it would be read as a string literal.


text:
Q: Is shrink_to_fit the proper way of reducing the capacity a `std::vector` to its size? In C++11 shrink_to_fit was introduce to complement certain STL containers (e.g., std::vector, std::deque, std::string).
Synopsizing, its main functionality is to request the container that is associated to, to reduce its capacity to fit its size. However, this request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.
Furthermore, in a previous SO question the OP was discouraged from using shrink_to_fit to reduce the capacity of his std::vector to its size. The reasons not to do so are quoted below:

shrink_to_fit does nothing or it gives you cache locality issues and it's O(n) to
  execute (since you have to copy each item to their new, smaller home).
  Usually it's cheaper to leave the slack in memory. @Massa

Could someone be so kind as to address the following questions:

*

*Do the arguments in the quotation hold?

*If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for std::vector).

*And if there's a better way to shrink a container, what's the reason for the existence of shrink_to_fit after-all?

A:

*

*If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for std::vector).

The 'swap trick' will trim a vector to the exact size required (from More Effective STL):
vector<Person>(persons).swap(persons);

Particularly useful when the vector is empty, to release all memory:
vector<Person>().swap(persons);

Vectors were constantly tripping my unit tester's memory leak detection code because of retained allocations of unused space, and this sorted them out perfectly.
This is the kind of example where I really don't care about runtime efficiency (size or speed), but I do care about exact memory usage.

*

*And if there's a better way to shrink a container, what's the reason for the existence of shrink_to_fit after-all?

I really don't know what the point of providing a function that can legally do absolutely nothing is.
I cheered when I saw it had been introduced, then despaired when I found it couldn't be relied upon.
Perhaps we'll see maybe_sort() in the next version.

A:
Do the arguments in the quotation hold?

Measure and you will know. Are you constrained in memory? Can you figure out the correct size up front? It will be more efficient to reserve than it will be to shrink after the fact. In general I am inclined to agree on the premise that most uses are probably fine with the slack.

If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for std::vector).

The comment does not only apply to shrink_to_fit, but to any other way of shrinking. Given that you cannot realloc in place, it involves acquiring a different chunk of memory and copying over there regardless of what mechanism you use for shrinking.

And if there's a better way to shrink a container, what's the reason for the existence of shrink_to_fit after-all?

The request is non-binding, but the alternatives don't have better guarantees. The question is whether shrinking makes sense: if it does, then it makes sense to provide a shrink_to_fit operation that can take advantage of the fact that the objects are being moved to a new location. I.e., if the type T has a noexcept(true) move constructor, it will allocate the new memory and move the elements.
While you can achieve the same externally, this interface simplifies the operation.  The equivalent to shrink_to_fit in C++03 would have been:
std::vector<T>(current).swap(current);

But the problem with this approach is that when the copy is done to the temporary it does not know that current is going to be replaced, there is nothing that tells the library that it can move the held objects. Note that using std::move(current) would not achieve the desired effect as it would move the whole buffer, maintaining the same capacity().
Implementing this externally would be a bit more cumbersome:
{
   std::vector<T> copy;
   if (noexcept(T(std::move(declval<T>())))) {
      copy.assign(std::make_move_iterator(current.begin()),
                  std::make_move_iterator(current.end()));
   } else {
      copy.assign(current.begin(), current.end());
   }
   copy.swap(current);
}

Assuming that I got the if condition right... which is probably not what you want to write every time that you want this operation.

A:

*

*Will the arguments hold?

As the arguments are originally mine, don't mind if I defend them, one by one:

*

*Either shrink_to_fit does nothing (...)
As it was mentioned, the standard says (many times, but in the case of vector it's section 23.3.7.3...) that the request is non-binding to allow an implementation latitude for optimizations. This means that the implementation can define shrink_to_fit as an no-op.

*(...) or it gives you cache locality issues
In the case that shrink_to_fit is not implemented as a no-op, you have to allocate a new underlying container with capacity size(), copy (or, in the best case, move) construct all your N = size() new items from the old ones, destruct all the old ones (in the move case this should be optimized, but it's possible that this involves a loop again over the old container) and then destructing the old container per se. This is done, in libstdc++-4.9, exactly as David Rodriguez has described, by
      _Tp(__make_move_if_noexcept_iterator(__c.begin()),
          __make_move_if_noexcept_iterator(__c.end()),
          __c.get_allocator()).swap(__c);

and in libc++-3.5, by a function in __alloc_traits that does approximately the same.
Oh, and an implementation absolutely cannot rely on realloc (even if it uses malloc inside ::operator new for its memory allocations) because realloc, if it cannot shrink in-place, will either leave the memory alone (no-op case) or make a bitwise copy (and miss the opportunity for readjusting pointers, etc. that the proper C++ copying/moving constructors would give).
Sure, one can write a shrinkable memory allocator, and use it in the constructor of its vectors.
In the easy case where the vectors are larger than the cache lines, all that movement puts pressure on the cache.

*and it's O(n)
If n = size(), I think it was established above that, at the very least, you have to do one n sized allocation, n copy or move constructions, n destructions, and one old_capacity sized deallocation.

*usually it's cheaper just to leave the slack in memory
Obviously, unless you are really pressed for free memory (in which case it might be wiser to save your data to the disk and re-load it later on demand...)

*

*If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for std::vector).

The proper way is still shrink_to_fit... you just have to either not rely on it or know very well your implementation!

*

*And if there's a better way to shrink a container, what's the reason for the existence of shrink_to_fit after-all?

There is no better way, but the reason for the existence of shrink_to_fit is, AFAICT, that sometimes your program might feel memory pressure and it's one way of treating it. Not a very good way, but still.
HTH!


text:
Q: Windows 8 VMWare guest under Ubuntu 16.04 host doesn't have access to the internet I have Ubuntu 16.04 host machine with WMWare Player and Windows 8 guest. The problem is that the guest Windows machine doesn't have access to the internet.
Host Ubuntu 16.04 configuration:
>>> grep VERSION= /etc/*-release
/etc/os-release:VERSION="16.04.3 LTS (Xenial Xerus)"

>>> sudo iptables --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

>>> sudo ufw status
Status: inactive

VMWare configuration:
> vmware --version
VMware Workstation 12.1.0 build-3272444

Windows guest machine:

Testing:

Notes:

*

*Note the ping is ok and nslookup hangs. Looks like host machine is stopping the traffic.

*I tried ssh into host - ok.

*I tried ssh into other machine within the Local lo network of the host - ok

*The gateway in the network config is set to 172.16.223.2. I tried to change that to the IP of the host (172.16.223.1) - same results.

A: My case was really simple. For some reason VMWare hasn't picked up proper DNS's of the host and 8.8.8.8 and 8.8.4.4 are blocked within the internal network. Setting DNS servers manually within Windows to the IPs that are allowed within internal network fixed the issue.
I am marking the question as resolved, but if smb posts a solution to fix the VMWare to pick-up the DNS's of the host, I will switch to his answer.


text:
Q: How to get the correct value? I want to allow user to input the key that they are looking for and then print out the corresponding key and values. However, if I use the following code, it prints out the correct key but wrong value
Example of text file :
apple (key)
sweet
red in colour
small
Grape (key)
purple
comes in different colour
small
juicy
name = (input("Type fruit name : "))
f = open(myfile, 'r+')
for key in f:
    if name in key:
        print({key:value})


text:
Q: How do you plot with multiple colours for the same point? I have some data that I have clustered, and wish to compare it to human-annotations of the same data. The problem I have is that the human-annotator has marked some of the points to have co-existing events (i.e. some points in the space would have two or more labels associated with them). Is there a way that I can show this using matplotlib?
I am thinking something along the lines of the following simplified example:

The main point is to not have the points with events 1 & 2 be classified as some new event '3', but instead to plot the points that have two events, to display these events independently. I assume that this is not an easy task, as there could potentially be more than two coexisting events, but for this example I am only focussing on two.

My plan was to create a one-hot array of shape=(n_points, n_events), and linearly selecting colours for a colourmap by using plt.cm.rainbow which would represent each unique event. But I have gotten stuck here as I do not know how to plot the points with >1 label.
The style in which the points are plotted does not strictly matter (i.e. having the side-by-side colours as I have illustrated is not a requirement), any method of displaying them should be adequate so long as points with multiple events are easily identifiable.
I would post my attempt so far, but as I am stuck on such an early step, it only goes as far as generating a random toy dataset of shape (20, 2), and creating the one-hot array of labels as I had previously mentioned.

A: You can specify color as well as markerfacecoloralt together with fillstyle='left' in order to obtain a side-by-side color plot. For more information and other styles see this tutorial.
import matplotlib.pyplot as plt
import numpy as np

x = np.sort(np.random.random(size=20))
y = x + np.random.normal(scale=0.2, size=x.shape)

i, j = len(x)//2 - 2, len(x)//2 + 3  # separate the points in left and right

colors = ['#1f77b4', '#ff7f0e']

fig, ax = plt.subplots()
ax.plot(x[:i], y[:i], 'o', color=colors[0], ms=15)  # left part
ax.plot(x[j:], y[j:], 'o', color=colors[1], ms=15)  # right part
ax.plot(x[i:j], y[i:j], 'o',                        # middle part
        fillstyle='left', color=colors[0], markerfacecoloralt=colors[1], ms=15)

plt.show()

Example plot:

A: If you don't require side-by-side colors you could plot two points on top of each other, using different sizes.
import matplotlib.pyplot as plt
import numpy as np

x = np.sort(np.random.random(size=20))
y = x + np.random.normal(scale=0.2, size=x.shape)

i, j = len(x)//2 - 2, len(x)//2 + 3  # separate the points in left and right

colors = ['#1f77b4', '#ff7f0e']

fig, ax = plt.subplots()
ax.scatter(x[:j], y[:j], c=colors[0], s=100)  # left part (including middle)
ax.scatter(x[j:], y[j:], c=colors[1], s=100)  # right part
ax.scatter(x[i:j], y[i:j], c=colors[1], s=20)  # middle part (using smaller size)

plt.show()

Example plot:


text:
Q: How to add 3 chars into a single char in C? I have char arrays like this:
char a[6] = {49, 50, 54, 49, 49, 54}; // ASCII '1', '2', '6', '1', '1', '6'
char b[2];

I want to convert a[0], a[1], a[2] into b[0], and a[3], a[4], a[5] into b[1]. So that I can have like this:
b[0] = 126;
b[1] = 116;

How can I do that?

A: You can do it like this:
b[0] = (a[0] - '0') * 100 + (a[1] - '0') * 10 + (a[2] - '0');

and similarly for b[1].
Note that if the characters in a are non-numeric, or represent a value outside the range that can be stored in a char, then the result will be undefined.

A: It appears that you are transforming decimal representations to bytes. sscanf can help you deal with this as follows:
char a[6] = {49, 50, 54, 49, 49, 54};
signed char b[2];
sscanf(a, "%3hhi%3hhi", &b[0], &b[1]);

Demo.


text:
Q: In angular 8 data input data binding is not working? This question is asked multiple times before and I satisfied with the all the solutions provided. But I am stuck in the basic problem, ie. how to get the data from the parent component to the child component. Don't know what I am doing wrong here!!!
app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  message: string = "Hello World!";

  constructor() {
    //
  }

  ngOnInit() {
    //
  }
}

app.component.html

        <app-menu></app-menu>

            <router-outlet></router-outlet>

        <app-footer></app-footer>

footer.component.ts
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss']
})

export class FooterComponent implements OnInit {

  @Input() message: string;

  constructor() {}

  ngOnInit() {
    console.log(this.message);
  }

}

The ngOnInit() function call on the footer.component.ts always returns undefined

A: You haven't bound the app-root's message to the child component. Templates are isolated from each other and doesn't inherit any attributes from the parent that renders them. Instead, you must pass data to the templates using data-binding.
Try this:

    <app-footer [message]="message"></app-footer>

Please see Template Syntax


text:
Q: Opening a file on a shared drive blocks access to other users I access a lot of shared files on a Windows-based networked drive (CIFS) for work. There is an annoying issue that effects other people only when when I'm accessing a file from my Ubuntu machine.
Here is the usual scenario where nothing bad happens:

*

*Windows/Mac User #1 opens a file on the network drive

*User #2 (any OS) tries to open that same file while User #1 still
  has it open.

*User #2 see a popup that says the file is in use, but user #2 will be  given an option to open a read-only copy.

However, if the Ubuntu user opens the file first, something different happens. Here is the scenario where the failure happens:

*

*Ubuntu User #1 opens a file on the network drive

*User #2 (any OS) tries to open that same file while Ubuntu User #1
  still has it open

*User #2 will get an error saying "the file is in use" and is NOT
  given the option to open a read-only copy.

Is there anyway to modify my settings to allow other users to view a read-only copy of a shared file while I am accessing it from Ubuntu?


text:
Q: How to hide warnings in compilation from external libraries I have a main.cpp file which only has this code:
#include <iostream>
#include "include/rapi/RApi.h"

using namespace std;

int main() {
    std::cout << "Test\n";
    return 0;
}

When I compile, I want to see warnings from my code, but not from external included files. I have been able to achieve this in the past, but I might be missing something here in the compilation flags, as I keep on seing errors from the included header file, when I don't want to see them.
This is my compile command:
g++ -isystem include -pedantic -Wall -Wextra main.cpp -o main.o

I want to see warnings and errors from main.cpp, but not from files in the include folder.
I have tried -isysteminclude -isysteminclude/rapi, passing the -isystem to the end of the flags, but to no avail.
Am I missing something here?

A: You need to add -isystem include to your compile line, then ALSO in your code use:
#include "rapi/RApi.h"

(not include/rapi/RApi.h). The -isystem option only applies the "system header" attribute to files that are looked up using that search path.  If you put the full path in the #include then GCC looks up the path directly and doesn't use the -isystem path, so the "system header" attribute is not applied.
Regarding using <> vs "", the exact difference in behavior is essentially implementation-defined.  There is no need to guess, just look at various SO questions and answers, such as this one.

A: #include <iostream>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#include "include/rapi/RApi.h"
#pragma GCC diagnostic pop

int main() {
  std::cout << "Test\n";
  return 0;
}


text:
Q: How to remove every nth term in a Python list I need to solve a problem using Python. I can solve the problem without code and if you search the internet the answer is public. I am having trouble in getting my code to work to solve this question. Anyways, here is the question:

Steve wrote the digits 1, 2, 3, 4, and 5 in order repeatedly from left
to right, forming a list of 10,000 digits, beginning 123451234512....
He then erased every third digit from his list (that is, the 3rd, 6th,
9th, ... digits from the left), then erased every fourth digit from
the resulting list (that is, the 4th, 8th, 12th, ... digits from the
left in what remained), and then erased every fifth digit from what
remained at that point. What is the sum of the three digits that were
then in the positions 2019, 2020, 2021?

I have written out the python code to print out all the numbers into a list. I need to figure out how to remove every nth digit.
list = []
value = 1
for i in range (10000):
    list.append (value)
    value = value + 1
    if value == 6:
        value = 1

That is the code for writing out the first 10,000 digits.
In a previous class I have written out a code to remove every nth term and prints it out. That code is shown below:
n = 3
def RemoveThirdNumber(int_list):

    pos = n - 1
    index = 0
    len_list = (len(int_list))

    while len_list > 0:

        index = (pos + index) % len_list

        print(int_list.pop(index))
        len_list -= 1

nums = [1, 2, 3, 4]
RemoveThirdNumber(nums)

print(list)

I need help in changing that code so it goes through the list once removing every third term and prints out the remaining numbers.
So that means that instead of the output being
3
2
4
1

it will be
[1,2,4]

Thanks for trying to help!

A: Here's a solution I came up with. I'm not a fan of having to turn each slice into a tuple, just to consume from the iterator and have chunk potentially equal something falsey. Maybe someone can look it over and let me know if I've made a mistake somewhere? Or just suggest other cute itertools recipes. Apparently, the sum of the three digits is 10:
from itertools import cycle, islice

digits = islice(cycle([1, 2, 3, 4, 5]), 10000)

def skip_nth(iterable, n):
    while chunk := tuple(islice(iterable, n)):
        yield from islice(chunk, n-1)

sum_of_digits = sum(islice(skip_nth(skip_nth(skip_nth(digits, 3), 4), 5), 2019, 2022))
print(sum_of_digits)

Output:
10

EDIT - As per Matthias' suggestion:
def skip_nth(iterable, n):
    yield from (value for index, value in enumerate(iterable) if (index + 1) % n)

A: a = [1,2,3,4,5] * (10000//5)
a = [a[i] for i in range(len(a)) if i%3 != 2]
a = [a[i] for i in range(len(a)) if i%4 != 3]
a = [a[i] for i in range(len(a)) if i%5 != 4]

print(a[2019:2022])  # --> [2, 5, 3]
print(sum(a[2019:2022]))  # --> 10

A: Tested with 100 only.
bigList = []
value = 1
for i in range (100):
    biglist.append(value)
    value += 1
    if value == 6:
        value = 1

# if you print here you get [1,2,3,4,5,1,2,3...]
x = 3
del biglist[x-1::x] #where x is the number of "steps" - in your case 3
# if you print here - biglist ==> 1,2,4,5,2,3 etc..

A: An inplementation could be this right here.
def RemoveThirdNumber(int_list,every):
    rList=[]
    i=0
    for element in int_list:
        i+=1
        if i%every!=0:
            rList.append(element)
    return rList

nums = range(1,101)

print(RemoveThirdNumber(nums,3))

A: I hope I understand your question.
If I do, instead of writing all of that, why not write fewer codes if you're going to remove every third item. And, avoid reserved words..instead of using 'list' as a variable name, use something like 'lst' or something else
lst = []
val = 1
for i in range(10000):
    lst.append(val)
    val = val + 1
    if val == 6:
        val = 1

def remove_third_item(your_list):
  for i in your_list:
      if i%3==0:
          your_list.remove(i)
  return your_list

print(remove_third_item(lst))

A: First thing- try to not use Python built in names as "list" to name your variables. It may cause problems.
Try to use filter method.
values_list = []
value = 1
for i in range(10000):
    values_list.append(value)
    value = value + 1
    if value == 6:
        value = 1

filtered = filter(lambda x: (values_list.index(x) + 1) % 3 != 0, values_list)

filtered_to_list = [element for element in filtered]

print(filtered_to_list)

FIlter returns generator, that's why used list comprehension to get its elements.
Lambda functions checks if it is third element of list ( + 1 to its index, because indexing starts at 0 and 0 % 0 == 0, so then it'll remove 1st element as well)
I'm also newbie, but I hope that was helpful.


text:
Q: Execute sudo without Password? Inspired by this question....
I am the sole person using my system with 12.04.
Every time I issue a sudo command; the system asks for the user password (which is good in its own way).
However I was thinking; without activating the root account; how can I execute the sudo commands which will not ask for user password to authenticate.
NOTE: I want to execute sudo command without authenticating via password; only when they are executed via terminal.
I don't want to remove this extra layer of security from other functions such a while using 'Ubuntu software center' or executing a bash script by drag-drop something.sh file to the terminal.

A: Of course what you want to do isn't recommended. After a while, though entering sudo becomes so automatic that its usefulness diminishes.
Another approach is to leave your sudoers file as is and, while doing something complicated to your umpteen hundred servers, enter sudo bash . That will give you a shell that will be authenticated as root until you exit it.

A: You can configure sudo to never ask for your password.
Open a Terminal window and type:
sudo visudo

In the bottom of the file, add the following line:
$USER ALL=(ALL) NOPASSWD: ALL

Where $USER is your username on your system.
Save and close the sudoers file (if you haven't changed your default terminal editor (you'll know if you have), press Ctl + x to exit nano and it'll prompt you to save).
As of Ubuntu 19.04, the file should now look something like
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

YOUR_USERNAME_HERE ALL=(ALL) NOPASSWD: ALL

After this you can type sudo <whatever you want> in a Terminal window without being prompted for the password.
This only applies, to using the sudo command in the terminal. You'll still be prompted for your password if you (for example) try to install a package from the software center

A: Nice one-liner to remove sudo prompts for the current user
sudo bash -c 'echo "$(logname) ALL=(ALL:ALL) NOPASSWD: ALL" | (EDITOR="tee -a" visudo)'

A: From Super User comes a good answer:
Use the -S switch which reads the password from STDIN:
echo <password> | sudo -S <command>

Replace <password> with your password.

A: This is a one line solution that also changes files permissions as stated in /etc/sudoers.d/README:
sudo sh -c 'echo "$(logname) ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/$(logname)' && sudo chmod 440 /etc/sudoers.d/$(logname)

A: The preferred way to grant individual (or group) permissions would be to add files under /etc/sudoers.d
This separates local changes from the default policy and saves time in case the distribution sudoers file changes.
To make the currently logged in user a a sudoer and make sudo not prompt them for a password, use
echo "$USER ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/$USER

this will create a file called /etc/sudoers.d/$USER (where $USER is the username of the user that you were logged in as when you ran that command), making it clear which users are granted permission.
If you want to do that for a different user, just replace both instances of $USER with some other username in the above command.
echo "otheruser ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/otheruser

Similarly, one file can be used to manage multiple directives:
echo "username ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee -a /etc/sudoers.d/local

See /etc/sudoers.d/README and man sudoers for more information.

A: One liner
sudo sed -i /etc/sudoers -re 's/^%sudo.*/%sudo   ALL=(ALL:ALL) NOPASSWD: ALL/g'

A: Root sudo timeouts are the easiest and safest way of doing this. I'll lay out all examples but be warned it is very risky any way you do this although this way is much safer:
sudo visudo

This opens an editor and points it to the sudoers file -- Ubuntu defaults to nano, other systems use Vi. You're now a super user editing one of the most important files on your system. No stress!
(Vi specific instructions noted with (vi!). Ignore these if you're using nano.)
Use the arrow keys to move to the end of the Defaults line.
(vi!) press the A (capital "a") key to move at the end of the current line and enter editing mode (append after the last character on the line).
Now type:
,timestamp_timeout=X

where X is the timeout expiration in minutes. If you specify 0 you will always be asked the password. If you specify a negative value, the timeout will never expire. E.g. Defaults env_reset,timestamp_timeout=5.
(vi!) hit Escape to return to command mode. Now, if you're happy with your editing, type in :w Enter to write the file and :q Enter to exit vi. If you made a mistake, perhaps the easiest way is to redo from start, to exit without saving (hit Escape to enter the command mode) and then type :q! Enter.
Hit Ctrl+X, then Y, then Enter to save your file and exit nano.
You might want to read the sudoers and vi manual pages for additional information.
man sudoers
man vi

Reset timeout value using:
sudo -k

These instructions are to remove the prompt for a password when using the sudo command. The sudo command will still need to be used for root access though.
Edit the sudoers file
Open a Terminal window. Type in sudo visudo. Add the following line to the END of the file (if not at the end it can be nullified by later entries):
<username> ALL=NOPASSWD: ALL

Replace <username> with your username (without the <>). This is assuming that Ubuntu has created a group with the same name as your user name, which is typical. You can alternately use the group users or any other such group you are in. Just make sure you are in that group. This can be checked by going to System -> Administration -> Users and Groups.
Example:
michael ALL=NOPASSWD: ALL

Type in ^X (Ctrl+X) to exit. This should prompt for an option to save the file, type in Y to save.
Log out, and then log back in. This should now allow you to run the sudo command without being prompted for a password.
The root account
Enabling the root account
Enabling the root account is rarely necessary. Almost everything you need to do as administrator of an Ubuntu system can be done via sudo or gksudo. If you really need a persistent root login, the best alternative is to simulate a Root login shell using the following command:
sudo -i

However, if you must enable root logins, you can do it like this:
sudo passwd root

Re-disabling your root account
If for some reason you have enabled your root account and wish to disable it again, use the following command in the terminal:
sudo passwd -dl root

System-wide group sudo
root$ echo "%sudo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

Log out, and then back in.
Reset sudo timeout
You can make sure sudo asks for password next time by running:
sudo -k

A: *

*Expanding on @upteryx idea.

*This is how I've implemented the non-root, passwordless user in an ephemeral Docker Image for use in a CICD pipeline:
RUN \
    groupadd -g 999 foo && useradd -u 999 -g foo -G sudo -m -s /bin/bash foo && \
    sed -i /etc/sudoers -re 's/^%sudo.*/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^root.*/root ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^#includedir.*/## **Removed the include directive** ##"/g' && \
    echo "foo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
    echo "Customized the sudoers file for passwordless access to the foo user!" && \
    echo "foo user:";  su - foo -c id

A: To never prompt the current user for a password when that user uses sudo run this command:
echo "$USER ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/dont-prompt-$USER-for-sudo-password

A: Open sudo config:
sudo visudo

add following line:
# Defaults specification
Defaults:username  !authenticate

where username is your usesrname.

A: sudo -i is the way to go if you don't want to be typing a password every 10 mins while doing modifications in your system (or other systems), and you don't want to modify any system files.
It will switch you to root using your sudo user password, when you close the console or type exit you are back to your normal user.


text:
Q: FFTW _GNUC_ is not defined as a preprocessor macro I have linked a FFTW library to the Unreal Engine project from this website. But now when I try to include the header file to my project, I get error:

'__GNUC__' is not defined as a preprocessor macro,
  replacing with '0' for '#if/#elif'

I have no idea how to fix this. I don't want to mess with the code itself, because I think it is perfectly fine. Did I forget something when linking the library? I've also tried including the header file as a C library.
Any help would be appreciated.
IDE: Visual Studio 2017 Community
OS: Windows 10 Pro 64x
UE4 Version: 4.20

A: UnrealEngine seems to treat many warnings as errors, so this causes trouble when trying to use with 3rd party libraries that produce those warnings. Usually it's best to fix code to avoid the warning, but I would assume you can't for whatever reason.
In this particular case you could set:
bEnableUndefinedIdentifierWarnings = false;

Inside your *.Build.cs class constructor.

If this wasn't UnrealEngine, but still Visual Studio C++, you could also try putting this before code that causes the warning (e.g. before including header in which you get the warning):
#pragma warning(disable: 4668)

https://learn.microsoft.com/en-us/cpp/preprocessor/warning?view=vs-2019
Or disable it as compilation flag:
/wd4668

https://learn.microsoft.com/en-us/cpp/build/reference/compiler-option-warning-level?view=vs-2019
In general, if you get something you feel shouldn't be an error, search web if given error number (here C4668) is not usually a warning. If it is, then this allows quick hacks like above.


text:
Q: Unix symbol \!* in alias cd 'chdir \!* && set prompt="${cwd} >"' I'm unable to understand use of symbol \!* in the following alias statement
alias cd 'chdir \!* && set prompt="${cwd} >"'. This is related to csh

A: The alias defines a command. This command can be launched with arguments, so the pattern !* represents the arguments that will be passed to the alias. For the definition to be correct, the symbol ! is de-specialized with \! to prevent the replacement to operate during the alias definition but during the alias usage.
If you call it with cd a b c d, this would be like you type chdir a b d c d && set prompt="${cwd} >"


text:
Q: Why is it - "My great-grandfather never left Scotland" Instead of " My great-grandfather has never left Scotland"? Since, the sentence has "never" it must be present perfect, but whereas it's simple past. Why is it so?

A: You are mistaken: never does not require present perfect.
In fact, present perfect is very awkward here unless your great-grandfather is still alive when you utter this sentence. The present perfect is a present tense, and cannot ordinarily be used with a deceased subject†, because the subject no longer exists to sustain a present-tense predication.

† There are exceptions: cases where the writer or author of a still-present work is deemed to be metaphorically present and speaking through the work, and cases where the subject is not the actual topic—the classic example is "Einstein has visited Princeton", which is ordinarily unacceptable but becomes grammatical in a larger context where Princeton is the actual topic "Many celebrities have visited Princeton: Carnegie has visited Princeton, Einstein has visited Princeton, Madonna has visited Princeton."


text:
Q: c++ libraries for dealing with distributed matrices on a grid Which c++ libraries (or libraries in Fortran with c++ interfaces) do you recommend for doing BLAS or Sparse BLAS operations on distributed matrices in terms of speed and ease of use?

A: Use PBLAS directly. I don't happen to know of any C++ library to ease this. There is http://cppscalapack.sourceforge.net/, but it seems not maintained any more (last update in 2004) and in an alpha stage.
Distributed linear algebra is quite cumbersome to do, and this will involve a lot of work whatever library you happen to use. I therefore think that using PBLAS directly, abstracting the computations in classes as you go is a quite sensible thing to do: understanding the Fortran interface is not the hard part of the problem.


text:
Q: how can i run MPI program in windows I tried running it with microsoft MPI but its not generating desired output.
#include <stdio.h>
#include <math.h>
#include "mpi.h"

double function(double x) {
    // Define the function to be integrated here
    return x * sin(x);
}

int main(int argc, char *argv[]) {
    double a, b, h, sum, x;
    int n, p, rank, size, i;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (rank == 0) {
        printf("Enter the number of subintervals (n): ");
        scanf("%d", &n);
        printf("Enter the number of processes (p): ");
        scanf("%d", &p);
    }

    // Broadcast the inputs to all processes
    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&p, 1, MPI_INT, 0, MPI_COMM_WORLD);

    a = 0.0;
    b = 1.0;
    h = (b - a) / n;
    sum = 0.0;

    // Divide the work among the processes
    int interval_per_process = n / p;
    int start = rank * interval_per_process;
    int end = (rank + 1) * interval_per_process - 1;

    for (i = start; i <= end; i++) {
        x = a + h * (i + 0.5);
        sum = sum + function(x);
    }

    sum = sum * h;

    // Reduce the results from all processes to process 0
    double global_sum;
    MPI_Reduce(&sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        printf("The value of the integral is %.6lf\n", global_sum);
    }

    MPI_Finalize();

    return 0;
}

So I need output like : It should ask for subintervals and processes and then give the final result i.e answer of integration using the midpoint rule.
But instead when i run it displays nohting and if enter any number it skips the scanner part and directly produce the output
I need a compiler


text:
Q: Cannot access custom agent parameters I'm trying to make a traffic simulation model in Anylogic. I made a custom car agent (the_car) and it has two parameters. I cannot access the parameters of car agent in StopLine "On passed Car Action". It is showing the error "Cannot make a static reference to the non-static field the_car.parameter".
String i =  the_car.parameter; //the error is in this line.

A: You need to tell your process blocks that it is the_car type agents passing through. Likely, you use a CarSource object, set it up such that it creates not default "Agent" agents but your the_car agents.
Then, you need to understand how code fields work. They often have specific keywords that refer to functionality, see my blog post. You will need to write String i = agent.parameter


text:
Q: Unable to "run as different user" in windows 7 I am not able to "run as different user" in my windows 7 (domain login) machine.
For example if i'm trying to start iexplore (run as diff user) It returns the error :
"The system cannot find the file specified".


text:
Q: BarButtonItem malformed after switch to Swift 4 After upgrading to Swift 4, the code I used to add a custom UIBarButtonItem no longer works, and instead, squeezes the image in a peculiar fashion:

  // In viewDidLayoutSubviews
  if let backButton = Utils.createBackButton(color: .white, target: self, selector: #selector(LoginViewController.backPressed)) {
        navigationItem.leftBarButtonItem = backButton
        print("navigation button width", backButton)
    }

// In Utils.swift
class func createBackButton(color: BackArrowColors, target: UIViewController, selector: Selector) -> UIBarButtonItem? {
    var backImage = UIImage()
    if color == .white {
        backImage = UIImage(named: "back-arrow-white.png")!
    } else if color == .black {
        backImage = UIImage(named: "back-arrow-black.png")!
    } else {
        return nil
    }

    let backButton: UIButton = UIButton(type: UIButtonType.custom)
    backButton.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
    backButton.contentMode = UIViewContentMode.scaleAspectFit
    backButton.setImage(backImage, for: .normal)
    backButton.addTarget(target, action: selector, for: .touchUpInside)
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10)
    let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: backButton)
    return leftBarButtonItem
}

It seems the frame is correct, in the console I get the following console message:
navigation button width <UIBarButtonItem: 0x7fb3d7c0d010> view=<UIButton: 0x7fb3d7c20ae0; frame = (0 0; 35 35); opaque = NO; layer = <CALayer: 0x60c000238b40>>

Any ideas? Thanks guys!

A: This is a known bug with current iOS 11 release. UIBarButton items now uses constraints instead of the earlier frame approach.
Follow this and this for solution or more explanation.
And this link helps with the new implementation.