text:
Q: Can I make a seperate HTML file for devices like mobile and tabs for my website? I have made and published my website. I want to make it compatible with mobiles without using media queries as for that I have to change the whole code. Is it possible to have separate HTML files for mobiles? If yes, how to link that to desktop version?

A: It is possible if you filter it server side looking at user agent. But i cant say ive ever seen it done and it sounds like bad practice. A general rule of programming would be to avoid duplicating code. Or dont repeat yourself as the principle is called.
If your mobile code is simple too different from the desktop code that you cant use media queries i would sugest just putting two sections on the page and using said media queries to show one and not the other.


text:
Q: Amazon S3 bucket policy for uploading and viewing pictures I have an app that users log in with facebook and then can upload images to s3 bucket and view them. I used Cognito service to allow every logged in user to upload and view all files.
I have no idea how to set the correct permissions on the s3 bucket. This is my attempt at it, but I get can't save the policy and get Statement is missing required element - Statement "NO_ID-0" is missing "Principal" element
{
    "Version": "2012-10-17",
    "Id": "Policy1457546546214",
    "Statement": [
        {
            "Sid": "Stmt1475657256771436",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        },
        {
            "Sid": "Stmt16577654572138125",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": [
                "bucket-name/identity-pool-id*"
            ]
        }
    ]
}

This is the client part, if it helps:
FB.login(function (response) {
    if (response.authResponse) {

      AWS.config.region = 'eu-west-1';
      AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'eu-west-1:xxxxxxxxxxx',
        Logins: {
          'graph.facebook.com': response.authResponse.accessToken
        }
      })

      var bucket = new AWS.S3({params: {Bucket: 'name'}})
      var fileChooser = document.getElementById('file-chooser')
      var button = document.getElementById('upload-button')

      button.addEventListener('click', function() {
        var file = fileChooser.files[0]
        var params = {Key: file.name, ContentType: file.type, Body: file}
        bucket.upload(params, function (err, data) {
        ...

Cognito IAM > Roles > Cognito_myappAuth_Role:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "cognito-identity:*"
            ],
            "Effect": "Allow",
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::bucket/${cognito-identity.amazonaws.com:sub}/*",
                "arn:aws:s3:::bucket/${cognito-identity.amazonaws.com:sub}"
            ]
        }
    ]
}

A: Have you checked out this blog post? It has a good example of how to set up a role that allows S3 bucket access for users. Cutting out the list bucket part out, the access policy you would link to your identity pool roles might look something like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::mybucket/${cognito-identity.amazonaws.com:sub}/*"]
    }
  ]
}

Edit:
Tl;dr from comments for future readers:

*

*Apply the policy to the pool's auth role instead of bucket

*If the app use case requires a common area, use the bucket root directory, otherwise use a directory for each identity defined in the policy (as described in the blog)

*The role itself doesn't apply until after the authentication occurs. The policy just defines what the credentials given back will have access to do and to what.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php gd выравнивание многострочного текста по середине Получается выравнивание по правому краю, и если для однострочного текста я могу самостоятельно задать отступы ($padLeft - отступ слева), то для двух и более строк никак, для вывода текста пользуюсь стандартным вызовом:

imagettftext($im, 12, 0, $padLeft, $padTop, $textColor, $font, "строка1

\nстрока2");

A: function text_center ($im, $str, font, $textColor, $pad_left, $padTop, $width_text, $font_size )
{
    $arr = explode(' ', $str); $ret = "";
    foreach($arr as $word){
        $tmp_string = $ret.' '.$word;
        $testbox = imagettfbbox($font_size, 0, $font, $tmp_string);
        if($testbox[2] > $width_text) $ret.=($ret==""?"":"\n").$word;
        else $ret.=($ret==""?"":" ").$word;
     }
    $arr = explode("\n", $ret);
foreach($arr as $str){
    $testbox = imagettfbbox($font_size, 0, $font, $str);// Размер строки
    $left_x = round(($width_text - ($testbox[2] - $testbox[0]))/2);
    imagettftext($im, $font_size, 0, $left_x +$pad_left, ($padTop), $textColor, $font, $str);
    $padTop=$padTop+ $font_size*1.5;
    }
}

A: Выводите и выравнивайте каждую строку отдельно. Рабочий пример такой ровнялки тут:


text:
Q: Decompiling an ARM asm back to C I wrote a nice ARM assembler routine a few years back and it has done its job beautifully over the years on the ARM embedded systems it was designed for.  Now, the time has come to port it on to non-ARM systems and I was wondering if there was tool or some sort of method to take my original ARM assembler source and get a rudimentory C file from it.  I could probably do it myself in a couple of days, but it would be nice to have a starting point.  Nicer still if the app or method was free :)
Any suggestions?

A: Hex-Rays Decompiler plugin for IDA Pro can decompile ARM. It's somewhat expensive, so probably not the best choice if you need just one routine.

A: I don't know such a tool unfortunately... Would be nice... ; )
So the only suggestion I can give is to concentrate on the logic.
You wrote assembly code. So you know what to code is supposed to do. Converting it to C code shouldn't be that hard, even with ARM assembly.
I mean porting C to ARM assembly can be a difficult task. But for the reverse option, if you know the code logic, and if you know how to write C, it should be just ok...
Creates C structures to ease the memory regions you are working with. About the algorithms, they won't change. Just translate what you are doing from assembly to C, with the help of some structs, etc...
Sorry I can give you such a tool...
Good luck : )

A: You can using radare2 decompiler plugin (r2dec), it convert asm to pseudo-C. But I think converting manually very interesting.


text:
Q: call to DJISDKManager.getInstance() hangs I am trying to register a app with the DJI android SDK, but the call to DJISDKManager.getInstance() just hangs.
I am following the tutorial here: https://developer.dji.com/mobile-sdk/documentation/application-development-workflow/workflow-integrate.html
After the app verifies it has all the required permissions it calls startSDKRegistration:
I have the call to DJISDKManager.getInstance() on a single line for testing.  It hangs on the call, and doesn't throw any errors.
private void startSDKRegistration() {
        if (isRegistrationInProgress.compareAndSet(false, true)) {
            Thread registrationThread = new Thread() {
                @Override
                public void run() {
                    showToast("registering, pls wait...");
                    try {
                        DJISDKManager temp = DJISDKManager.getInstance();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(), new DJISDKManager.SDKManagerCallback() {
                        @Override
                        public void onRegister(DJIError djiError) {
                            if (djiError == DJISDKError.REGISTRATION_SUCCESS) {
                                showToast("Register Success");
                                DJISDKManager.getInstance().startConnectionToProduct();
                            } else {
                                showToast("Register sdk fails, please check the bundle id and network connection!");
                            }
                            Log.v(TAG, djiError.getDescription());
                        }

                        @Override
                        public void onProductDisconnect() {
                            Log.d(TAG, "onProductDisconnect");
                            showToast("Product Disconnected");
                            notifyStatusChange();

                        }
                        @Override
                        public void onProductConnect(BaseProduct baseProduct) {
                            Log.d(TAG, String.format("onProductConnect newProduct:%s", baseProduct));
                            showToast("Product Connected");
                            notifyStatusChange();

                        }

                        @Override
                        public void onProductChanged(BaseProduct baseProduct) {
                            // there was nothing in the tutorial for this method
                        }

                        @Override
                        public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent,
                                                      BaseComponent newComponent) {

                            if (newComponent != null) {
                                newComponent.setComponentListener(new BaseComponent.ComponentListener() {

                                    @Override
                                    public void onConnectivityChange(boolean isConnected) {
                                        Log.d(TAG, "onComponentConnectivityChanged: " + isConnected);
                                        notifyStatusChange();
                                    }
                                });
                            }
                            Log.d(TAG,
                                    String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
                                            componentKey,
                                            oldComponent,
                                            newComponent));

                        }
                        @Override
                        public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {

                        }

                        @Override
                        public void onDatabaseDownloadProgress(long l, long l1) {

                        }
                    });
                }
            };

            GlobalParams.getInstance().getThreadPool().submit (registrationThread);

        }

  private void notifyStatusChange() {
        mHandler.removeCallbacks(updateRunnable);
        mHandler.postDelayed(updateRunnable, 500);
    }

    private Runnable updateRunnable = new Runnable() {

        @Override
        public void run() {
            Intent intent = new Intent(FLAG_CONNECTION_CHANGE);
            sendBroadcast(intent);
        }
    };

    private void showToast(final String toastMsg) {

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_LONG).show();
            }
        });

    }

A: The problem occurs after Android Gradle plugin version 3.6.0+
https://developer.android.google.cn/studio/releases/gradle-plugin#3-6-0-behavior

Native libraries packaged uncompressed by default
When you build your app, the plugin now sets extractNativeLibs to "false" by default. That is, your native libraries are page aligned and packaged uncompressed. While this results in a larger upload size, your users benefit from the following:
Smaller app install size because the platform can access the native libraries directly from the installed APK, without creating a copy of the libraries.
Smaller download size because Play Store compression is typically better when you include uncompressed native libraries in your APK or Android App Bundle.
If you want the Android Gradle plugin to instead package compressed native libraries, include the following in your app's manifest:

<application
    android:extractNativeLibs="true">
</application>

A: Question: What is the setting for minSdkVersion and targetSdkVersion?
I ask because there is a known issue with the values.  I don't remember exactly but setting  the following should work.
minSdkVersion 22
targetSdkVersion 29


text:
Q: Add Invitees to calendar event programmatically iOS I've been trying to look for the answer to this quite some time.
Apple EventKit documentation isn't allowing changing meeting invitees programmatically since those properties in an EKEvent are read-only.
I'm trying to find a way to create a calendar meeting (not necessary using EventKit), adding invitees to the meeting and setting it programatically.
Any solution will be great,
Thanks!

A: As you already figured out you cannot currently write meeting fields in iOS (AFAIK EventKit is the only API giving you access to the calendar database on iOS).
If you know what kind of account it is (and get the credentials from the user), you could sidetrack EventKit and directly create meetings on the server. Eg using EWS when the account is on Exchange or CalDAV when the account is on iCloud or Apple Calendar Server etc.
And finally you always have the option to send out meeting invites via iMIP. Though you would still need to get the event into the users calendar (so that replies have a target). Depends on your useless whether this is useful.


text:
Q: SQL - Filter rows with the same foreign key as a group I'm trying to filter rows with the same foreign ID as a whole group.
(Meaning that WHERE col1 = 'foo' AND col1 = 'bar' would be applicable to the whole group, and would only return foreign IDs where col1 have rows with 'foo' and 'bar')
I have table with pageviews. Each pageview contains its url, and is a part of a user session. I need to filter only sessions which pageviews contains some words.
Let's say I want to filter sessions where the user visited both '/basket-step-1' and '/basket-finish'. (it has to work also with negation, ie visited step-1  but didn't visit finish)
I cannot simply use JOIN and then WHERE on the pageview.url because one pageview can never contain multiple urls.
something like this would work in theory:
SELECT * FROM session WHERE id IN
(
    SELECT session_id FROM pageview
    GROUP BY session_id
    HAVING array_agg(url) ILIKE '%step-1%' AND ILIKE '%finish%'
)

however, you cannot use ILIKE in HAVING and would probably be quite slow. I'm now out of ideas as how to approach creating this query.

A: You can use having along with conditional aggregation:
select s.*
from session s
where s.id in (select session_id
               from pageview pv
               group by session_id
               having sum(case when url ilike '%step-1%' then 1 else 0 end) > 0 and
                      sum(case when url ilike '%finish%' then 1 else 0 end) > 0
             );

If you wanted negation, you would just use = 0 instead of > 0.


text:
Q: Deny from all folders except /index.php and two folders This is an odd configuration, I'll give you that, but I'm looking to deny access to all folders in our system but it must be able to access,
/index.php (Wordpress bootloader)
/wp-*/* (e.g. wp-content, wp-admin, etc.)
/templates/* (some of our templates and custom content)

Everything else is denied (and there are hundreds of folders).
The problem I have is allowing index.php and 2 folders and then denying everything else inside /.
I should be able to accept,
http://example.com/
http://example.com/index.php
http://example.com/wp-content/...
http://example.com/wp-admin/...
http://example.com/wp-includes/...
http://example.com/templates/template.css
http://example.com/templates/subfolder/js/file.js

and reject,
http://example.com/thisIsAFolder
http://example.com/thisIsAnotherFolder

This is what I have,
<VirtualHost *:80>
    ServerName example.com

    DirectoryIndex index.php
    DocumentRoot /var/www/

    <Directory />
        Order deny,allow
        Deny from all
    </Directory>

    <Files index.php>
        Allow from all
    </Files>

    <Directory "/var/www(/|/wp*/|/templates/)">
        Allow from all

        Options FollowSymLinks

        RewriteEngine On
        RewriteBase /

        RewriteRule ^index\.php$ - [L]
        RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d

        RewriteRule ^ - [L]
        RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) wp/$2 [L]
        RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ wp/$2 [L]
        RewriteRule . index.php [L]
    </Directory>
</VirtualHost>

But I continually receive Red Hat Enterprise Linux Test Page (using CentOS) and it allows for sub-directories because I allow /.
EDIT
This is the Apache config that ended up working for me. Big thanks to Jon Lin for the help.
<VirtualHost *:80>
    ServerName example.com

    DirectoryIndex index.php
    DocumentRoot /var/www/

    # first, deny all access
    <Directory />
        Order deny,allow
        Deny from all
    </Directory>

    # then start to allow access where required
    <Files index.php>
        Allow from all
    </Files>

    <Directory "/var/www/">
        Allow from all

        Options FollowSymLinks

        RewriteEngine On
        RewriteBase /

        # go directly to index.php if it is accessed
        RewriteRule ^index\.php$ - [L]

        # re-write URL for wp-admin access
        RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

        # re-write wp-* access to route through wp/
        RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) wp/$2 [L]

        # re-write all .php files to route through wp/
        RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ wp/$2 [L]

        # go directly to real files and directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # respond to all other URLs by passing them through index.php
        RewriteCond %{REQUEST_FILENAME} !-f [OR]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . index.php [L]

        # deny access if URL doesn't start with these
        RewriteCond %{REQUEST_URI} !^/(index\.php)?$
        RewriteCond %{REQUEST_URI} !^/wp-[^/]+/
        RewriteCond %{REQUEST_URI} !^/templates/
        RewriteRule ^ - [L,F]
    </Directory>
</VirtualHost>

A: You could try adding:
RewriteCond %{REQUEST_URI} !^/(index\.php)?$
RewriteCond %{REQUEST_URI} !^/wp-[^/]+/
RewriteCond %{REQUEST_URI} !^/templates/
RewriteRule ^ - [L,F]

right before:
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d

The problem here though, is that permalinks will probably break, because a request like: /posts/post-title/ will not match an of the "allowed" URI's. If that's a problem, then move it to right before this line:
RewriteRule . index.php [L]


text:
Q: Git pull via SSH I try set up jenkins for automatically execute git pull from bitbucket. I created an SSH on repository and executed ssh -T git@bitbucket.org and got response:

authenticated via a deploy key. You can use git or hg to connect to Bitbucket. Shell access is disabled.This deploy key has read access to the following repositories:

If I try execute ssh git pull the console does infinite loading.. Why?

A: Did you clone repository?  You should be able to login to Bitbucket web interface and in you profile add your public SSH key.
Then you can clone repository. From Bitbucket webinterface --> repo --> click on clone. This will pop up window with ssh command to clone repository.
Once you repo is cloned, you should be able to use
    git pull
    ...edit,add,commit
    git push

A: There is no need to manually open SSH connection - git will do it itself. You just need to tell git to pull a specify from which repository. Git will parse the URL, and invoke SSH if needed.
And this is the best practice to disable shell access to git hosts. See e.g. https://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server


text:
Q: Twitter Android SDK not executing Callback I'm running this code with a Twitter handle I'm pretty sure doesn't exist in order to test error handling. The breakpoints on the Callback are never hit, neither for success nor failure.
Any pointers on why this is?
Just as a note, this code works fine with a valid Twitter handle, but doesn't call the Callback either.
final Callback<Tweet> actionCallback = new Callback<Tweet>() {
    @Override
    public void success(Result<Tweet> result) {
        int x = 1;
        x++; // This code is just so I can put a breakpoint here
    }
    @Override
    public void failure(TwitterException exception) {
        DialogManager.showOkDialog(context, R.string.twitter_feed_not_found);
    }
};

final UserTimeline userTimeline = new UserTimeline.Builder().screenName(handleStr + "dfdfddfdfdfasdf") // Handle that doesn't exist
        .includeReplies(false).includeRetweets(false).maxItemsPerRequest(5).build();

final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(context)
        .setTimeline(userTimeline)
        .setViewStyle(R.style.tw__TweetLightWithActionsStyle)
        .setOnActionCallback(actionCallback)
        .build();

listView.setAdapter(adapter);

A: I think you misundestood the purpose of the actionCallback. From the source code of the TweetTimelineListAdapter you can see that this callback is for the actions on tweet view,ie, when you click on favorite icon for example. I've test with the favorite icon and the callback gets called.
Take a look at this comment at the getView method of the source code.
   /**
     * Returns a CompactTweetView by default. May be overridden to provide another view for the
     * Tweet item. If Tweet actions are enabled, be sure to call setOnActionCallback(actionCallback)
     * on each new subclass of BaseTweetView to ensure proper success and failure handling
     * for Tweet actions (favorite, unfavorite).
     */

The callback is not intended to handle a screenname that does not exist and indeed the actions/buttons of a specific tweet.
Hope this helps.
UPDATED: You don't need to detect any erros on UserTimeLine, since the builder does not throw any exception and the adapter will be empty, with no rows/views showing on the screen. But if you still need to detect some "error" in the loading you have to rely on the "next" method of the UserTimeLine.
Take a look
  userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {

        }

        @Override
        public void failure(TwitterException exception) {
            Log.d("TAG",exception.getMessage());
        }
    });

This method shows the next tweet for the user, if the failure callback get called you will know for sure that this user does not have any tweet or the user does not exist.


text:
Q: Ways of getting 20% of elements in array - PHP I have an array of n elements and I need to get random 20% of those elements into another array. Is there any function which can achieve this?
Currently what I can think of is this:
foreach ($orders as $order) {
    if (rand(1, 100) > 80) {
        echo('20%');
    } else {
        echo('80%');
    }
}

Is there a more optimal way?

A: You could shuffle the array and then take the first 20% elements.
$array = [1, 2, 3, 4];
shuffle($array);

$twenty = array_slice($array, 0, floor(count($array) / 5));
$eighty = array_slice($array, floor(count($array) / 5));

A: The simplest solution is probably to use shuffle:
shuffle($orders);
for ($i = 0; $i < count($orders) / 5; $i++) {
    // do something with the first 20% of elements
}
for (; $i < count($orders); $i++) {
    // do something with the rest of the array
}

A: To get two arrays by one function call, use array_splice function. After
shuffle($array);
$twenty = array_splice($array, floor(count($array) / 5 * 4));

$twenty will held 1/5 of source array and $array - other items

A: Shuffle is the simplest solution for this case
$array = [1,2,3,4]
shuffle($array);
$firstSlice = array_slice($array , 0 , count($array)/2);
$secondSlice = array_slice($array , count($array)/2 , count($array));


text:
Q: What is the real name of median sort and/or where can I find more material on it I'm reading the book Algorithms in a Nutshell published by O'Reilly Media and I was reading the section on sorting algorithms and found one called Median Sort. Since I had never heard of it before and my textbook from CS3 (which covered algorithms) did not have it listed, I googled it and tried looking it up on Wikipedia and found nothing. I would greatly appreciate it if someone could provide the name I could easily look the algorithm up under or point me to other resources about it. Thank you.
Also, from what I can tell about the algorithm, it's essentially Quicksort except it always uses the median value as the pivot. By median value I mean it seems to scan the array of items and pick the middle value as the pivot, not pick the middle item in the array as the pivot.  Also, the book mentions a Blum-Floyd-Pratt-Rivest-Tarjan (BFPRT) in relation to the "Median" sort.

A: Most versions of quicksort pick (for example) the median of three elements (typically the first, middle and last), giving what's normally called a median of 3 Quicksort. Just starting with the middle element as the pivot doesn't usually qualify for any name other than just Quicksort.
Edit (much later, after seeing the edit in the question): it appears that what you're talking about is using the "median of medians" algorithm to choose the pivot element for a QuickSort. The median of medians algorithm is better known for being used independently as an alternative to (or refinement of, depending on your viewpoint) Hoare's Select algorithm. This is known to find the median (or other rank, but in this case we only care about median) in linear time.
The bottom line is that the sort is really still a Quicksort. Hoare's description of choosing the pivot element neither requires nor prohibits a media of medians selection:

The first step of the partition process is to choose a particular key value which is known to be within the range of the keys of the items in the segment which is to be sorted. A simple method of ensuring this is to choose the actual key value of one of the items in the segment. The chosen key value will be called the bound.

Of course, nearly everybody now calls it the "pivot" instead of the "bound", but this is mostly irrelevant. The method used to choose the pivot/bound is left open.

A: As I don't own the aforementioned book, I'll take a wild guess and say that Blum-Floyd-Pratt-Rivest-Tarjan algorithm (also see the paper if you want to know more) is probably used for pivot selection. I also recommend you to read the Partition-based general selection algorithm section from the same Wikipedia article as I think it is exactly what you are looking for.

A: Yes you are right it is similar to quicksort but it is better than Quicksort in the way that it avoids those cases where your arrays are divided very disprorportionately(not in equal halves).
Because in quicksort we cannot be sure that each time our array will be divided into two equal halves or nearly equal halves.In median sort we assure this by paying price for finding median but that could be worthy to make quick sort similar to merge sort and benefits of having sorting in place.

A: I don't own the book but I will take a guess. The algorithm the book is referring to is the Floyd-Rivest's SELECT algorithm. Blum-Floyd-Pratt-Rivest-Tarjan (BFPRT) refers to this paper where they discuss their earlier PICK (now known as Median of medians) selection algorithm:
M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest, R. E. Tarjan, "Time Bounds for Selection," Journ. Comp. and. Sys. Sci., vol. 7, iss. 4, pp. 448-461, 1973.
This paper sets up the early understanding of the selection problem in computer science.


text:
Q: Trouble writing MySQL query involving ordered data from three tables I have a table called tags, like this:
+-------+----------+
| tagID | tagName  |
+-------+----------+
|     1 | jewelery |
|     2 | gifts    |
|     3 | asdf     |
|     4 | fashion  |
|     5 | diamonds |
+-------+----------+

Then a table called coupon_tags, like this:
+-------+----------+
| tagID | couponID |
+-------+----------+
|     1 |        1 |
|     2 |        1 |
|     3 |        2 |
|     4 |        2 |
|     5 |        3 |
+-------+----------+

And lastly, a table called coupons, here are the pertinent parts (id is the same as couponID elsewhere):
+----+-----------------+
| id | zone            |
+----+-----------------+
|  1 | Los Angeles     |
|  2 | Orange County   |
|  3 | Los Angeles     |
|  5 | Orange County   |
|  6 | Orange County   |
+----+-----------------+

What I need to write a query for: I want to get tagNames via the first table that correspond to the ordered list of the top 10 most used tagIDs in the second table, but it only looks through couponIDs that match another criteria - that the "zone" be a certain zone. In the end, only the top 10 tagNames from a certain zone will show. I've never done a triple-table query before, any help?
I'm trying to keep this purely SQL, as I had a partially working PHP solution but it was messy and very slow.

A: SELECT tags.tagName FROM
(SELECT tagID, COUNT(*) FROM
 coupon_tags
 JOIN coupons ON coupons.couponID = coupon_tags.couponID AND zone = 'Los Angeles'
 GROUP BY tagID ORDER BY COUNT(*) DESC LIMIT 10) AS most_used
JOIN tags ON most_used.tagID = tags.tagID


text:
Q: Mazur's theorem-abelian torsion group of rational points of an elliptic curve I am looking at Mazur's theorem...
$$E(\mathbb{Q})_{\text{torsion}} \cong \mathbb{Z}/n\mathbb{Z}, \text{ for } n=1,2, \dots ,10,12$$
means that the torsion group $E(\mathbb{Q})_{\text{torsion}}$ contains the points $P$ which have the identity
$$nP=0, \text{ for } n=1,2, \dots ,10,12$$
and the coordinates are integers, right ??
What does
$$E(\mathbb{Q})_{\text{torsion}} \cong \mathbb{Z}/2m\mathbb{Z} \oplus \mathbb{Z}/2\mathbb{Z}, \text{ for } m=1,2,3,4$$
mean??

A: The result specifies what are the exact possibilities for the torsion part of the group of rational points on an elliptic curve (over the rationals).
By Mordell's theorem you know that  $E(\mathbb{Q})_{\text{torsion}}$ is some finite abelian group. Now, you know that it cannot by just whatever finite abelian group but it must be one of a very particular form.
Namely, the group is either cyclic with order $\le 10$ or equal to $12$ or it is a direct product of a group of order two with a cyclic group of order $2,4,6,$ or $8$.
For one particular elliptic curve it can be only one of these groups of course, but the result asserts that for every elliptic curves you will get one of these groups.
If the torsion part is cyclic, yes, this means about what you said: there is a point $P$ with rational coefficients on the group that has order $n$ where $n\le 10$ or $n=12$, and $P, 2P, \dots, nP=0$ is the set of all $n$ rational points of finite order on this curve.
For the other case, you have two points $P,Q$ the order of $P$ is $2$ the order of $Q$ is $n$ with $n$ equal $2,4,6,$ or $8$ and $Q,2Q, \dots ,n Q$ and $P+Q , P + 2Q, \dots , P+nQ$ is the set of all $2n$ rational points of finite order on this curve.


text:
Q: Como definir tipos pré definidos no MySQL? No site que estou desenvolvendo terei, por exemplo, um formulário de cadastro onde o usuário deve definir seu sexo em uma combobox (masculino ou feminino). A tabela usuários na base de dados terá todos os campos do usuário como string, date, float. Como faço para definir o sexo?
Para que na combobox de cadastro eu já carregue a opção masculino e feminino e na base cadastre como M ou F, já tendo essas duas opções lá cadastradas. Assim teria que aparecer ao usuário 'Masculino' ou 'Feminino' sendo que na tabela do banco de dados eu tenho isso como campo sexo tendo como opção desse campo somente M ou F.

A: O MySQL não tem nenhum recurso para criar um domínio de dados como existe em outros bancos de dados.
A solução normalmente adotada é criar uma enumeração, embora muitos dizem que o ideal é não usar este tipo de dado. Ou criar uma tabela auxiliar com os dados que precisa e fazer um relacionamento.
A segunda forma tem diversas maneiras de fazer de acordo com sua necessidade. Mas todas envolverão algum trabalho manual. Não tem jeito.
Neste caso o mais comum para pegar os valores possíveis é só olhar para a tabela auxiliar, no caso seria a tabela de sexo ou gênero como seria uma nomenclatura mais correta. Quando fizer alguma consulta na tabela de usuário terá que fazer um JOIN para que a coluna de sexo pegue a descrição na tabela auxiliar ao invés do código/id do sexo escolhido.
Uma outra forma é não se preocupar com isso no banco de dados, cadastrar as letras referentes ao gênero na coluna e tratar as descrições só na aplicação. Em geral este informação não costuma mudar.
Como curiosidade há um padrão para representar dados de gênero e ao contrário do que pensam as pessoas, não deve se usar "M" ou "F".
Coloquei no GitHub para referência futura.


text:
Q: CSOM code deployment in SharePoint On premise as well as SharePoint Online I am new to SharePoint Client Object model. It will be very thankful if someone outlines the steps required to deploy  CSOM code in SharePoint on premise as well as SharePoint Online.

A: In SharePoint 2013 On-premise,

*

*You can deploy your WSP to SharePoint farm

*

*Run the below command on SharePoint 2013 Management Shell.

Add-SPSolution -LiteralPath "path to wsp file\EventReceiverProject.wsp"
example : Add-SPSolution -LiteralPath "C:\EventReceiverProject.wsp"

*On the Central Administration Home page, click System Settings.

*In the Farm Management section, click Manage farm solutions.

*On the Solution Management page, click the solution that you want to deploy.

*On the Solution Properties page, click Deploy Solution.

*On the Deploy Solution page, in the Deploy When section, select one of the following:
a. Now
b. At a specified time. If you select this option, specify a time by using the date and time boxes. We recommend that you select a time when the load on the destination servers is low.

*In the Deploy To? Section, in the A specific web application list, click either All web applications or select a specific Web application.

*Click OK.

*Now open your site, go to Site Settings -> Site features

*Activate the feature if it is not active.

In SharePoint Online, you can deploy your wsp (No Code WSP) because Microsoft has restricted managed code.
Reference:

*

*Deprecation of Custom Code in Sandboxed Solutions

*http://www.sharepointnutsandbolts.com/2016/08/sandbox-code-disabled-in-Office-365.html
You can create SharePoint hosted / Provider hosted app or pure client-side development.
Reference:
a. Get started creating SharePoint-hosted SharePoint Add-ins
b. Step by Step approach to create a Provider Hosted Application in SharePoint 2013
You can use Content Editor / Script Editor  web parts and place JavaScript, REST API code with HTML design in the web parts or You can attach JS files to that web parts and place files in Style Library.


text:
Q: Reference request: Hard measure theory / functional analysis problems I want to revise basic measure theory and functional analysis and I was wondering if there's a good source of challenging problems? Ideally I'm hoping these problems will help me go through the material again, as I know that this is the best way to learn. Preferably, there are worked out solutions to refer to as well, but at the very least hints? One possibility is to say "just look at the problems at the end of the chapters in Rudin" but I'm wondering if there are any other good sources you know of.

A: You might try Biler and Witkowski, Problems in Mathematical Analysis


text:
Q: ArcGIS Conflation Tool Recommendation or Custom Script for Comparing Points Can anyone recommend conflation tools for ArcGIS Desktop (10 or 10.1, paid or free) or a scripting outline / procedure (or just a script) to have a technician efficiently process the following rules?
We need to compare and update 2 points of interest (POI) point layers, let's call them MasterPOI and ComparePOI. Aprox 30k points in each. The rules for a technician would be the following:

*

*Find any ComparePOI points within a ~1000m of MasterPOI.

*If a ComparePOI point has a better location or a better description (using their human judgement), update MasterPOI with either location or its description field.

*Separate step maybe -- then any ComparePOI point not used to update MasterPOI, simply add it to the MasterPOI. Most points would fall into this category. (I'm thinking just put a flag on a feature in ComparePOI when #2 occurs.)

I could script it myself eventually, but wondering if someone has some experience they could share

A: Take a look at conflex by citygate gis.
We used this for a nationwide job a few years ago that required adjusting roads and point junctions to various boundaries in ArcGIS. The spatial adjustment tools in ArcGIS didnt have the functionality we required even with customization so we looked at off the shelf solutions.
Conflex had the usual spatial and attribute matching routines but also included some clever pattern recognition that increased the hits to around 85-90%. Their QA tools are ok but we also had to use the data reviewer extension for some of our requirements.
Its probably an overkill for you with just point to point matching but short of writing your own tools, there just isn't a lot of options out there. Unfortunately we don't have scripts to share.

A: MapMerger is a powerful conflation extension that is completely integrated into ArcGIS.  MapMerger automated conflation is something like 200X faster than doing the same conflation task manually.


text:
Q: Return an Array of Arrays via PHP WSDL based web service I'm struggling with the following problem:
I have a PHP-based web service which needs to be consumed by various
clients. As long as I keep things simple, everything works fine. I figured that Axis2 and .NET don't like soapenc:array definitions in WSDL, so I created list types for mapping object arrays:
<xsd:complexType name="CourseList">
  <xsd:sequence>
    <xsd:element name="Courses" type="tns:Course" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
</xsd:complexType>

Now, if I include something like a List of CourseLists (using the same WSDL procedure), .NET fails as Axis2 (ADB) does with handling this data.
I checked the XML that comes over the wire with soapUI; it looks reasonable.
I'm really on the ropes with this one. Any hint would be highly appreciated.
TIA
 KB22

A: This question is older than sin, but it's never been answered, and I struggled to find an answer myself when I recently ran into the same problem. There might be a better way to do this, but what I ultimately ended up doing was something like this.
This is actually even a level further, a 3-d array, but the general principle is the same.
<xs:element name="myOtherArray">
<xs:complexType>
    <xs:sequence>
        <xs:element name="someInsideArrayProperty" type="xs:int"/>
    </xs:sequence>
</xs:complexType>

<xs:element name="myArray">
<xs:complexType>
    <xs:sequence>
        <xs:element name="someArrayProperty" type="xs:string"/>
        <xs:element name="yetAnotherArray" maxOccurs="unbounded" type="ns:myOtherArray"/>
    </xs:sequence>
</xs:complexType>

<xs:element name="myResponse">
<xs:complexType>
    <xs:sequence>
        <xs:element name="myResponseArray" maxOccurs="unbounded">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="someProperty" type="xs:int"/>
                    <xs:element name="someOtherProperty" type="xs:string"/>
                    ...
                    <xs:element name="anotherArray" type="ns:myArray" maxOccurs="unbounded"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:sequence>
</xs:complexType>


text:
Q: SQL Server locks on concurrent table I have the following scenario:

*

*a table that is accessed (update, delete, insert and select) by multiple programs. In fact they are the same, but instantiated by multiple users. This table never grows to more than 1000 rows as the program deletes data after use and inserts new data again. It's like a Supplier/Collector situation.

*as this is a industrial production scenario and I must guarantee some operations, so when a user confirms any action, the program updates that table with data coming from other tables on the system.
So we implemented transaction on a lot of commands.And the result was a lot of deadlock situations.
I want some tip about what we could do for avoid those locks. In fact we don't need the transaction, we just need to guarantee that a command will run and if for any reason it fails, the whole operation gets rolled back. I don't know if there's a way to do that without using transactions.
PS: We're using SQL Server 2008 R2.
PS2: I discovered that some system tables I used in the clause FROM on the update was the big problem. Those tables are used for the whole system and gets tons of insert/update/select. So I was just locking things that should not because I didn't change data on that tables with this program.
EX:
   Update t1
   set x= 1
   from systable1 as t
   inner join systable2 t2
   where .....

I guess this was the big problem, so I added hint WITH (NOLOCK) on t and t2 and WITH (ROWLOCK) on t1.
Other thing I must mention, this is a test ambient and we are stressing the data base and program at max, because we just can't risk to fail on production.
Can I use a checkpoint strategy to re-do the action if it fails?
Thanks.

A: First, yes you need transactions to ensure success or failure (rollback).  Only a 1,000 records? That table must be getting slammed with inserts/updates/deletes!  So to me this sounds like a heavy transaction table - so be careful with adding indexes as they will only make your inserts/updates/deletes slower.  And I have to confirm there are no triggers on your  heavy transaction table, right?
So what about your reads?  Ever think about separating out a reporting table or something?  Replication might be overkill. How accurate and up-to-the-minute does the data need to be?
Finally - profile, profile, profile.

A: You may be able to eliminate locking problems by using READ UNCOMMITTED (see Why use a READ UNCOMMITTED isolation level? and http://msdn.microsoft.com/en-us/library/aa259216(v=sql.80).aspx). But be aware that this could result in reading data that is inconsistent or won't necessarily be persisted in the database.

A: Using readuncommitted is a possible solution though it has knock on effects. I'd try rowlock first though. SQL Server optimises to page lock to reduce the number of locks on a record, as you only have a thousand records unless they are very wide, a page lock will lock a goodly few of them.

A: Start by performance tuning all of the queries inside the Transaction.  Sometimes speeding up a query on the inside of the transaction by adding an index can make a big difference in the amount of deadlocks yous see.
Also, keep the transactions as small as possible to achieve the rollback that you need when something fails.  For instance if you had 5 queries that look up data, but only 3 that change data, then you might be able to shrink the transaction down to just the 3 queries changing the data.
Hope this helps.


text:
Q: creating a simple key press checker in python using pygame I'm making a messenger application in python using pygame for the gui. I'm trying to detect key presses but the code I'm using is a large amount and i don't like it, i was wondering if there is a better way of checking which keys where pressed then sending that to a string variable.
My code:
##------>>>__ Letters __<<<------##
            if event.key == pygame.K_q:
                self.CharKeyPressed = "q"
            if event.key == pygame.K_w:
                self.CharKeyPressed = "w"
            if event.key == pygame.K_e:
                self.CharKeyPressed = "e"
            if event.key == pygame.K_r:
                self.CharKeyPressed = "r"
            if event.key == pygame.K_t:
                self.CharKeyPressed = "t"
            if event.key == pygame.K_y:
                self.CharKeyPressed = "y"
            if event.key == pygame.K_u:
                self.CharKeyPressed = "u"
            if event.key == pygame.K_i:
                self.CharKeyPressed = "i"
            if event.key == pygame.K_o:
                self.CharKeyPressed = "o"
            if event.key == pygame.K_p:
                self.CharKeyPressed = "p"
            if event.key == pygame.K_a:
                self.CharKeyPressed = "a"
            if event.key == pygame.K_s:
                self.CharKeyPressed = "s"
            if event.key == pygame.K_d:
                self.CharKeyPressed = "d"
            if event.key == pygame.K_f:
                self.CharKeyPressed = "f"
            if event.key == pygame.K_g:
                self.CharKeyPressed = "g"
            if event.key == pygame.K_h:
                self.CharKeyPressed = "h"
            if event.key == pygame.K_j:
                self.CharKeyPressed = "j"
            if event.key == pygame.K_k:
                self.CharKeyPressed = "k"
            if event.key == pygame.K_l:
                self.CharKeyPressed = "l"
            if event.key == pygame.K_z:
                self.CharKeyPressed = "z"
            if event.key == pygame.K_x:
                self.CharKeyPressed = "x"
            if event.key == pygame.K_c:
                self.CharKeyPressed = "c"
            if event.key == pygame.K_v:
                self.CharKeyPressed = "v"
            if event.key == pygame.K_b:
                self.CharKeyPressed = "b"
            if event.key == pygame.K_n:
                self.CharKeyPressed = "n"
            if event.key == pygame.K_m:
                self.CharKeyPressed = "m"
            ##------>>>__ Numbers __<<<------##
            if event.key == pygame.K_1:
                if self.BlnShift:
                    self.CharKeyPressed = "!"
                else:
                    self.CharKeyPressed = "1"
            if event.key == pygame.K_2:
                if self.BlnShift:
                    self.CharKeyPressed = '"'
                else:
                    self.CharKeyPressed = "2"
            if event.key == pygame.K_3:
                if self.BlnShift:
                    self.CharKeyPressed = "£"
                else:
                    self.CharKeyPressed = "3"
            if event.key == pygame.K_4:
                if self.BlnShift:
                    self.CharKeyPressed = "$"
                else:
                    self.CharKeyPressed = "4"
            if event.key == pygame.K_5:
                if self.BlnShift:
                    self.CharKeyPressed = "%"
                else:
                    self.CharKeyPressed = "5"
            if event.key == pygame.K_6:
                if self.BlnShift:
                    self.CharKeyPressed = "^"
                else:
                    self.CharKeyPressed = "6"
            if event.key == pygame.K_7:
                if self.BlnShift:
                    self.CharKeyPressed = "&"
                else:
                    self.CharKeyPressed = "7"
            if event.key == pygame.K_8:
                if self.BlnShift:
                    self.CharKeyPressed = "*"
                else:
                    self.CharKeyPressed = "8"
            if event.key == pygame.K_9:
                if self.BlnShift:
                    self.CharKeyPressed = "("
                else:
                    self.CharKeyPressed = "9"
            if event.key == pygame.K_0:
                if self.BlnShift:
                    self.CharKeyPressed = ")"
                else:
                    self.CharKeyPressed = "0"
            ##------>>>__ Specials __<<<------##
            if event.key == pygame.K_SPACE:
                self.CharKeyPressed = " "
            if event.key == pygame.K_PERIOD:
                if self.BlnShift:
                    self.CharKeyPressed = "@"
                else:
                    self.CharKeyPressed = ". "
            if event.key == pygame.K_COMMA:
                if self.BlnShift:
                    self.CharKeyPressed = "'"
                else:
                    self.CharKeyPressed = ", "
            if event.key == pygame.K_SLASH:
                self.CharKeyPressed = "/"
            if event.key == pygame.K_SEMICOLON:
                if self.BlnShift:
                    self.CharKeyPressed = ":"
                else:
                    self.CharKeyPressed = ";"

A: For most cases, you can simply use the unicode attribute of the KEYDOWN event:
self.CharKeyPressed = event.unicode


text:
Q: PERMISSION_DENIED: Missing or insufficient permissions... and I change nothing I know this question has been asked a few times, but I couldn't find any working answer.
I'm using Google App Engine and Firestore (Database location: eur3 - europe-west).
A few days ago, my simple app was working like a charm and more precisely Firestore was working.
I could test/use it locally through nodemon or online (when deployed).
Since this morning, and I change nothing, it doesn't work anymore locally.
I can't access my DB locally anymore, but I can when deployed to GAE.
Locally I got this error and this is a DB access issue:

PERMISSION_DENIED: Missing or insufficient permissions. {"code":7,"details":"Missing or insufficient permissions.","metadata":{}}

My code to access DB has always been as simple as:
// service/firestore.js
const Firestore = require("@google-cloud/firestore");
const db = new Firestore();
module.exports.db = db;

Do you have any clue why I can't write/read locally to Firestore this morning?
(BTW I've never modified security rules and it has always been working).
Thanks


text:
Q: What is this type of linking, or direct, called? So I'm building a website and a user's profile link would be like this
domain.com/profile.php?name=john.smith

But what is it called for it to be like this instead
domain.com/john.smith

Normally this would return a 404 error since it's not a file or directory in the root.


text:
Q: How to send data to php using POST and then retrieve data from php using GET in pure javascript? I want to send data with the POST method to a php server, then retrieve data from the server, using GET method this time (I assume).
Here's the JS :
function send()
function send(leURL, laValeur) {
    try {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open('POST', leURL);
            req.setRequestHeader("Content-Type", "application/json");
            req.onreadystatechange = function() {
                if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
                    document.getElementById("result").innerHTML = "Ok!";
                }
            };
            jmail = JSON.stringify(laValeur);
            req.send(jmail);
            resolve("true");
        });
    }
    catch (err) {
        window.alert("erreur 2");
    }
}

function recieve()
function recieve(laURL) {
    try {
        var reqt = new XMLHttpRequest();
        reqt.open('GET', laURL);
        reqt.onreadystatechange = function(e) {
            if (this.readyState == XMLHttpRequest.DONE && this.status = 200) {
                var rep = JSON.parse(this.responseText);
                try {
                    window.alert(rep);
                }
                catch (e) {
                    window.alert("erreur 4");
                }
            }
        }
        reqt.send();
        //return rep;
    }
    catch (e) {
        window.alert("erreur 3");
    }
}

function calls :
//there's a form in the HTML (id="form")
document.getElementById("form").addEventListener('submit', function(evt) {
    evt.preventDefault();
    send(url, mail)
        .then(recieve(url));
});

Old recieve() function (for testing purposes) :
function recieve(laURL) {
    window.alert(laURL);
}

So, as long as I was using old recieve() function, I had send() print "Ok!" and recieve() creating an alert, which makes me think it worked fine. But now that I use the new recieve() function, the page just reloads. (No catch block is even displayed !)
Here's the PHP :
<?php
if (!empty($_POST)) {
    $var = //do something with the data, involving $_POST
    echo $var;
}
else {
    echo "Hello, there !";
}
?>

Since $var was generated out of the first HTTP request (POST), how do I retrieve it in javascript ?
I suspect the error is caused either by the php or because of using two XMLHttpRequests (still I don't know how I should do this using only one HTTP request)

A: Your PHP stores the data in a variable, echos it out, then exits.
At this point, the PHP program has finished, the memory gets cleaned up, and the variable no longer exists.
If you want the data to be available to another request, then you have to store it somewhere persistent such as a session or a database.
If you want to use a single request, then read this.responseText in the readyStateChange handler.

A: What do you do with your data ?
How do you store them ?
How do you retreive them on the server to sending them after to the client if needed ?
You should store the $var somewhere, generally we use session $_SESSION for that. All depends of what you want finally.
Documentation for PHP session : https://www.php.net/manual/fr/reserved.variables.session.php
Once you have start the session,
I think you want to do something like that:
<?php
if ($_SESSION['var']) {
    echo "already done";
    ...
} else {
  if(!empty($_POST)) {
    $_SESSION['var'] = //do something with the data, involving $_POST
    echo $_SESSION['var'];
  } else {
    echo "var = not done, post = empty";
  }
}
?>

A: The POST request already returns the value (using echo). All you need to so is show it using your JavaScript.
e.g. in the POST request:
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
  document.getElementById("result").innerHTML = this.responseText;
}

I don't see any need for the GET request, unless you intend to use this at a later time in your process, expecting that the data may have changed on the server. But for that to make any sense, you have to have stored the data somewhere on the server, and also send in the request some identifier telling the server which piece of data to retrieve.


text:
Q: Copy data from one sheet and paste that data in all worksheets I have a sheet in which formulas are stored now I want that formulas to be copied and paste in all the other worksheets that I have in my workbook
I have such 70 sheets in which data need to be copied.
sheet name from which data will be copied is "SAMPLE"
data should be copied from sheet number 3
("SAMPLE" is sheet number 1 and after leaving 2 sheets, data need to be copy in each sheet in range of "Y1:BA151"
I have tried following code
Sub COPY()

 Dim WS_Count As Integer
     Dim I As Integer

     WS_Count = ActiveWorkbook.Worksheets.Count

     For I = 1 To 70

       Worksheets("SAMPLE").Range("Y1:BA151").COPY

     Next I

  End Sub

but I am begginer so i am lacking somewhere, kindly help with this.
in advance thx.

A: You need to loop from 3 to the Count of the Worksheets, and then use i within the loop. Or maybe that should be 4, not sure if I am reading " 'SAMPLE' is sheet number 1 and after leaving 2 sheets" correctly.
Sub Copy

    ThisWorkbook.Worksheets("SAMPLE").Range("Y1:BA151").Copy

    Dim i as Long
    For i = 3 to ThisWorkbook.Worksheets.Count
         ThisWorkbook.Worksheets(i).Range("Y1").PasteSpecial xlPasteAll
    Next

    Application.CutCopyMode = False
End Sub


text:
Q: How to import Vensim model to Anylogic PLE? I have encountered "parsing error! com.anylogic.ui.bad: encountered " ","","" at column X, row Y, was expecting: ..."
The Vensim model is in MDL format and consists of three simple formulas, however, the importer doesn't work. How can I fix the issue?

A: This is a bug
I just tested models with Vensim 7 and no problem to import, but with vensim 8 it's impossible to import models, and I get your same error.
I will report this problem to AnyLogic.
Response from AnyLogic:

Our converter was written several years ago, and we do not maintain
  compatibility with newer versions of Vensim.They have updated file
  format, and we need to research it, and update our converter. This is
  not a taks with high priority. Vensim 8 support will be added in next
  versions (8.8 or later).


text:
Q: Rails: filling a form out with a name, submitting an ID This is pretty simple, I just can't quite get it. I'm sure there's a rails-way to do it.
When creating a new comment, I want the user to be able to enter her name in a field, but have the form submit the matching ID for her name (or toss an error/create new person).
Thanks!

A: There are a couple of ways to go about this:

*

*In your controller, split the name on " " and save each to a variable, then do a User.find_by_firstname_and_lastname(firstname, lastname). If none exists, tell the user to create one.

*Have the text field that the users enters their name into be an AJAXified field that searches for their username and lets them select the correct one. If none exists, you can then find out immediately and tell them that they need to create an account. If it finds one, it sets the value of a hidden field to the ID of the user that was selected.

Option 1 is very error prone, but option 2 requires quite a bit more work. Honestly, this is going to be a hard one to pull off properly. What do you do if there are two John Smiths? How do they know which one to choose, how do you choose in the backend, etc.
I would highly suggest making it based off of username instead of first name or last name. However, if you show the user which one you are going to use (possibly by showing their username, email, etc) then it could work.


text:
Q: Breaking my code down into a loop I am currently working on a battleship game to practice my programming skills. I have functional code but was wondering if anyone can help me break my code down into a for loop?
import random
def main():
    board = []
    for i in range(0,5):
        board.append(random.randint(1,50))

    print(board) #test purposes

    guess=int(input("enter number between 1-50"))

    if guess == board[0]:
       print("hit")
       board[0]="hit"
    elif guess != board[0]:
       print("miss")
       board[0]="miss"

Note i want to carry out the if statement multiple times to check for board[0-5].
Instead of repeating it 5 times I was thinking of doing something like this:
for x in range(0,5):
    if guess == board[x]:
        print("hit")
        board[x]="hit"
    else:
        print("miss")
        board[x]="miss"

But this is not working as it takes just 1 input whereas I want it to take 5. For each input it has to check if input is equal to board[0-5]
Thank You in advance for any help.

A: write guess in a for loop,be careful about indentation
import random
def main():
    board = []
    for i in range(0, 5):
        board.append(random.randint(1, 50))
        guess = int(input("enter number between 1-50 : "))
        print(board)  # test purposes

        if guess == board[0]:
            print("hit")
            board[0] = "hit"
        elif guess != board[0]:
            print("miss")
            board[0] = "miss"

A: I'm not quite sure what you are trying to achieve, but I believe it to be this:
import random
def main():
    board = []
    for i in range(0,5):
        board.append(random.randint(1,50))

    print(board) #test purposes

    guesses = []
    try_nr = 0
    while try_nr < 5:
        try_nr += 1
        guess = int(input("enter number between 1-50"))
        guesses.append(guess)

    for i in enumerate(guesses):
        i = i[0]
        if guesses[i] in board:
            print("hit")
            # board[0]="hit" --> not quite sure what you want to achieve here?
        else:
            print("miss")
            # board[0]="miss" --> not quite sure what you want to achieve here?

NB1: There are other more neat/dense ways to code this, but this helps you to get going. See if you can perfect it for yourself if needed.
NB2: I have changed your elif statement into else. Your equation can only have two possible answers (either a hit or a miss). By using elif you are forcing python to reconsider/re-calculate your if-statement fully while using else it only considers the if-statement once.

A: You can use the enumerate() function to add a counter to your for loop. This will be useful.
board = [12, 4, 76, 2]
for index, number in enumerate(board):
    print index, number

#output
# 0 12
# 1 4
# 2 76
# 3 2

You said you want to take 5 guesses? You could do something like this:
for i in range(5):

    guess=int(input("enter number between 1-50"))

    for index, number in enumerate(board):
        if guess == number
            print("hit")
            board[index] = "hit"
        else:
            print("miss")
            board[index] = "miss"


text:
Q: How to redirect to a page using PHP in one page website I have one a page webiste www.yahavi.com (all pages in 1 html) in which different pages are referenced using their div id (eg; #home, #contact ). After successful sign up I want to direct user to my thankyou page with id #thanku . How can i do that using my PHP script that runs after form submission.
home url: www.yahavi.com/#home
form at : www.yahavi.com/#contact
thankyou: www.yahavi.com/#thanku

I am using   header (Location: /#thanku) in my PHP but this doesnt work.
Note: I dont want a complete new html page to reload.

A: You can do it with just PHP. No need for JavaScript or jQuery.
Declare a global variable for storing your base path like this
$BASE_URL="www.yahavi.com/";

and redirect to the specified page like
header("Location:'".$BASE_URL."#thanku'");

A: You can use javascript on your PHP code like this:
<?php

<script> location.href="#thanku" </script>

?>

Try that. I hope this helps.
UPDATE
If you do AJAX instead, it would be best. After signup, if the user signups successfully, on the javascript file you can use location.href="#thanku".
For that, you would need to do an AJAX request in your signup form.


text:
Q: How to get `devtools::install_deps` to repsect `(<= version)` restrictions? For a package I am developing, I have the following Imports: in DESCRIPTION file
Imports:
  forecast (<= 0.8.7)

However, when I try to install the package using devtools::install_deps it installs the latest version of forecast instead of respecting the version restriction.
How do install packages locally that also respects the restrictions in DESCRIPTION?


text:
Q: Positive Integers Equation This is a very interesting word problem that I came across in an old textbook of mine. So I know its got something to do with the least common multiple, but other than that, the textbook gave no hints really and I'm really not sure about how to approach it. So anyway, here the problem goes:
Find all solutions in positive integers for the equation
$$x-y^4= LCM(x, y).$$
Any subtantial answers or help would be truly greatly appreciated. Thanks so much :)

A: AFAIK the least multiple of any positive integer $x$ is $x$ itself. As $y^4$ is greater than zero, $x-y^4$ is less than $x$, so it can't be a multiple of $x$ (whether common with $y$ or not...). Of course that holds unless you allow ZERO as a multiple, in which case $x-y^4 = 0$ would give solutions.


text:
Q: Define function / method if not defined before c++ I don't use C++11 yet, so I wrote the functions to_string(whatever) by myself. They should only be compiled if they don't exist. If I switch to C++11, they should be skipped. I have something like this:
#ifndef to_string

string to_string(int a){
    string ret;
    stringstream b;
    b << a;
    b >> ret;
    return ret;
}

string to_string(double a){
    string ret;
    stringstream b;
    b << a;
    b >> ret;
    return ret;
}

#endif

This doesn't work apparently. Is something like this possible and if yes, how?

A: You can't test whether they're defined as such, but you can check the language version:
#if __cplusplus < 201103L

(There's a useful collection of predefined compiler macros here.)

A: You could play with SFINAE having in mind that non-template overloads are preferred over the template ones. This compiles in both pre-c++11 and c++11:
#include <sstream>
#include <string>
#include <iostream>

using namespace std;

namespace my {
   template <bool V, class T>
   struct enable_if {
   };

   template <class T>
   struct enable_if<true, T> {
      typedef T type;
   };

   template <class T1, class T2>
   struct is_same {
      static const bool value = false;
   };

   template <class T>
   struct is_same<T, T> {
      static const bool value = true;
   };
}

template <class T>
typename my::enable_if<my::is_same<T, int>::value
                      || my::is_same<T, double>::value, string>::type
  to_string(T const& a) {
    string ret;
    stringstream b;
    b << a;
    b >> ret;
    return ret;
}

int main() {
   cout << to_string(2) << endl;
   cout << to_string(3.4) << endl;
}

A: This is one of main purpose of namespace existence.
My suggest is to include your personal function in a proper namespace, something like:
namespace myns {
  std::string to_string(...) {
    // ...
  }
  // etc...
}

This is fundamental in order to avoid future conflict problems.
Afterwards, when you're going to use that function, you can simple select the proper function with a MACRO substitution.
Something like:
#if (__cplusplus >= 201103L)
  #define my_tostring(X) std::to_string(X)
#else
  #define my_tostring(X) myns::to_string(X)
#endif

Note __cplusplus is a pre-defined macro which contains compiling information about standard version.

Edit:
Something less "violent", it will select the proper namespace for that specific function in accordance with the standard version:
#if (__cplusplus >= 201103L)
  using std::to_string;
#else
  using myns::to_string;
#endif

// ... somewhere
to_string(/*...*/);  // it should use the proper namespace

A: You can put your functions inside a macro, like this:
#ifndef to_string
#define to_string

//....

#endif

Then, in another file, write this:
#if __cplusplus >= 201103L
    #undef to_string
#else
    #define to_string
#endif

A: Boost.Config has some macros to check whether C++11 features are supported/used.


text:
Q: Xam plugin : CrossLocalNotifications.Current.Show doesn't work on Samsung S8 (after latest updates) Local Notifications
using Plugin.LocalNotifications;

[...]

CrossLocalNotifications.Current.Show();

stopped working after latest update(s) to the android phone : Samsung Galaxy S8  (though it works fine on emulators/tablets etc.).
Any Ideas why?


text:
Q: vite hmr watch log format I'm working on a Nuxt3 project, which uses Vite as a default bundler.
Its HMR was working very fine till I just found out that the whole app is restarting every time there is any change, the console is showing

✔ Vite server hmr 9 files in 21.731ms

I mean I obviously changed only one file.
Is there any way to check which 9 files were changed?
Maybe config for logging format?
I tried looking in vite source code and docs, but couldn't find any solution.

A: OP fixed the issue by downgrading to Nuxt RC12.
Probably a regression, there will probably be a changelog note on the next release: https://github.com/nuxt/framework/releases


text:
Q: Are there existing examples of this type of game I'm new to the topic and have begun reading some of the literature out there. I have been trying to find examples of a type of game to see if it already exists but did not have much luck.
Are there examples of two player cooperative games where Player A can communicate with Player B but Player B cannot communicate with Player A and the goal is to maximize their cumulative rewards. Think Player A gets a reward if they communicate helpful information to Player B and Player B gets a reward if they were able to use the information that Player A gave.
This is the general framework of the game and I've tried to keep it as general as possible to hopefully see if there are multiple examples out there that look at this.
Any insights would be appreciated. Cheers!

A: What you might be looking for is called a signaling game or the related screening game. Signaling games are two-stage games where player 1, has some private information and moves first. The move of Player 1 is observed by Player 2. Player 2 moves second, possibly getting a "signal" from observing the move of player 1. In a screening game it is reversed player 2, the uniformed actor, moves first.


text:
Q: What's the best way to include a LIKE clause in a Rails query? What's the best way to include a LIKE clause in a Rails query i.e. something along the lines of (the completely incorrect):
 Question.where(:content => 'LIKE %farming%')

A: If you want really sexy conditions and and don't have problems with external dependencies, I highly recommend MetaWhere and it's successor Squeel:
# MetaWhere
Question.where(:content.like => '%farming%')

# MetaWhere with operators overloaded
Question.where(:content =~ '%farming%')

# Squeel
Question.where { :content.matches => '%farming%' }

# Squeel with operators overloaded
Question.where { :content =~ '%farming%' }

A: You'd use the syntax:
Question.where("content LIKE ?" , "%#{farming}%")

A: If this is Rails 3 you can use Arel's matches.  This has the advantage of being database agnostic.  For example:
Question.where(Question.arel_table[:content].matches("%#{string}%"))

This is somewhat clunky, but easily extracted to scopes, e.g.:
class Question

  def self.match_scope_condition(col, query)
    arel_table[col].matches("%#{query}%")
  end

  scope :matching, lambda {|*args|
    col, opts = args.shift, args.extract_options!
    op = opts[:operator] || :or
    where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op)
  }

  scope :matching_content, lambda {|*query|
    matching(:content, *query)
  }
end

Question.matching_content('farming', 'dancing') # farming or dancing
Question.matching_content('farming', 'dancing', :operator => :and) # farming and dancing
Question.matching(:other_column, 'farming', 'dancing') # same thing for a different col

Of course to join with "AND" you could just chain the scopes.
Edit: +1 to metawhere and squeel though (haven't tried latter but it looks cool)  They both add this type of functionality and much more.


text:
Q: Hide Rows Based on Check Boxes - Google App Script I'm trying to hide certain rows based on checkboxes that are checked in column 'C'.
Simply put if 'Option A' is checked, I only want to show rows 11 - 13, and row 22. If 'Option B' is checked. I only want to show rows 14 - 15, and row 22, etc.
I also would like to have them revert back after I uncheck. This is more of a learning exercise than anything, so I will get to 'checking multiple boxes' later.
I'm wondering if there should be some 'for' logic in there as well? I'm just not sure where...
Any help or recommendations would be greatly appreciated! Happy to get into more detail if need be.
Thanks a lot,
-M

A: How about this modification? I think that there are several answers for your situation. So please think of this as one of them.
Modification points :

*

*Run the script using onEdit(). This was mentioned by @I'-'I.

*Retrieve the values of all checkboxes.

*the rows which correspond to each checkbox are shown and hidden.

Modified script :
When you use this modified script,

*

*Please copy and paste this script to your script editor, and save it. When you check to the checkbox on the sheet, the rows are shown and hidden.

*

*Before you use this script, please confirm that there are no onEdit() functions in your project.

*When you modify the cell of checkbox and rows, please set cfg. For example, when there is a checkbox at "C7" and the rows are from row 11 to row 13, please set C7: {startRow: 11, endRow: 13}.

Script :

function onEdit(e) {
  var cfg = { // Please set this object.
    C7: {startRow: 11, endRow: 13},
    C8: {startRow: 14, endRow: 16},
    C9: {startRow: 17, endRow: 19},
    C10: {startRow: 20, endRow: 21}
  };

  var activeRange = e.range.getA1Notation();
  var ranges = Object.keys(cfg);
  if (cfg[activeRange]) {
    var sheet = e.source.getActiveSheet();
    var values = sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).getValues();
    values.forEach(function(e, i) {
      if (e[0]) {
        sheet.showRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow);
      } else {
        sheet.hideRows(cfg[ranges[i]].startRow, cfg[ranges[i]].endRow - cfg[ranges[i]].startRow);
      }
    });
  }
}

Note :

*

*In this modified script, if several checkboxes are true, the rows which correspond to each checkbox are shown.

*If you want to run the script at the specific sheet, please modify to if (cfg[activeRange] && e.source.getSheetName() == "### sheet name ###") {.

Rererence :

*

*Event Objects
If I misunderstand your question, please tell me. I would like to modify it.
Edit :
You want to show all rows without hiding, when users open the Spreadsheet. If my understanding is correct, how about this?
function onOpen(e) {
  var cfg = { // Please set this object.
    C7: {startRow: 11, endRow: 13},
    C8: {startRow: 14, endRow: 16},
    C9: {startRow: 17, endRow: 19},
    C10: {startRow: 20, endRow: 21}
  };
  var sheet = e.source.getSheetByName("### sheet name ##");
  var ranges = Object.keys(cfg);
  sheet.showRows(cfg[ranges[0]].startRow, cfg[ranges[ranges.length - 1]].endRow - cfg[ranges[0]].startRow);
  sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).setValue(true);
}

*

*When you use this, please copy and paste it in your script editor.

*onOpen() can be used for running when the spreadsheet is opened.

*You can also use cfg as a global variable.

*When true of sheet.getRange(ranges[0] + ":" + ranges[ranges.length - 1]).setValue(true); is modified to false, when the spreadsheet is opened, all checkboxes are no check and all rows are shown.

A: function onEdit(e) {

    // Replace with the name of your sheet
    var sheetName = 'NameofYourSheet';

    // Align the trigger to the 4 checkboxes
    if (e.source.getActiveSheet().getName() != sheetName
        || e.range.rowStart < 6 || e.range.rowStart > 11 || e.range.columnStart != 3) {
        return;
    }

    // Get checkbox values
    var sh = SpreadsheetApp.getActive().getSheetByName(sheetName),
        status = sh.getRange('C7:C10').getValues();

    // Crude helper func
    function showHideRow(v, i) {
        // [[row, numberRows]]
        var rows = [[11,3],[14,3],[17,3],[20,2]];

        return v[0]
               ? sh.showRows.apply(sh, rows[i])
               : sh.hideRows.apply(sh, rows[i])
    };

    status.forEach(showHideRow);
}


text:
Q: Help with first Core Data project This is my first project which I've encountered that I can't get by on NSUserDefaults peppered with some NSCoding protocol. I've been asked to write some POS software.
Essentially, the App needs to store a bunch of products, prices and sales accounts. The user should be able to add items and accounts, and track the balance of accounts over time. The balance of an account should be able to be carried over from one "Session" (time period) to the next.
I'm comfortable with the concepts, but I'd like to be confident that I'm modeling this right. Here's how I've modeled my data. I'd like to know if I've done this properly or if there are any glaring errors/omissions.
I've created an "Account" Entity, which has the following properties:

*

*First Name

*Last Name

*Account ID

*Group

*There is a relationship to the transaction entity.

I've created an entity for each Session. Again, a session is just like a fiscal month. The session will have a custom name and an ID.

*

*Session ID

*Session Name

*There is a relationship to all of the accounts that are applied to that session.

There are of course, products, which have a name and ID. There is also a relationship to the "price" object, so I can change the prices without affecting balances.
Please see this screenshot from Xcode 4 which explains my model in its entirety:

Edit:
Looking at this, it seems that I'm missing some important info, such as dates of transactions etc. That said, am I on the right track?

A: It has been my experience that point of sale transactions list all the data that is necessary to recreate the receipt in three tables, a header (think date of sale, singular tracking entity), a set of records for all items being sold (linking back to the sale header), and a set of records for all the methods of payment (again linked back to the sale header).
This will give you the opportunity to rebuild the individual transactions in the future. Also, this is a simplistic model, but should suffice for what you're asking. Nominally yo uwould also keep track of applied discounts on a per-line-item basis, and per-invoice discounts, and per-group discounts, and etc.
What's the relationship between sessions and transactions?

A: You probably don't need to have an entity for price, as it will likely just be a float. I'd recommend adding a price attribute to your product entity instead.
I don't know if transactions will need names or not, I suppose if you want to have notes then they should.
Also transactions should probably have a to-many relationship with products.
Will this be used on a single device or will there be many users? If each user (account) is responsible for its own data then it may make more sense to have transactions/session rather than transactions/user.


text:
Q: key board event on dropdown combobox mfc How to handle delete key on dropdown of combobox which is created with style CBS_DROPDOWNLIST?
I want to delete the items in the dropdow list when user presses delete key. Please someone explain how to handle this on a combobox.

A: Either use PreTranslateMessage in the parent dialog to fetch the VK_DELETE key. Or subclass the list control when the combo box drops down.
You can get the handle of the list control with GetComboBoxInfo


text:
Q: How can I make JavaFX re-initialize when Scene is swapped? I want to make a very simple program in JavaFX. It goes like this:
The user inputs something into a TextField
The program displays the input on a label but on a different Scene

Here is my code:
Controller.java
package sample;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import javax.xml.soap.Text;
import java.io.IOException;

public class Controller {

    //textField in sample.fxml
    @FXML
    TextField textField;

    //label in display.fxml
    @FXML
    Label label;

    String text;

    @FXML
    public void enter() throws IOException {
        text = textField.getText();

        Stage stage = (Stage) (textField).getScene().getWindow();

        Parent root = FXMLLoader.load(getClass().getResource("display.fxml"));
        stage.setResizable(false);
        stage.setTitle("Display");
        stage.setScene(new Scene(root, 300, 275));

        label.setText(text);
    }
}

Main.java
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

There are 2 other FXML files containing either a single textField or a single Label.
But whenever I run this code there is a NullPointerException signaling that label is null, because it hasn't been initialized. How do I fix this?

A: I believe you should make antoher controller for the display.fxml file (the other scene). Than in this new controller you can prepare a function to set label value:
DisplayController.java
public class DisplayController {

    //label in display.fxml
    @FXML
    Label label;

    public void setLabelText(String s){
        label.setText(s);
    }
}

and in Controller.java edit enter() function by calling a new DisplayController.java instance:
    @FXML
    public void enter() throws IOException {
        text = textField.getText();

        Stage stage = (Stage) (textField).getScene().getWindow();
        FXMLLoader loader = new FXMLLoader.load(getClass().getResource("display.fxml"));
        Parent root = loader.load();
        DisplayController dc = loader.getController();

        //here call function to set label text
        dc.setLabelText(text);

        stage.setResizable(false);
        stage.setTitle("Display");
        stage.setScene(new Scene(root, 300, 275));

    }


text:
Q: C# Azure Setup second ServiceBus for failover I tried to follow the steps mentioned from Microsoft documentation to set up second ServiceBus to prevent ServiceBus outage.
However, when I run below code, pairing never finishes:
public class ServiceBusContext
{
    public ServiceBusContext()
    {
        var nsManager1 = NamespaceManager.CreateFromConnectionString("...");
        var messageFactory1 = MessagingFactory.Create(nsManager1.Address, nsManager1.Settings.TokenProvider);

        var nsManager2 = NamespaceManager.CreateFromConnectionString("...");
        var messageFactory2 = MessagingFactory.Create(nsManager2.Address, nsManager2.Settings.TokenProvider);

        var sendAvailabilityOptions = new SendAvailabilityPairedNamespaceOptions(nsManager2, messageFactory2, 10, TimeSpan.Zero, false);

        messageFactory1.PairNamespaceAsync(sendAvailabilityOptions).Wait();

        Debug.WriteLine("Cannot reach this code");
    }
}

How to setup ServiceBuses with failover feature properly?

A: While this feature is still available with the old client, I would discourage from using it. Besides a few problematic design issues with the feature, it also doesn't really help with a flow where you need to send and receive. It is only designed for send-only scenario, leveraging fail-over (secondary) namespace as storage. Which inflates the cost in turn as well.
Not to mention that this is a legacy library. The contemporary equivalent is .NET Standard Microsoft.Azure.ServiceBus library. Instead, it offers Geo-DR feature (Premium only) which is not quite the same, but offers fail-over is trully critical scenarios where your namespace is gone. For other than that, the namespace should be available 24/7. With the additional support for Availability Zones with Service Bus (Premium only), you're getting

financially-backed SLA with fault-isolated locations within an Azure region, providing redundant power, cooling, and networking.

which should remove the need for paired namespaces.


text:
Q: Windows 10 Boot Linux without BIOS menu or USB stick I have Linux both command line linux, and Ubuntu, but my computer is Windows 10 based. Also the hardware is not what it used to be. I.e... No working USB port, No DVD slot (But I do have a Micro SD slot if I can boot it from there) but I was wondering if I can install and boot linux directly in Windows? And I was wondering if Windows 10 would be active still, and if I an switch in between the two? I have never worked with Linux or booted it. How can I boot linux in windows without anything but a micro sd card?

A: Use a virtual machine. They allow you to run multiple operating systems at once, and as long as your machine supports virtualization, they work perfectly for the situation you are describing.
My preferred virtualization software include:
VMWare
and
VirtualBox
From there, download and install the Linux .iso file of your choice to be able to open and switch between operating systems at will. Also, make sure to enable virtualization in your BIOS settings.

A: you can not boot linux on windows. you can make Bootable USB and use live linux or use virtual machine like VMWare


text:
Q: Installing LaravelCollective in 5.5.* On xampp,While installing laravelcollective in Laravel 5.5.* version  i got an error saying:-
[UnexpectedValueException]

Could not parse version constraint :5.5.: Invalid version string ":5.5."
I had used composer require "laravelcollective/html":"^5.5." in terminal  for installing it
How to fix this problem?

A: Open your composer.json file and add "laravelcollective/html": "5.4.0", manually
(Try this 5.4.0 version. As I know there is no laravel collective version like '5.5.' )
Should be;
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "intervention/image": "^2.4",
        "laravel/framework": "5.5.*",
        "laravel/tinker": "~1.0",

        "predis/predis": "^1.1",
        "unisharp/laravel-ckeditor": "^4.6",
        "laravelcollective/html":"^5.4.0" //here
    },

Then say composer update, it should works

A: Open your composer.json and following changes on
  "require": {
       "php": ">=7.0.0",
      "doctrine/dbal": "^2.10",
      "fideloper/proxy": "~3.3",
      "laravel/framework": "5.5.*",
       "laravel/tinker": "~1.0",
      "laravelcollective/html": "^5.5" //here
   },

then update your composer as "composer update".
My result on
Updating symfony/css-selector (v5.1.5 => v5.1.6): Loading from cache
    Updating nikic/php-parser (v4.10.0 => v4.10.2): Downloading (100%)
    Installing laravelcollective/html (v5.5.4): Downloading (100%)

while composing.... success.!


text:
Q: How to solve internet connection in ubuntu after upgrade failure I was trying to upgrade a Linux(Ubuntu) and the process went ahead correctly until power went off. Now i am trying to connect via my Ethernet and wireless but no connection.
What could be the problem with what I was doing?

A: If the power failed when you were doing the upgrade, then your system is probably permanently broken.  There is only one practical way to fix it: back up your important files, and install Ubuntu from scratch.  See more information and instructions here.  Good luck.


text:
Q: What does the parameter "source" mean in monaco-editor? There are many methods in monaco-editor that need the parameter "source".
For example, the method trigger in IStandaloneCodeEditor. It's parameters list as belows:

*

*source: string
The source of the call.

*handlerId: string
The id of the handler or the id of a contribution.

*payload: any
Extra data to be sent to the handler.
I'm confused what does source actually mean.


text:
Q: Error when running a basic Hadoop code I am running a hadoop code that has a partitioner class inside the job. But, when I run the command
hadoop jar Sort.jar SecondarySort inputdir outputdir

I am getting a runtime error that says
class KeyPartitioner not org.apache.hadoop.mapred.Partitioner.

I have ensured that the KeyPartitioner class has extended the Partitioner class, but why am I getting this error?
Here is the driver code:
JobConf conf = new JobConf(getConf(), SecondarySort.class);
    conf.setJobName(SecondarySort.class.getName());

    conf.setJarByClass(SecondarySort.class);

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(TextOutputFormat.class);

    conf.setMapOutputKeyClass(StockKey.class);
    conf.setMapOutputValueClass(Text.class);

    conf.setPartitionerClass((Class<? extends Partitioner<StockKey, DoubleWritable>>) KeyPartitioner.class);

    conf.setMapperClass((Class<? extends Mapper<LongWritable, Text, StockKey, DoubleWritable>>) StockMapper.class);
    conf.setReducerClass((Class<? extends Reducer<StockKey, DoubleWritable, Text, Text>>) StockReducer.class);

and here is the code of the partitioner class:
public class KeyPartitioner extends Partitioner<StockKey, Text> {

@Override
public int getPartition(StockKey arg0, Text arg1, int arg2) {

    int partition = arg0.name.hashCode() % arg2;

    return partition;
}
}

A: Notice that there are two partitioners in hadoop:
org.apache.hadoop.mapreduce.Partitioner
org.apache.hadoop.mapred.Partitioner

Make sure your KeyPartitioner class implements the second interface, not the first abstract class.
Edit: You have to set the input and output folders:
FileInputFormat.addInputPath(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));


text:
Q: Set a project in Apache flex? can any one tell me about step by step configuration of Apache flex . I have a project code but I can't understand how to set it at local and run this programme .
I have read the documentation of Apache flex but I can't understand the settings . I have downloaded the software development kit for Apache but I can't understand how to run this ?

A: i have found the real solution 1st download the Apache Flex sdk. then download flex development tool (FDT). and finally download and install JDK.
then it needs some settings for JDK...
For Windows 7: 1. Right click on My Computer. 2. Go to Properties. 3. Click on Advanced system settings. 4. Click on the Advanced tab. 5. Click the Environment Variables button. 6. Under system variables, find the 'Path' variable, select it and click the Edit button.
 1. Add a semicolon to the end of the path value and then paste in the path to your java bin folder. Example: %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_21\bin <--Appended path. 8. Click Ok.
 9. Back in the Advanced tab, under System variables, click the New button. 10. Under Variable name, enter JAVA_HOME. 11. Under Variable value, enter the path to your jre. Example jre path: C:\Program Files\Java\jdk1.6.0_21\jre
Check this link for further details
http://coranguweb.wordpress.com/2013/08/17/
http://coranguweb.wordpress.com/2013/08/14/


text:
Q: Populate array of structure using define I have to create array of structure using a define. Please suggest me how to do it.
file1.c have data
{
    "string1",
     13
}

file2.c have data
{
    "string2",
    14
}

Need to pass this data to one common define so that it can populate data like below:
struct test data[]=
{
    {"string1", 13},
    {"string2", 14}
}

Let me elaborate it here like this:
file1.c
ADD_DATA_IN_STRUCT(....) ---> pass data {"string1", 13}

file2.c
ADD_DATA_IN_STRUCT(....) ---> pass data {"string1", 14}

main.h
#define ADD_DATA_IN_STRUCT(....)  ---> should expand to
struct test data[]=
{
    {"string1", 13},
    {"string2", 14}
}

A: Hope it helps, I've left out the details.
// 1. define the test struct
define struct test {
    char *string;
    int number;
};

// 2. define the data array
struct test data[2];

// 3. read file, assign value to corresponding fields in data array
// you may want to dynamically allocated memory for `string` using `malloc`
// or if the string has a maximum size, define it using `char string[MAX_SIZE]` instead


text:
Q: Why is the speed of light being invariant and finite in all inertial reference frames? I understand the basics of Lorentz transformation and Riemann Geometry but I still cannot understand why the speed of light is the same in all inertial references. Has anyone ever researched about this?

A: Within the theory of special relativity this is postulated. Hence the theory does not address why this is true. If you're wondering why special relativity postulates this, the simple answer is that these are arguably the simplest postulates that give a theory that explains observed phenomena. You may want to read about the history of special relativity to better understand what discoveries and competing theories led up to the formulation of this theory.


text:
Q: Show that the product of some terms of the sequence is congruent to $2$ modulo $p$.
QUESTION: Let $p\geq 3$ be a prime number and $\mathfrak{S}=\{a_1, a_2, \cdots , a_{p-2}\}$ be a sequence of positive integers such that
  $p$ doesn't divide neither $a_k$ or $a_k^k-1$ $\forall k\in \{1,2,\cdots, k\}$. Prove that the product of some terms of the
  sequence is congruent to $2$ modulo $p$.

How to solve the problem?
I can understand that numbers of the form $pk, pk+2; k\in\mathbb{N}$ can be excluded beforehand. Then we are left with the following $p-2$ classes of numbers, i.e, the ones congruent to : $$\bigg\{1,3,4,5,6,\cdots, \frac{p-1}{2}, -\frac{p-1}{2}, \cdots, -3,-2,-1\bigg\}$$.
How to proceed further?
A few of the initial comments might not match. The question was initially wrongly worded. And it has been fixed. Parts of the question and my example (s) have been removed.

A: This is a Mathematical Olympiad problem. A solution can be found here, and I give a modified version below:

Lemma: There exist $p-1$ positive integers $b_1, b_2, \ldots b_{p - 1}$ such that
a) $b_1 = 1$;
b) If $1 \leq i < j \leq p-1$, $b_i \not \equiv b_j \mod p$;
c) For $1 < i \leq j$, $b_i$ is the product of some of the $a_k$ (with $k < i$).

Proof:
Set $b_1 = 1, b_2 = a_1$.
For $2 \leq k \leq p - 2$, suppose we have defined $b_1, \ldots, b_k$ satisfying conditions a, b and c.
Consider the numbers $a_kb_1, a_kb_2, \ldots, a_kb_k$. Since $a_k \not \equiv 0 \mod p$ and all the $b_i's$ are different modulo $p$ by condition c, we know that $a_kb_i \not \equiv a_kb_j$ for $1 \leq i < j \leq k$.
Also, because $(a_k b_1) (a_k b_2) \ldots (a_k b_k) = a_k^k (b_1 \ldots b_k) \not \equiv b_1 \ldots b_k \mod p $ (because $a_k^k \not \equiv 1 \mod p$), we also know that $(a_kb_1, a_kb_2, \ldots, a_kb_k)$ is not a permutation of $(b_1, \ldots, b_k)$ modulo $p$, so that there must exist some $j$ such that $a_kb_j \not \equiv b_i \mod p$ whenever $1 \leq i \leq k$.
Set $b_{k+1} = a_k b_j$, and it's trivial to check that conditions a,b and c are still satisfied.

To finish the proof, let $b_1, \ldots, b_{p-1}$ be as in the Lemma. Because $a_k \not \equiv 0 \mod p$ for each $k$, we know that $b_k \not \equiv 0 \mod p$, so that $(b_k \mod p) \in \{1, \ldots, p-1\}$. By the pidgeonhole principle, there must exist some $k$ such that $b_k \equiv 2 \mod p$; since $b_1 = 1$, we have $k > 1$ and, by condition c in the Lemma, $b_k$ is the product of some of the $a_j$. We are done.

Obs:
1) The choice of $2$ in the problem is arbitrary. There exists some product that is congruent to $m$ modulo $p$ for any $m \in \{2, 3, \ldots, p -1\}.$
2) If we look at the proof of the Lemma, we might get the impression that if the sequence of $a_k's$ were longer (say infinite), we could go on forever and get a sequence of $b_k$ that is as long as we'd like. But this obviously cannot be true by condition b. Is this a contradiction?
No, because by Fermat's Little theorem, the condition $a_k^k \not \equiv 1 \mod p$ cannot be true for $k = p -1$ if $a_k \not \equiv 0 \mod p$. Therefore, we could not have a longer sequence of $a_k$ satisfying both conditions.


text:
Q: Reroute to a profile page w/user data Angular2 and Firebase I am trying to set up a profile page route after the user has signed in through Firebase. My signin component includes a path to the profile route. The only problem here is that my profile component has user data that comes from a Firebase DB. And as a result, when I am redirected to my profile page, I get an error of Cannot read property 'uid' of null.
If I refresh the page after signing in, then my profile page comes up with no errors.
My signin.component.ts
  signInSubmit(){
    var self = this;
    firebase.auth().signInWithEmailAndPassword(self.signInForm.value.smail, self.signInForm.value.spassword).catch(function(error){
    console.log(error.message);
    });
    localStorage.setItem('confirmo', 'verdad');
    self.router.navigate(['profile']);
  }

My profile.component.ts
ngOnInit(){
   var self = this;
   let user = firebase.auth().currentUser;
   let userNamePath = `users/${user.uid}/username`;
   let notesPath = `users/${user.uid}/addnote`;

this.username$ = this.af.database.object(userNamePath);
this.addsnotes$ = this.af.database.list(notesPath);

function redis(){
   self.proshow = true; }
   setTimeout(redis, 3000);
}

To attempt to solve this, I placed a timeout before showing my profile component. However, this does not work. Even if I put my entire ngOnInit inside a timeout function, the same error shows up.
Also, a portion of my profile.component.html if it helps.

Welcome {{ (username$ | async)?.$value }}

A: The answer turned out to be the almighty onAuthStateChanged. Like so:
profile.component.ts
ngOnInit(){
var self = this;
firebase.auth().onAuthStateChanged(function(user){
if (user){
var userNamePath = `users/${user.uid}/username`;
var notesPath = `users/${user.uid}/addnote`;

self.username$ = self.af.database.object(userNamePath);
self.addsnotes$ = self.af.database.list(notesPath);
self.proshow = true;
}
});

}