text:
Q: A random seed that makes tests fail the same way every time? I've never worked with the random library and I'm a bit confused about what this fixme statement is asking me to do. Is there a seed number that specifically does this?
The code is making an ordered list ADT and this file is testing the functions within that file. We use the random library to create random numbers that will be added into, or removed from the ordered list ADT.
Please let me know if there's any other information I should give!

A: The random library will generate the same sequence of random numbers (!) when you provide the same seed value. Any seed will do - 652 is fine as in your example - but could be 7, or 42, or any int value. This is counter-intuitive but basic random numbers generated like this are more accurately called pseudo-random numbers - they are not 100% random since the random sequence can be regenerated exactly the same. This is good for testing though, as indicated in your question.
For this parameter we have the following notes from the python docs:
random.seed(a=None)

*

*Initialize the random number generator.

*If a is omitted or None, the current system time is used. If
randomness sources are provided by the operating system, they are
used instead of the system time.

*If a is an int, it is used directly.

A: When you set the seed, as is done here, you should get a consistent set of random numbers afterwards.
If the numbers that you're getting are NOT consistent, then one of the following is true:

*

*You're using a different random number function somewhere so setting the seed didn't fix it.

*The test depends on external state, so it does different things on different runs.

*You're trying to compare running the entire test suite to testing a single function.

The right fix will depend on which of those is the issue.

*

*Find where you're using a different generator and either stop, or mock it out.

*Find the external state and set it or mock it out.

*Move setting the seed into a setUp method so that it is set fresh for every test.

My guess is that your problem is the last.  But if it isn't, hopefully this answer gives you somewhere to start digging from.

A: When you fix a number using the seed method, all calls for a pseudo-random methods will return the same numbers associated to order of the calls. If you change the number you will have different succession of random numbers. That's why if you want that the random calls produce a different or not controlled value set the seed with a hard to predict number like the exact current time.


text:
Q: Close console after closing a .txt file I've made a simple script that saves disk structure to a .txt file and then opens it. Is there any way to close the console automatically after closing that .txt file?
This is how my code looks. variables.cmd contains all of my variables declarations.
@echo off

call "%~dp0\variables.cmd" /b

%disk%:
cd /

echo Creating folders

md %loc_a%
md %loc_b%
md %loc_c%
md %lok_d%
md %loc_e%
md %loc_f%

echo Folders created
echo %name% > %name%\%aa%_1.txt
echo %aa% > %lokalizacja_a%\%bb%_2.txt
echo %bb% > %lokalizacja_b%\%cc%_3.txt
echo %cc% > %lokalizacja_c%\%dd%_4.txt
echo %dd% > %lokalizacja_d%\%ee%_5.txt
echo %ee% > %lokalizacja_e%\%ff%_6.txt
echo %ff% > %lokalizacja_f%\%gg%_7.txt

cd %name%

set fileone= %aa%_1.txt

copy %icon1% %icon2%

echo [.ShellClassInfo] > %loc_a%\desktop.ini
echo IconFile=%dysk%:\%ikona2% >> %loc_a%\desktop.ini
echo IconIndex = 0 >> %loc_a%\desktop.ini
attrib +h +r -a &loc_a%\desktop.ini
attrib +r %loc_a%

start %name%\%aa%_1.txt

pause

rem I want to close this after I close %pause%\%aa%_1.txt

A: Replace:
start %name%\%aa%_1.txt
pause

With:
start /wait %name%\%aa%_1.txt
REM No need for pause, as you want the script to exit when text is closed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter plugin: invoking iOS and Android method including parameters not working Trying my first Flutter plugin, I try to invoke a method in both, the iOS and the Android-world. I successfully was able to invoke such a method without any parameters.
But now I would like to invoke a method that has parameters.
For iOS, I can't get it to work for some reason. (maybe it is just an autocomplete thing that I keep overseeing since VSCode is not autocompleting my Swift code). But maybe it is something else. Please any help on this.
Here is my code:
My lib (Flutter-world) looks like this:
import 'dart:async';
import 'package:flutter/services.dart';

class SomeName {
  static const MethodChannel _channel =
      const MethodChannel('myTestMethod');

  static Future<String> get sendParamsTest async {
    final String version = await _channel.invokeMethod('sendParams',<String, dynamic>{
        'someInfo1': "test123",
        'someInfo2': "hello",
      });
    return version;
  }
}

.
My swift plugin (iOS-world) looks like this:
import Flutter
import UIKit

public class SwiftSomeNamePlugin: NSObject, FlutterPlugin {

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "myTestMethod", binaryMessenger: registrar.messenger())
    let instance = SwiftSomeNamePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

    // flutter cmds dispatched on iOS device :
    if call.method == "sendParams" {

      guard let args = call.arguments else {
        result("iOS could not recognize flutter arguments in method: (sendParams)")
      }
      String someInfo1 = args["someInfo1"]
      String someInfo2 = args["someInfo2"]
      print(someInfo1)
      print(someInfo2)
      result("Params received on iOS = \(someInfo1), \(someInfo2)")
    } else {
      result("Flutter method not implemented on iOS")
    }
  }
}

The error messages say:
note: add arguments after the type to construct a value of the type
String someInfo1 = args["someInfo1"]
note: add arguments after the type to construct a value of the type
String someInfo2 = args["someInfo2"]
note: use '.self' to reference the type object
String someInfo1 = args["someInfo1"]
note: use '.self' to reference the type object
String someInfo2 = args["someInfo2"]
warning: expression of type 'String.Type' is unused
String someInfo1 = args["someInfo1"]
warning: expression of type 'String.Type' is unused
String someInfo2 = args["someInfo2"]

A: With the help of miguelpruivo, I found the solution.
Here is the working code:
The Flutter-world in Dart was correct:
import 'dart:async';
import 'package:flutter/services.dart';

class SomeName {
  static const MethodChannel _channel =
      const MethodChannel('myTestMethod');

  static Future<String> get sendParamsTest async {
    final String version = await _channel.invokeMethod('sendParams',<String, dynamic>{
        'someInfo1': "test123",
        'someInfo2': 3.22,
      });
    return version;
  }
}

.
And here below, the iOS-world in Swift - now working as well...
(Dart's dynamic corresponds to Swift's Any)
(the method parameter is a dictionary of type [String:Any] - kind of like Swift's often used userInfo - therefore you need to cast at the receiver handler)...
import Flutter
import UIKit

public class SwiftSomeNamePlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "myTestMethod", binaryMessenger: registrar.messenger())
    let instance = SwiftSomeNamePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

    // flutter cmds dispatched on iOS device :
    if call.method == "sendParams" {

      guard let args = call.arguments else {
        return
      }
      if let myArgs = args as? [String: Any],
         let someInfo1 = myArgs["someInfo1"] as? String,
         let someInfo2 = myArgs["someInfo2"] as? Double {
        result("Params received on iOS = \(someInfo1), \(someInfo2)")
      } else {
        result(FlutterError(code: "-1", message: "iOS could not extract " +
           "flutter arguments in method: (sendParams)", details: nil))
      }
    } else if call.method == "getPlatformVersion" {
      result("Running on: iOS " + UIDevice.current.systemVersion)
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

A: This looks like a swift syntax error.
You want to do let someInfo1 : String = args["someInfo1"]


text:
Q: Why zipfile module is_zipfile function cannot detech a gzip file? I am aware of this question Why "is_zipfile" function of module "zipfile" always returns "false"?. I want to seek some more clarification and confirmation.
I have created a zip file in python using the gzip module.
If I check the zip file using the file command in OSX I get this
>  file data.txt
data.txt: gzip compressed data, was "Slide1.html", last modified: Tue Oct 13 10:10:13 2015, max compression

I want to write a generic function to tell if the file is gzip'ed or not.
import gzip
import os

f = '/path/to/data.txt'
print os.path.exists(f)  # True

with gzip.GzipFile(f) as zf:
    print zf.read()  # Print out content as expected

import zipfile

print zipfile.is_zipfile(f)  # Give me false.  Not expected

I want to use zipfile module but it always reports false.
I just want to have a confirmation that zipfile module is not compatible with gzip. If so, why it is the case? Are zip and gzip considered different format?

A:
I have created a zip file in python using the gzip module.

No you haven't. gzip doesn't create zip files.

I just want to have a confirmation that zipfile module is not compatible with gzip.

Confirmed.

If so, why it is the case?

A gzip file is a single file compressed with zlib with a very small header. A zip file is multiple files, each optionally compressed with zlib, in a single archive with a header and directory.

Are zip and gzip considered different format?

Yes.


text:
Q: How to check for version of app and request users to update? How can I check if the user has the current version of my app and also pop up a message to request them to update their app version?
Something like what you would see below.

A: You need to have a WebService on your server (or something similar) that your app requests at startup, to know which is the latest version available. (If you don't have a WS yet and really don't want to implement one for that, you may also simply use an XML or text file that contains the version too)
Then compare this version retrieved from your server with the current version of the application, using [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"].
If they are different, you can display the alertview and redirect to itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftwareUpdate?id=[APPID]&mt=8 (replacing APPID with your iTunes Connect App ID), which is the link that will make your iPhone open the AppStore application directly on your application's update page

A: To check to see if you have the latest version just query iTunes for app data using the following query (note: change the id to match your app's id from iTunesConnect):
http://itunes.apple.com/lookup?id=520604518
This returns a JSON dictionary which is very easy to convert to an NSDictionary to use directly within your code, then all you need to do is pull out the value for the "version" key and compare it against your apps version number (see version key/value bolded below):
{
    "resultCount": 1,
    "results": [
        {
            "kind": "software",
            "features": [],
            "supportedDevices": [
                "all"
            ],
            "isGameCenterEnabled": false,
            "artistViewUrl": "https://itunes.apple.com/us/artist/d-m-holdings/id388608883?uo=4",
            "artworkUrl60": "http://a899.phobos.apple.com/us/r1000/086/Purple/v4/6d/b3/05/6db305aa-c685-558b-8c8e-8b7245375ce1/IconAudio.png",
            "screenshotUrls": [
                "http://a86.phobos.apple.com/us/r1000/078/Purple/v4/8f/ff/47/8fff4783-f2e4-fe3f-ef92-96d67d66c12b/mzl.dwbdvxny.png",
                "http://a731.phobos.apple.com/us/r1000/097/Purple/v4/cb/65/f6/cb65f613-408a-dffe-fb36-165db0c1a360/mzl.jexyhdnq.png",
                "http://a940.phobos.apple.com/us/r1000/097/Purple/v4/f6/26/a1/f626a18c-691f-7345-8d3d-f19713144818/mzl.llsgsagl.png",
                "http://a185.phobos.apple.com/us/r1000/071/Purple/v4/7d/5e/bc/7d5ebcad-7755-e772-727c-65de99effd60/mzl.zuyvhebk.png",
                "http://a48.phobos.apple.com/us/r1000/096/Purple/v4/d6/f5/f1/d6f5f108-10ab-3738-26cf-5ce82c6bb690/mzl.ijtyynie.png"
            ],
            "ipadScreenshotUrls": [],
            "artworkUrl512": "http://a672.phobos.apple.com/us/r1000/100/Purple/v4/e3/cb/5d/e3cb5d2d-f1a8-8b80-3a91-58be8f654710/mzm.uogqezwx.png",
            "artistId": 388608883,
            "artistName": "D&M Holdings",
            "price": 0,
            **"version": "1.0.5",**
            "description": "Designed to enhance the listening experience with Denon's new line of Music Maniac™ headphones, the Denon Audio app is designed for the on-the-go audiophile. The Denon Audio app features a premium audio player that lets you experience the best possible sound quality from your iPod music library and favorite Internet radio stations. Create & save custom EQ curves, create & save instant playlists, enjoy internet radio stations via the built-in TuneIn service, and more. The Denon Audio app will quickly replace all of your other music apps.\n \nThe Denon Audio app features a customizable graphical equalizer that lets you contour your own sound by directly manipulating more than 1000 discrete bands of equalization without adding spatial distortion or decreasing sound quality. Pump up the bass, restore those highs, and start jammin'! \n \nEQ FEATURES:\n \n• Graphical equalizer for your iPod music library and streaming Internet Radio\n• 1000 possible discrete bands\n• 10 built in EQ Presets\n• Create and save your own EQ Presets\n• Bypass mode to quickly compare the original and equalized audio\n• Real-time spectrum analyzer\n• Linear phase design\n• No spatial distortion\n\nIPOD MUSIC LIBRARY FEATURES:\n\n• Enhances your listening experience with Denon Music Maniac Headphones or other audio playback devices such as docking stations, a/v receivers, car stereos via USB, Bluetooth, or Airplay.\n• Powerful queue based playback system lets you build and order your own playlist on the fly.\n• Save the playback queue as a new playlist\n• A single song, all songs on an album, all songs by an artist, and all songs in a genre can easily be added to the now playing queue.\n• Supports both portrait and landscape modes for browsing, playing, and equalizing\n• Shuffle and repeat playback modes\n• iPod library browsing by Playlist, Artist, Album, Song, Genre, Composer, Compilation, and Podcast (no importing needed)\n\nINTERNET RADIO FEATURES:\n\n• The TuneIn service provides global access to Internet radio – covering over 70,000 radio stations and 2 million on-demand programs including sports, news, talk, music and comedy. \n• Browse Internet radio stations by location, genre, language or Podcast (on-demand programs).\n• Powerful search feature for your iPod music library and Internet Radio \n• Save your favorite Internet Radio stations or programs as convenient presets and share them with  other TuneIn compatible devices\n• Ability to choose high or low quality streams offered by broadcasters\n \nADDITIONAL FEATURES:\n\n• Streams music over AirPlay to any Denon AirPlay compatible receiver or HiFi product\n• Share what you're listening to via Facebook, Twitter, Email, or Text Message (iMessage)\n\nNOTICES:\n \n• The Denon Audio app requires iOS 5 or later and works with the iPhone 3GS or newer, the iTouch 3rd generation or newer, and all iPads (in 2x mode). \n• DRM protected iTunes music is NOT supported by the Denon Audio app (or any 3rd party music app)\n• iTunes Match will be supported in a future update \n• WiFi or data connection required to stream Internet radio",
            "currency": "USD",
            "genres": [
                "Music",
                "Lifestyle"
            ],
            "genreIds": [
                "6011",
                "6012"
            ],
            "releaseDate": "2012-05-29T07:00:00Z",
            "sellerName": "D&M Holdings Inc.",
            "bundleId": "com.dm-holdings.denon-audio",
            "trackId": 520604518,
            "trackName": "Denon Audio",
            "primaryGenreName": "Music",
            "primaryGenreId": 6011,
            "releaseNotes": "• Added 4\" display support for the iPhone 5 and 5th generation iPod Touch\n\n• Added an audio limiter function to protect against possible distortion introduced from pushing the EQ too high\n\n• Displays the Shuffle, Repeat, AirPlay, and Share icons as well as the scan/scrub controls on the \"Now Playing\" screen by default (so everyone knows they are included in the app). Tap the cover art to hide/show these controls",
            "formattedPrice": "Free",
            "wrapperType": "software",
            "trackCensoredName": "Denon Audio",
            "trackViewUrl": "https://itunes.apple.com/us/app/denon-audio/id520604518?mt=8&uo=4",
            "contentAdvisoryRating": "4+",
            "artworkUrl100": "http://a672.phobos.apple.com/us/r1000/100/Purple/v4/e3/cb/5d/e3cb5d2d-f1a8-8b80-3a91-58be8f654710/mzm.uogqezwx.png",
            "languageCodesISO2A": [
                "ZH",
                "DE",
                "EN",
                "ES",
                "FR",
                "JA",
                "NL"
            ],
            "fileSizeBytes": "9060882",
            "sellerUrl": "http://www.usa.denon.com/headphones",
            "averageUserRatingForCurrentVersion": 4.5,
            "userRatingCountForCurrentVersion": 329,
            "trackContentRating": "4+",
            "averageUserRating": 4.5,
            "userRatingCount": 471
        }
    ]
}

Here is some code to accomplish this task. -rrh
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",APPSTORE_ID]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if (!error) {
                               NSError* parseError;
                               NSDictionary *appMetadataDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
                               NSArray *resultsArray = (appMetadataDictionary)?[appMetadataDictionary objectForKey:@"results"]:nil;
                               NSDictionary *resultsDic = [resultsArray firstObject];
                               if (resultsDic) {
                                   // compare version with your apps local version
                                   NSString *iTunesVersion = [resultsDic objectForKey:@"version"];

                                   NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)@"CFBundleShortVersionString"];
                                   if (iTunesVersion && [appVersion compare:iTunesVersion] != NSOrderedSame) { // new version exists
                                       // inform user new version exists, give option that links to the app store to update your app - see AliSoftware's answer for the app update link
                                       UIAlertView *alert = [UIAlertView bk_showAlertViewWithTitle:APP_NAME message:[NSString stringWithFormat:@"New version %@ available. Update required.",iTunesVersion] cancelButtonTitle:@"update" otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {

                                        NSString *iTunesLink = [NSString stringWithFormat:@"itms://itunes.apple.com/us/app/apple-store/id%@?mt=8",APPSTORE_ID];
                                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
                                       }];
                                       [alert show];
                                   }
                               }
                           } else {
                               // error occurred with http(s) request
                               NSLog(@"error occurred communicating with iTunes");
                           }
                       }];


text:
Q: How come AWS S3 is erasing my extension from PDF files? In my current app, I've successfully been able to upload PDFs to my storage.  The problem is, when I download the file, it doesn't have an extension and cannot be opened.  I have to add .pdf to the end of the file for it to be recognized (and it does open the correct file).
However in my app, my file already has a .pdf extension, and I know is uploading properly because I'm able to download and open.
  { fieldname: 'files',
  originalname: 'tsunami_zone_e_final.pdf',
  encoding: '7bit',
  mimetype: 'application/pdf',
  size: 2310366,
  bucket: 'company-name-dev',
  key: '123456789999',
  acl: 'public-read',
  contentType: 'application/octet-stream',
  contentDisposition: null,
  storageClass: 'STANDARD',
  serverSideEncryption: null,
  metadata: [Object],
  location: 'https://company-name.s3.us-west-2.amazonaws.com/1521233750192',
  etag: '"12345etag12345etag12345"' } ] }

Here I logged the file after it's been uploaded to S3 storage. In this example the file would be downloaded as 1521233750192 with no file extension if I were to click on that link right now.

A: I am not sure what language/framework you are using but you should make sure to pass the correct Content-Type header. You will also need Content-Disposition header to make sure your file is downloaded with the same originalname property value. And once most browsers will allow for inline display of pdfs, you may also want to force the download (also using Content-Disposition). Here is an example with the nodejs S3 sdk.
var params = {
  Body: <Binary String>,
  Bucket: "youbucket",
  Key: "1521233750192",
  ContentDisposition: 'attachment; filename="tsunami_zone_e_final.pdf";', // from `originalname`
  ContentType: 'application/pdf', // from `mimetype`
 };

 s3.putObject(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
 });

Content-Disposition values can be either inline (default value, indicating it can be display inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).`


text:
Q: How to use UUID for Physical Drives When Bypassing Host: VMWare Workstation on Win7 I have a Linux guest on a Win7 VMWare Workstation host. I route physical drives from the host directly into the VM. I've noticed in the vmdk for these disks that the mapping in the vmdk to a physical drive is done by drive identity (i.e., a number from 0-6). This number matches what you see in disk manager on the host.
I would like to not use drive number, and instead use the ID for the drive (UUID), so that if the ordering of the drives changes, the correct mapping is maintained.
The motivation for this type of solution comes from the problem stated in this post: SATA drive order get scrambled on reboot; Windows 7 / Asus P5Q MB
Is there a way to edit this section of he vmdk file in order for this to happen?
# Extent description
RW 1953525168 FLAT "\\.\PhysicalDrive2" 0

I would like to change PhysicalDrive2 to PhysicalDrive{UUID}, or something VMWare Workstation interprets to mean this.
EDIT: Also posted the question on VMWare Communities: http://communities.vmware.com/message/1986851#1986851


text:
Q: Find number of sub-string in a string between two character(a*b) using python re module Given a string S as input. The program must find the number of patterns matching a*b. where * represent 1 or more alphabets.
import re
s = input()
matches = re.findall(r'MAGIC',s)
print(len(matches))

'''
i/p - aghba34bayyb
o/p - 2
(i.e aghb,ayyb)
It should not take a34b in count.

i/p - aabb
o/p - 3
(i.e aab abb aabb)

i/p : adsbab
o/p : 2
(i.e adsb ab)'''

A: You can use
a[a-zA-Z]+?b

import re
s = input()
matches = re.findall(r'a[a-zA-Z]+?b',s)
print(len(matches))

Python Demo

A: Using re.finditer to match all substrings:
inputs = ['aghba34bayyb',
'aabb',
'adsbab']

import re

def all_substrings(s):
    length, seen = len(s), set()
    for i in range(length):
        for j in range(i + 1, length + 1):
            for g in re.finditer(r'(a[^\d]+b)', s[i:j]):
                if (i+g.start(), i+g.end()) in seen:
                    continue
                seen.add((i+g.start(), i+g.end()))
                yield g.groups()[0]

for i in inputs:
    print('Input="{}" Matches:'.format(i))
    for s in all_substrings(i):
        print(' "{}"'.format(s))

Prints:
Input="aghba34bayyb" Matches:
 "aghb"
 "ayyb"
Input="aabb" Matches:
 "aab"
 "aabb"
 "abb"
Input="adsbab" Matches:
 "adsb"
 "adsbab"

A: You can find the positions of a and b in the word, find all possible substrings and then filter the substrings that only contains one or more chars in between
from itertools import product

words = ['aghba34bayyb', 'aabb', 'adsbab']

for word in words:
    a_pos = [i for i,c in enumerate(word) if c=='a']
    b_pos = [i for i,c in enumerate(word) if c=='b']
    all_substrings = [word[s:e+1] for s,e in product(a_pos, b_pos) if e>s]
    substrings = [s for s in all_substrings if re.match(r'a[a-zA-Z]+b$', s)]
    print (word, substrings)

Output
aghba34bayyb ['aghb', 'ayyb']
aabb ['aab', 'aabb', 'abb']
adsbab ['adsb', 'adsbab']

A: re.findall(r'a[A-Za-z]+?b',s)

Where

*

*[A-Za-z] matches an alphabetic character,

*+ is one or more characters

*? tells it to be nongreedy

A: You could match a followed by 1 char a-z and then use a character class matching 0+ times a or c-z and then match the first b
a[a-z][ac-z]*b

Regex demo
If you want to match all following b's to match aabb instead of aab you could use
a[a-z][ac-z]*b+

Regex demo | Python demo
import re
s = input()
matches = re.findall(r'a[a-z][ac-z]*b+',s)
print(len(matches))


text:
Q: Run Java with third party JAR I've been trying for 1 week to run a simple java program using third party jar, but I keep getting error. Just now I try this program as below
import org.apache.commons.lang3.*;
public class HelloWorld{
        public static void main(String[] args){
                String x = "abcd";
                System.out.println(StringUtils.capitalize(x));
        }
}

and when I try to compile and run, command prompt return error as below
c:\training\java\exercise>javac -cp ".;./org/apache/commons/lang3/commons-lang3-3.9.jar" HelloWorld.java
HelloWorld.java:5: error: cannot find symbol
                System.out.println(StringUtils.capitalize(x));

I take this example from this sites as for reference https://www.programcreek.com/2014/01/compile-and-run-java-in-command-line-with-external-jars/
can anyone help me how to solve this? Thanks in advance
enter image description here

A: There is an article about just that available here
I assume you're on Windows as the working folder has disk C: so it should be Windows.
Bottom line it looks like you're mixing the notions of folder and jar.
Make sure that the folder C:\training\java\exercise contains both HelloWorld.java and commons-lang3-3.9.jar
Also make sure you're in the C:\training\java\exercise folder
Then compile like this:
 javac -cp ".;./commons-lang3-3.9.jar" HelloWorld.java

Now this should create HelloWorld.class file
Now Run the java process:
java  -cp ".;./commons-lang3-3.9.jar" HelloWorld


text:
Q: How do I hide the sound effect icon in PowerPoint? When I add a sound file to my PowerPoint presentation, it shows up in my presentation as a small speaker icon.

How can I hide the sound icon when playing my presentation?

A: If you are using Microsoft PowerPoint 2010, 2013 or 2016:

*

*Click the audio clip icon .

*Under Sound Tools, on the Playback tab, in the Audio Options group, select the Hide During Show check box.

If you are using Microsoft PowerPoint 2007:

*

*Click the audio clip icon .

*Under Sound Tools, on the Options tab, in the Sound Options group, select the Hide During Show check box.

Source: Add audio to your PowerPoint presentation - Microsoft Support

A: In all versions of PowerPoint

*

*Select the sound icon so that the selection box appears.

*Drag the sound icon so that it is no longer on the slide.

This technique is not very useful for grouped objects, as moving the visible area can cause the sound to reappear on screen. However, as sub-objects of groups cannot have separate animations applied to them (including the Play and Pause actions) this will probably not have much of a detrimental effect.


text:
Q: Userform listbox populate with range Is there any way I can populate list box or other feature in user form by range of cells?
I would like to put each of my selected columns into 1 list box like in:
.
For example A2:U100 without creating new list box for every column?
Right now I do it like:
ListBox1.List = Application.Worksheets("Můj_Ranking").Range("B2:B" & lastRw).Value
ListBox2.List = Application.Worksheets("Můj_Ranking").Range("C2:C" & lastRw).Value
ListBox3.List = Application.Worksheets("Můj_Ranking").Range("D2:D" & lastRw).Value
ListBox4.List = Application.Worksheets("Můj_Ranking").Range("E2:E" & lastRw).Value
ListBox5.List = Application.Worksheets("Můj_Ranking").Range("F2:F" & lastRw).Value
ListBox6.List = Application.Worksheets("Můj_Ranking").Range("G2:G" & lastRw).Value
ListBox7.List = Application.Worksheets("Můj_Ranking").Range("H2:H" & lastRw).Value
ListBox8.List = Application.Worksheets("Můj_Ranking").Range("I2:I" & lastRw).Value
ListBox9.List = Application.Worksheets("Můj_Ranking").Range("J2:J" & lastRw).Value
ListBox10.List = Application.Worksheets("Můj_Ranking").Range("K2:K" & lastRw).Value
ListBox11.List = Application.Worksheets("Můj_Ranking").Range("L2:L" & lastRw).Value

A: So you indeed want a ListBox with multiple columns, something like this should help :
With ListBox1
    .ColumnCount = 11
    .ColumnWidths = "50;50;50;50;50;50;50;50;50;50;50"
    .ColumnHeads = False
    .RowSource = "=Můj_Ranking!B2:L" & LastRw
    .MultiSelect = fmMultiSelectMulti
End With

Or how to loop through controls :
For i = 1 To 11
    With Application.Worksheets("Můj_Ranking")
         Controls("ListBox" & i).List = .Range(ColLet(i) & "2:" & ColLet(i) & lastRw).Value
    End With
Next i

And you also have .RowSource property for most of the controls! ;)
And the function to get the letters for columns :
Public Function ColLet(x As Integer) As String
With ActiveSheet.Columns(x)
    ColLet = Left(.Address(False, False), InStr(.Address(False, False), ":") - 1)
End With
End Function

A: haven't tested for Listbox but here is how I fill a Combobox with the result of a recordset
 Function Fill_Combobox(ByRef cbo As ComboBox, ByVal rs As ADODB.Recordset, ByVal colWidth As String)
    Dim aryColumnWidth() As String
    Dim i As Integer

    aryColumnWidth = Split(colWidth, ";")
    cbo.Clear
    cbo.ColumnCount = UBound(aryColumnWidth) + 1
    cbo.ColumnHeads = False
    cbo.ColumnWidths = colWidth

    Do Until rs.EOF
        With cbo
            .AddItem
            For i = 0 To UBound(aryColumnWidth)
                .List(.ListCount - 1, i) = rs.Fields(i)
            Next
        End With
        rs.MoveNext
    Loop
End Function

it should work similar for a listbox. Call the AddItem Method to add an new entry to the listbox and then fill it by accessing the List element

A: Assuming I'm reading your question right, this should add a single line with the number of columns you have in a single ListBox.
for i = 2 to lstRw
    With ListBox1
        .AddItem Application.Worksheets("Můj_Ranking").Range("B" & i).value
        .List(.ListCount - 1 ,1) = Application.Worksheets("Můj_Ranking").Range("C" & i).Value
        .List(.ListCount - 1 ,2) = Application.Worksheets("Můj_Ranking").Range("D" & i).Value

        'And so on for each column
        .List(.ListCount - 1 ,10) = Application.Worksheets("Můj_Ranking").Range("L" & i).Value
    End With
next i

Remember to edit the column count properties of the ListBox control on your userform of it won't work :)


text:
Q: How can variables be used in SQL to perform multiple functions on one column? I'm trying to do a join on two tables with SSN. In one table, the SSN has no dashes, so it starts out simple:
SELECT a.vSSN, b.vSSN
FROM tableA a
inner join tableB b on replace(a.vSSN, '-', '') = b.vSSN

But then, table b also has no leading zeroes. So I want to use the SQL substring function to remove that leading zero from vSSN in tableA:
SUBSTRING(a.vSSN, PATINDEX('%[^0]%', a.vSSN), LEN(a.vSSN))

If I try to use both functions at once, it gets a bit hard to read. What's the correct way to use a variable in my select statement to make it easier to follow? So something like:
DECLARE @var varchar(11)
SELECT a.vSSN, b.vSSN
SET @var = replace(a.vSSN, '-', '')
SET @var = SUBSTRING(@var, PATINDEX('%[^0]%', @var), LEN(@var))
FROM tableA a
inner join tableB b on @var = b.vSSN

A: Is this what you want?
SELECT a.vSSN, b.vSSN
FROM tableA a inner join
     tableB b
     on replace(SUBSTRING(a.vSSN, PATINDEX('%[^0]%', a.vSSN), LEN(a.vSSN)), '-', '') = b.vSSN;

You should really fix your database to have proper primary keys and foreign keys between the tables.
Note:  you cannot use variables for this purpose, although you could use CTEs or subqueries to break up the computation.

A: You can't use a variable, but you can nest some queries w/views, table expressions, or CTEs to split out the calcs:
SELECT A.ssn, B.ssn
FROM (
    SELECT
        SUBSTRING(ssn, PATINDEX('%[^0]%', ssn), LEN(ssn)) as ssn
    FROM (
        SELECT REPLACE(ssn, '-', '') as ssn FROM TableA
    ) Q
) as A
JOIN TableB as B ON A.ssn = B.ssn

You could also use a UDF, of course.


text:
Q: extracting reusable UI parts in cocoa touch - views vs controllers - how should it be done? Let's say I am designing an iPad app that presents user a screen. The screen contains several "controls" that for the sake of this example can be simple labels with +/- signs that increment/decrement integer value presented by the label, making sure that the value doesnt exceed max number defined for each control (numerical up/down control, but could be anything that has some simple logic). As integers are manipulated some read only values are calculated (labels). Moreover each "control" should respond to a tap gesture (and for example increase value by 10)
The question i want to ask is - how should I design such a screen in terms of MVC used in cocoa touch?
Given that the view controller that manages the screen is called MainController:

*

*Should numeric up/down controls be separate views containing all the logic (somehow violates MVC pattern) that are added to MainController.view?

*Should numeric up/down controls be separate viewControllers (with a view attached to them of course) containing all the logic (more reasonable approach in terms of MVC - am I correct?)

*Are touches/gestures processed on viewcontroller or view level?

A: *

*Up/Down controls should be filled with function through the screen's View-Controller (MainController)

*There is no need for extra View-Controllers on that control-level -- in fact, Apple suggests that for such commom situations only one View-Controller exists (MainController)

*Touches/Guestures are processed on View-Controller level (MainController)


text:
Q: How to find out that a method is Long Method? How can I find out that whether a method is considered a long method or not.  Because, it may possibly contain 3 lines of code or it may contain 300 lines of code.  If it contains 3 lines of code then it is not a long method, but if it contains 300 lines of code then definitely it is a long method.  My question is how can someone find out that whether it is a long method or not.  Is there any algorithm?

A: Uncle Bob suggests a method should have no more than 4 lines. Only in rare cases you could disregard this rule.
functions

A: There are many existing metrics packages that measure the size of methods (e.g., the Eclipse Metrics plug-in).  The number of lines that constitutes a "long" method varies by language and by various authors' opinions (e.g., see this book on OO metrics).


text:
Q: Section/Subsection, cited including the subsection with a dot and auto include supra/infra So here is my next issue, this time in the cross-reference. I've tried some other posts found here to use the reference with a mixture of formatting related to my requirements and TOC formatting. I'd like the following :

*

*My section are "I.", "II."

*My subsection are : "1.", "2.", without repeating the section

*All my TOC entries are cited with the trailing "."

*All the subsection cite should include the section but without the trailing dot, i.e. "II.1", "I.2".

*All the section cite should be just the section the trailing dot, i.e. "I" or "II"

*Finally, I'd love to have the automated inclusion of "supra" and "infra" keyword.

To explain on the supra/infra, the is a mandatory requirement (language/domain constraint) that indicate the relative position of the "infra" if the cited part will appears below and supra if the cited part has already been seen above the citation.
I guess all the formatting should be "easy" even if my example is currently not working fine with all the "dots" part.
And additionally, is there a way to make a special command that include the "supra/infra" directly ?
\documentclass{article}

\setcounter{secnumdepth}{3}
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesubsection}{\arabic{subsection}}

\makeatletter
\renewcommand\@seccntformat[1]{\csname the#1\endcsname.\quad}
\renewcommand\p@subsection{\thesection.}
\makeatother

\begin{document}

\tableofcontents

\section{Test Section 1}
A cross-reference to some Subsection that comes below: \ref{a}, \ref{b} and \ref{c}.
This would ideally be cited "infra \ref{a}" and "infra \ref{b}"

\subsection{Test Subsection}\label{a}

\section{Test Section 2}
\subsection{Test Subsubsection}\label{b}
At this point \ref{a} is above citation and \ref{c} is below. It should cite "supra \ref{a}" and "infra \ref{c}"

\section{Test Section 3}
\subsection{Test Subsubsection}\label{c}

A cross-reference to some Subsection that comes below: \ref{a}, \ref{b} and \ref{c}.
This would ideally be cited supra \ref{a}, supra \ref{b}

\end{document}

A: You are almost there. You just need the table of contents to agree and the "infra"/"supra" thing.
You can use tocloft for the TOC and a solution similar to Reference "up" or "down" for "supra"/"infra". The trick is that we can just check if the label was already created, if yes, we have a "supra" reference, if no it must be "infra" (that assumes that all references are defined, undefined references are "infra", but that should be OK).
\documentclass{article}

\setcounter{secnumdepth}{3}
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesubsection}{\arabic{subsection}}

\makeatletter
\renewcommand\@seccntformat[1]{\csname the#1\endcsname.\quad}
\renewcommand\p@subsection{\thesection.}
\makeatother

\usepackage{tocloft}
\setlength{\cftsecnumwidth}{2em}% default is 1.5em
\setlength{\cftsubsecnumwidth}{1.5em}% default is 2.3em
\def\cftsecaftersnum{.}
\def\cftsubsecaftersnum{.}

\usepackage{etoolbox}
\makeatletter
\newcommand*{\xawi@seenlabels}{}
\newcommand*{\lawlabel}[1]{%
  \@bsphack
  \label{#1}%
  \listadd{\xawi@seenlabels}{#1}%
  \@esphack
}
\newcommand*{\lawref@supinf}[1]{%
  \ifinlist{#1}{\xawi@seenlabels}
    {supra}
    {infra}}
\newcommand*{\lawref}[1]{%
  \lawref@supinf{#1}~\ref{#1}}
\makeatother

\begin{document}
\tableofcontents

\section{Test Section 1}\lawlabel{d}
A cross-reference to some Subsection that comes below: \lawref{a}, \lawref{b} and \lawref{c}.
This would ideally be cited "infra \ref{a}" and "infra \ref{b}"

\subsection{Test Subsection}\lawlabel{a}

\section{Test Section 2}
\subsection{Test Subsubsection}\lawlabel{b}
At this point \lawref{a} is above citation and \lawref{c} is below. It should cite "supra \ref{a}" and "infra \ref{c}" finally \lawref{d}

\section{Test Section 3}
\subsection{Test Subsubsection}\lawlabel{c}

A cross-reference to some Subsection that comes below: \lawref{a}, \lawref{b} and \lawref{c}.
This would ideally be cited supra \ref{a}, supra \ref{b}

\end{document}


text:
Q: PHP multi dimensional array increment duplicate I have an array with products where i want to search for duplicate names and increment the duplicate values.
I tried to create an empty array and push all the title values key[0] to it, then i found how many duplicates i have for each value of key[0] with array_count_values.
This is my array;
$products=Array
(
    [0] => Array
        (
            [0] => 'Intel I3',
            [1] => 146,
            [2] => 'intel-i3'
        ),

    [1] => Array
        (
            [0] => 'Intel I3',
            [1] => 146,
            [2] => 'intel-i3'
        ),
    [2] => Array
        (
            [0] => 'Intel I3',
            [1] => 250,
            [2] => 'intel-i3'
        ),
    [3] => Array
        (
            [0] => 'AMD graphic',
            [1] => 146,
            [2] => 'amd-graphic'
        )
);

I want this result with incrementing by 1.
How can i get this result ?
$products=Array
(
    [0] => Array
        (
            [0] => 'Intel I3',
            [1] => 146,
            [2] => 'intel-i3'
        ),

    [1] => Array
        (
            [0] => 'Intel I3_1',
            [1] => 146,
            [2] => 'intel-i3'
        ),
    [2] => Array
        (
            [0] => 'Intel I3_2',
            [1] => 250,
            [2] => 'intel-i3'
        ),
    [3] => Array
        (
            [0] => 'AMD graphic',
            [1] => 146,
            [2] => 'amd-graphic'
        )
);

A: $titleCounts = array();

foreach ($products as &$product) {

    if (!isset($titleCounts[$product[0]])) {
        $titleCounts[$product[0]] = 0;
    } else {
        $titleCounts[$product[0]]++;
        $product[0] = ($product[0].'_'.$titleCounts[$product[0]]);
    }
}

You can see this work here:
http://ideone.com/4xoGgP

A: <?php
$counter = [];
$i = 0;
foreach($products as $product){
    $counter[] = $product[2];
    $vals = array_count_values($counter);
    $current_number = $vals[$product[2]];
    if($current_number)
        $products[$i][0] .= '_'.$current_number;
    $i++;
}

That should do.

A: Tested, and it works.
$tmpArray = array();

foreach ($products as &$product) {
    $name = $product[0];
    if (array_key_exists($name, $tmpArray)) {
        $product[0] = $name . '_' . $tmpArray[$name];
        $tmpArray[$name]++;
    } else {
        $tmpArray[$name] = 1;
    }
}
unset($product);


text:
Q: How to get a foreach statement output in an array with if statement to implode with commas in Wordpress + ACF? I am making a artist portfolio site in wordpress. I am working on a single page for a custom post type Artwork, which contains numerous metadata fields created using ACF. I have run into trouble displaying the contents of an ACF repeater field with the names of collaborators, if there are any, who contributed to the artwork linked to their personal sites if they have one. This repeater is cloned as one element into the Artwork Field group.
I have been able to display the collaborators' names with and without links using the code below. So it will display "Co-creators: Name1 (with href)Name2 (no href)". But the commas don't show up between the collaborators. I think it is because I am not creating the arrays properly.
Any help would be greatly appreciated.
<?php
while (have_posts()) : the_post();
  // lots more code here
  $artwork_collaborators = get_field('artwork_collaborators'); // get the value of the acf clone field
  if ($artwork_collaborators) : // check if has data ?>

<?php
    _e('Co-creators: ', 'aopa'); // multilanguage label for translation
    foreach ($artwork_collaborators as $artwork_collaborator) : // foreach loop to get all collaborators
      if ($artwork_collaborator['artwork_collaborator_url']) : // check if there is a url for the collaborator
        $array_collaborators = array('' . $artwork_collaborator['artwork_collaborator_name']  . ''); // create array with URL
      else :
        $array_collaborators = array($artwork_collaborator['artwork_collaborator_name']); // create array without url
      endif;

      $collaborator_string = implode(", ", $array_collaborators); // implode the array and add commas
      echo $collaborator_string; // echo the collaborators with link or no link separated by commas if there is more than one
    endforeach; ?>

  <?php endif;
  // lots more code here
endwhile?>

A: I ended up getting some help on this problem from a programmer friend. Now the output is "Co-creators: Name1 (with href), Name2 (no href)" with the commas in the right place and the link in place when needed and not there when not.
One of the main problems was that the implode and the echo were inside the loop. This was causing them to repeat too many times.
We also created an empty array off the top, then added all the strings into that. See the comments in the code below:

<?php
    _e('Co-creators: ', 'aopa'); // multilanguage label for translation
    $collaborators_all = []; // Create an empty Array
    foreach ($artwork_collaborators as $artwork_collaborator) : // foreach loop to get all collaborators
      if ($artwork_collaborator['artwork_collaborator_url']) : // check if there is a url for any of the collaborators
        $collaborator = '' . $artwork_collaborator['artwork_collaborator_name']  . ''; // add rows in loop to the variable
      else : // check if there are any collaborators without URLS
        $collaborator = $artwork_collaborator['artwork_collaborator_name']; // add these rows in loop to the variable
      endif;
      $collaborators_all[] = $collaborator; // combine in the array created above all the rows of collaborator names, with and without and links, if there are any of each
    endforeach;
    $collaborator_string = implode(", ", $collaborators_all); // implode the array and add commas
    echo $collaborator_string; // echo the collaborators separated by commas if there is more than one ?>

<?php
  endif; ?>


text:
Q: Как правильно сверстать кнопки? Сверстал 2 кнопки, одна простая, вторая с иконкой. Проблема заключается в том, что обе кнопки не находятся на одной высоте, кнопка с иконкой опустилась на пару пикселей ниже.
В чем проблема и как быть?

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.link {
  background: lightgray;
  display: inline-flex;
  font-size: 5rem;
  border: 1px solid;
}

.link__icon {
  padding: 10px 20px;
  line-height: inherit!important;
  background: azure;
}

.link__text {
  padding: 10px 20px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css" integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">

      Текст

      Текст

  </div

A: Вы поставили display:flex не тому родителю:

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
}

.container__inner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.link {
  background: lightgray;
  display: inline-flex;
  font-size: 5rem;
  border: 1px solid;
}

.link__icon {
  padding: 10px 20px;
  line-height: inherit!important;
  background: azure;
}

.link__text {
  padding: 10px 20px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css" integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">

      Текст

      Текст

  </div

A:

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.link {
  background: lightgray;
  display: inline-flex;
  font-size: 5rem;
  border: 1px solid;
}

.link__icon {
  padding: 10px 20px;
  line-height: inherit!important;
  background: azure;
}

.link__text {
  padding: 10px 20px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css" integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">

      Текст

      Текст

  </div

A: По вопросу - нужно было выставить vertical-align: bottom; кнопкам .link.
@Alex и @Александр Срокин спасибо, что обратили внимание на flex контейнер, действительно, не верно выставил.

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.link {
  background: lightgray;
  display: inline-flex;
  font-size: 5rem;
  border: 1px solid;
  vertical-align: bottom;
}

.link__icon {
  padding: 10px 20px;
  line-height: inherit!important;
  background: azure;
}

.link__text {
  padding: 10px 20px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css" integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">

      Текст

      Текст


text:
Q: How valuable is decoupling in proprietary software? When developing with Symfony2 PHP framework I often see reccomendations to decouple code but most of the time that is accompanied by a 'if you want to release as a third party bundle'.
Which begs the questions, if my software is proprietary should I even bother to decouple it for e.g., using interfaces and models (abstract classes) for defining domain objects. You can use an ORM and create entities which extend from models and if you want to change to an ODM you can create a Document which extends from the model. This is just an example, there are more like having a UserManager which implements a UserManagerInterface (why need this in proprietary software which is never gonna be released to the public).
Decoupling to me looks more like a way to satisfy all needs when releasing your code as open source, which can adapt to most needs.

A: You couldn't be more wrong.
Decoupling is not for the benefit of third-party integrators who might want to take one of your components and rig it together with someone else's other component. The entire idea of reusable software objects that might be sold separately has been a gigantic disappointment, because it's simply too difficult to define clearly and umabiguously want precisely it is that a component is supposed to do.
The benefit is rather that modularized software with isolated parts is far easier to think about and work with, even when all the parts were written by yourself. This is an effect that only becomes perceptible when you program "in the large", beyond the threshold where you can actually hold all details in your head simultaneously. For that reason, there is never a shortage of beginners who think that as geniuses, they don't need structure, modules or visibility restrictions; this is part of the reason why there are so many large projects with an atrociously bad architecture.
In short, decoupling is a good idea because it helps you understand your own creation better. You should only disregard it if you really are a genius (and have no collaborators).


text:
Q: How do I extract emojis from a string in Flutter? I need to extract emojis from a string for this side project I am working on in Flutter
Input:
"Hey everyone "
Output:
""
How do I achieve this?
This is what I have tried so far based on this post
var emojiRegex = RegExp(
  "r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])'");

getEmojis(String message) {
  print("EXTRACTING EMOJI");
  var output = message.replaceAll(emojiRegex,"");
  print("EMOJI: $output");
}

A: You can use
String extractEmojis(String text) {
  RegExp rx = RegExp(r'[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]', unicode: true);
  return rx.allMatches(text).map((z) => z.group(0)).toList().join("");
}

void main() {
    print(extractEmojis("Hey everyone "));
}

Output:
The [\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}] regex is taken from Why do Unicode emoji property escapes match numbers? and it matches emojis proper and light skin to dark skin mode chars and red-haired to white-haired chars.


text:
Q: Remotely performing tasks on a remote Windows Server 2003 server I have to perform various tasks such as restarting processes, monitoring the state of processes, checking disk space and log monitoring on Windows Server 2003.
In order to do this, I am currently using remote desktop which is very slow.
Are there any tools or frameworks for Windows Server 2003 using which I can execute the script on my machine and the required task will be performed on the remote machine in a somewhat interactive manner (like putty in linux)?

A: There are a number of ways you can do this. My preferred method is to use psexec.

A: I'd use wmic or install PowerShell (preferred). Neither of these (nor psexec) are really interactive, though. What do you need this to be interactive for?


text:
Q: Flowlayout Adding control in between controls dynamically I am making a change to an existing application. I am stuck on an issue where I need to add controls in the middle of a flow panel. I have simplified the problem below.
A label and button controls are added per object. I have 3 sets of objects I add at initial screen launch.

When user clicks any button then another object is added:

However, I need the controls to be under the button where it was clicked instead of being added at the bottom. For example, the A button is clicked then the Label D and button d should appear under the A button and moving other controls down. The event is a button but could also be other events like a dropdown but the rules/behaviour are the same. is it possible to add a control in the middle of the flow panel?
Below is a sample of the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Control_Info> list = new List<Control_Info>();
            list.Add(new Control_Info { Label_Name = "Test A", Button_Name = "Desc A" });
            list.Add(new Control_Info { Label_Name = "Test B", Button_Name = "Desc B" });
            list.Add(new Control_Info { Label_Name = "Test C", Button_Name = "Desc C" });

            foreach (Control_Info ci in list)
            {
                loadControlToPanel(ci);
            }

        }

        private void loadControlToPanel(Control_Info ci)
        {
            Label label = new Label();
            label.Text = ci.Label_Name;
            label.AutoSize = false;
            flowLayoutPanel1.Controls.Add(label);

            Button button = new Button();
            button.Text = ci.Button_Name;
            button.AutoSize = false;
            button.Click += new EventHandler(buttonClickEvent);
            flowLayoutPanel1.Controls.Add(button);
        }

        private void buttonClickEvent(object sender, EventArgs e)
        {
            Control_Info ci = new Control_Info{ Label_Name = "Test D", Button_Name = "Desc D" };
            loadControlToPanel(ci);
        }
    }
}

A: Use the SetChildIndex(...); method, e.g:
    Form f5 = new Form();
    FlowLayoutPanel panel = new FlowLayoutPanel { FlowDirection = FlowDirection.TopDown, Dock = DockStyle.Fill };
    f5.Controls.Add(panel);
    Label lbA = new Label { Text = "A" };
    Button btnA = new Button { Text = "A" };
    panel.Controls.Add(lbA);
    panel.Controls.Add(btnA);
    char c = 'B';
    EventHandler action = null;
    action = (o, e) => {
        int index = panel.Controls.IndexOf((Control) o); // index of button clicked
        Label lbNew = new Label { Text = c.ToString() };
        Button btnNew = new Button { Text = c.ToString() };
        btnNew.Click += action;
        c++;
        panel.SuspendLayout();
        panel.Controls.Add(lbNew);
        panel.Controls.Add(btnNew);
        panel.Controls.SetChildIndex(btnNew, index+1);
        panel.Controls.SetChildIndex(lbNew, index+1);
        panel.ResumeLayout(true);
    };
    btnA.Click += action;

    Application.Run(f5);


text:
Q: java.lang.NoClassDefFoundError i am getting java.lang.NoClassDefFoundError error for Constant_Country class, that is exist inside com.mi.uVite.model package.
Class is exist still it says NoClassDefFoundError. How can i overcome this issue?
java.lang.NoClassDefFoundError: com.mi.uVite.model.Constant_Country
        at com.mi.uVite.db.MIDatabaseHandler.createCountryTable(MIDatabaseHandler.java:911)
        at com.mi.uVite.db.MIDatabaseHandler.onCreate(MIDatabaseHandler.java:632)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
        at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
        at com.mi.uVite.db.MIDatabaseHandler.rowCount(MIDatabaseHandler.java:570)
        at com.mi.uvite.BackGroundIntentService$1.onResponse(BackGroundIntentService.java:110)
        at com.mi.uvite.BackGroundIntentService$1.onResponse(BackGroundIntentService.java:67)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:1)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)

And
public class Constant_Country
{
public static String country_id = "country_id";
public static String country_short_code = "country_short_code";
public static String country_name = "country_name";
public static String country_code = "country_code";
}

A: I think you have to add the class Constant_Country into the package com.mi.uVite.model and put in the first line of Constant_Country
package com.mi.uVite.model

Remember that if you use an object of type Constant_Country you have to use an import.


text:
Q: how to get user input as a value in jq in shell script I have a JSON file from which I am trying to get a value using below
[a223180n@363748ln41dk012 ~]$ cat status.json| jq  '.details.server1.status'
"UP"

In my script, I have the option where the user will enter the server name. So I need the script to pick that value and update the jq command accordingly I am using below and it is failing.
jq is 1.6 version
[a223180n@363748ln41dk012 ~]$ cat status.json| jq --arg server server1'.details.$server.status'
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.details.$service.status
jq: 1 compile error

A: < status.json jq --arg server server1 '.details[$server].status'

The dot operator is a special version of the [] operator that only works with literal keys. You have a variable for a key here, so you need the [] operator.


text:
Q: Caused by android.view.InflateException on Android 10 API level 29 My app runs on every API level, but failing to load on some specific devices sometime.
this time it's failing to find resources which are already there on a HUAWEI device, with device details as follow:
Build.DEVICE : HWJNY
Build.FINGERPRINT : HUAWEI/JNY-LX1/HWJNY:10/HUAWEIJNY-L21/10.1.0.388C432:user/release-keys
Build.HARDWARE : kirin810
Build.PRODUCT : JNY-LX1
Location : RO
Brand:HUAWEI
Model:JNY-LX1
Orientation: Portrait
RAM free: 1.57 GB
Disk free: 103.26 GB
Operating system
Version:Android 10
Orientation: Portrait
Rooted:No

Stacktrace:
Non-fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.package/com.package.onboarding.VerifyPhoneNumberActivity}: android.view.InflateException: Binary XML file line #49 in com.package:layout/activity_verify_phone_number_new: Binary XML file line #49 in com.package:layout/activity_verify_phone_number_new: Error inflating class androidx.appcompat.widget.AppCompatImageView
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3897)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
       at android.os.Handler.dispatchMessage(Handler.java:110)
       at android.os.Looper.loop(Looper.java:219)
       at android.app.ActivityThread.main(ActivityThread.java:8349)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)

more to stacktrace:
Caused by android.content.res.Resources$NotFoundException: Resource ID #0x7f080271
       at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:328)
       at android.content.res.Resources.getValue(Resources.java:1468)
       at androidx.appcompat.widget.ResourceManagerInternal.createDrawableIfNeeded(ResourceManagerInternal.java:179)
       at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:144)
       at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:135)
       at androidx.appcompat.content.res.AppCompatResources.getDrawable(AppCompatResources.java:104)
       at androidx.appcompat.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:63)
       at androidx.appcompat.widget.AppCompatImageView.<init>(AppCompatImageView.java:82)
       at androidx.appcompat.widget.AppCompatImageView.<init>(AppCompatImageView.java:69)
       at java.lang.reflect.Constructor.newInstance0(Constructor.java)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
       at android.view.LayoutInflater.createView(LayoutInflater.java:864)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1016)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:971)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1133)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1094)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:536)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
       at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
       at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
       at androidx.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:303)
       at androidx.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:284)
       at com.talkhome.onboarding.VerifyPhoneNumberActivity.onCreate(VerifyPhoneNumberActivity.kt:53)
       at android.app.Activity.performCreate(Activity.java:8085)
       at android.app.Activity.performCreate(Activity.java:8073)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3870)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
       at android.os.Handler.dispatchMessage(Handler.java:110)
       at android.os.Looper.loop(Looper.java:219)
       at android.app.ActivityThread.main(ActivityThread.java:8349)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)

ImageView where inflation is failing:
<androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/img"
            app:layout_constraintHeight_percent="0.35"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/guide_line"
            app:srcCompat="@drawable/mobileverification" />

Any idea what could be failing it?


text:
Q: Is there an alternative to pyinstaller for python 3.8? Since pyinstaller is not available for python 3.8, is there any alternative to convert a .py file into a .exe file?
Edit(for better understanding): I am searching another compiler because pyinstaller is not updated for py 3.8 yet because of the changes in the python bootloader(https://github.com/pyinstaller/pyinstaller/issues/4311)

A: Alternatives for pyinstaller are,
py2exe
autopy2exe
cx_freeze

py2exe is the same like pyinstaller,
autopy2exe has UI for converting the script to executable,
cx_freeze is platform independent exe creation method.

A: PyOxidizer is another "fresh" one take in this domain.
Here is the comparison of it vs other tools mentioned in the accepted answer.


text:
Q: Are these private static members thread safe? I have the following code with private static members.
All of these classes say that they are thread safe in the MSDN library for "public static" members.
My question is whether these members will be thread safe when used as private static instead of "public static" as stated in the MSDN library.
 public static class passwordManager
{
    private static System.Security.Cryptography.SHA256 shaM = new System.Security.Cryptography.SHA256Managed();
    private static System.Security.Cryptography.RandomNumberGenerator rand = new System.Security.Cryptography.RNGCryptoServiceProvider();
    private static System.Text.Encoding enc = System.Text.Encoding.ASCII;

    public static string produceSalt(int size)
    {
        byte[] by = new byte[size];
        lock (rand)
        {
            rand.GetBytes(by);
        }
        return enc.GetString(by, 0, by.Length);
    }

    public static string encryptPassword(string password, string salt){

        return enc.GetString(shaM.ComputeHash(enc.GetBytes(password + salt)));
    }

    public static bool isCorrectPassword(string inputPassword, string DBsalt, string DBpassword)
    {
        return encryptPassword(inputPassword, DBsalt) == DBpassword;
    }

This might be entirely dependent on whether the methods I am using themselves use shared variables instead of all method instance variables... some peace of mind would be helpful but I would rather not have to lock everything here if it isn't necessary.
The only reason I locked the random number generator is to limit the possibility of getting the same salt however the chances of this being called by two threads at the same time is very low in my situation.
Thanks,
Mike
This should now be thread safe. I was trying to save on object instantiation overhead but I guess there is a trade off between this and lock waiting. On a high load system lock waiting would likely greatly overpower instantiation overhead and memory usage.
    public static class passwordManager
{
    private static System.Security.Cryptography.RandomNumberGenerator rand = new System.Security.Cryptography.RNGCryptoServiceProvider();

    public static byte[] produceSalt(int size)
    {
        byte[] by = new byte[size];
        lock (rand)
        {
            rand.GetBytes(by);
        }

        return by;
    }

    public static byte[] encryptPassword(string password, byte[] salt){

        System.Security.Cryptography.SHA256 shaM = new System.Security.Cryptography.SHA256Managed();
        System.Text.Encoding enc = new System.Text.UTF8Encoding();

        return shaM.ComputeHash(concatArrays(enc.GetBytes(password), salt));
    }

    public static bool isCorrectPassword(string inputPassword, byte[] DBsalt, byte[] DBpassword)
    {
        return compare(encryptPassword(inputPassword, DBsalt), DBpassword);
    }
}

A: thread safety won't depend on whether something is private or public.
BTW, thread safety document says any public static members of this type, not when this type is embedded as public static.
In short you have to lock your fields like sham, if you are multi-threading.

A: Your code is not thread-safe.
Consider the System.Text.Encoding variable enc. You are calling GetString which is an instance member. The documentation says that only public static members are thread-safe so by inference GetString is not thread-safe because it is not a public static member.1
This code may fail due to the following reasons:

*

*You have made no attempt to synchronize access to Encoding.GetString.

*Encoding.GetString is called from a public static method in your passwordManager class.

*Public static methods have a high probability of being executed by multiple threads simultaneously.

The reason why public static methods are almost always designed to be thread-safe is because it would be awkward for the caller to always synchronize access to it. You cannot limit multithreaded access to static members like you can with instance members. Consider an ASP.NET application, for example. Web page requests are frequently handled concurrently on separate threads. Do you want to use a lock everytime you call a static method? Of course not. This is a ridiculous burden to place on a developer.
Update:
Your new code is now thread-safe. You will have to do some benchmark tests to see which way is faster: using a lock or instantiating new instances on every call like you have now. I would not be surprised if the lock were faster.

1The same could be said for shaM.ComputeHash and enc.GetBytes.

A: You might be better off creating method level variables instead of trying to make synchronise access to shared private fields. That way you will still achieve concurrency as each thread has it's own call stack so will have separate instances of each object and thus allow multiple threads to execute the method simultaneously. If you lock on a shared object then only one thread can execute the method at a time. Another option may be to use the [ThreadStatic] attribute on each field so they will not be shared across threads.


text:
Q: autobreak not working if left and right delimeter breaks My code follows:
\documentclass{book}
\usepackage{amsmath,autobreak}

\begin{document}

\begin{align}
\begin{autobreak}
a+b=c\left(\sum
+\prod\right)
\end{autobreak}
\end{align}

\end{document}

if I remove the linebreak after sum then it works nice. Is this any possible to make it work even if the left and right delimeter breaks.


text:
Q: Using the Enter Key to move between Textboxes A user of one of my apps said that he was "expecting" the Enter key to move between the Textboxes.  Is there a way to do that with the Windows Phone?
See you can set the TabIndex of each control but do I have to write a lot of code to capture the onKeyDown?
Just wondering if there is an easy way to add this feature.

A: One decent options is, by implementing logic to move between Textboxes as Custom Behavior. Like done by Mike Hole as written in his blog. With Mike's custom behavior, we can simply attach that behavior to the textbox and specify control name to move focus to upon enter key pressed :
<TextBox x:Name="txtUsername">
    <i:Interaction.Behaviors>
        <mh:OnEnter NextControlName="txtPassword" />
    </i:Interaction.Behaviors>
</TextBox>


text:
Q: D3 Dendrogram - Not shown I'm trying to work with a Dendrogram from the D3 library. I understand the example as far, but I can't see anything while viewing the file in the browser. It's just a white screen. Can someone help me how to show the figure?
Or do you need further information?
Thanks allready for your help!
Here is the link to the project: Dendrogram D3

A: Looks like there are javascripts error with generation your dendrogram.
What browser do you use? If it's chrome press F12 to debug your web page and see where error is.
If you just copied html example most likely you've missed json file invoked inside of this example /mbostock/raw/4063550/flare.json


text:
Q: Batch, read filename backwards I'm working on a little script that moves files to a different map sorted by the last 2 characters, now my problem is, files always look like this:
1238184AD
1237135881AD
123477TG

And my problem here is, I can move files to the correct map if they have a fixed length, but they are not fixed. Sow now my question is, can I count the filename backwards so that the script will make a directory of the last 2 characters.
This is how my current script looks like:
@ECHO OFF
setlocal enabledelayedexpansion

set index=~8,2
set moveFrom=C:\Users\**\Desktop\Map\
set moveTo=C:\Users\**\Desktop\Map2\

for /R "%moveFrom%" %%f in (*.txt) do (
    echo %%f
    set "fileName=%%~nf"
    cd %moveTo%
    IF EXIST "!fileName:%index%!" (
        move /-y "%%f" "%moveTo%"!fileName:%index%!"\"
        echo "%%f" moved
    ) ELSE (
        mkdir "!fileName:%index%!"
        move /-y "%%f" "%moveTo%"!fileName:%index%!"\"
        echo "%%f" moved
    )
)

pause


text:
Q: How to use .properties in a Spring Validation annotation I have the following annotation
@Size(min=5,message="{error.address1.null}")

and the following in my properties
#Error Messages
error.address1.null = Address is required

and the following jsp
<form:errors path="addressLine1" cssClass="error" />

But I see
{error.address1.null}

Do i have to wire something? What am I missing?

A: Amazingly easy
@Size(min=5)

properties
Size.class.getterSetter = message

Not sure how this will work for multiple annotations in Java8


text:
Q: what's the best way to clone a graph in Jung? the title pretty much sums it all -
I'm using Jung as my graph model and I want to clone my graphs. is there a best-practice for this?
thanks

A: You could do a simple copy of vertices & edges:
Graph<V, E> src;
Graph<V, E> dest;

for (V v : src.getVertices())
    dest.addVertex(v);

for (E e : src.getEdges())
    dest.addEdge(e, src.getIncidentVertices(e));

that would create a new Graph, but the objects inside will be passed by reference
so you could use this cloning library
https://code.google.com/p/cloning/
and do a deep copy:
Cloner cloner = new Cloner();
Graph<V, E> clonedGraph = cloner.deepClone(graph);


text:
Q: Move values between columns in MYSQL (?) I'm trying to move the value of 3 different columns between them but I can't make it works correctly
<?php

include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'db_manual_connect.php';

$error_msg = "";
if (isset($_POST['value'], $_POST['id'])) {
$value= $_POST['value'];
$id = $_POST['id'];

    if (!$conn) {
         die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "UPDATE equipo SET
    slot1= CASE WHEN slot1= '".$value."' THEN slot1
                    WHEN slot2= '".$value."' THEN slot2
                    WHEN slot3= '".$value."' THEN slot3 END,

    slot2= CASE WHEN slot1= '".$value."' THEN slot2
                    WHEN slot2= '".$value."' THEN slot1
                    WHEN slot3 = '".$value."' THEN slot2 END,

    pokemon3 = CASE WHEN slot1= '".$value."' THEN slot3
                    WHEN slot2= '".$value."' THEN slot3
                    WHEN slot3= '".$value."' THEN slot1 END WHERE id = '".$id."'";

    $result = mysqli_query($conn, $sql);

A: You can do it with a query like this. first you must save the values from slot1-3 in local variables and the you can test and set the fields.
UPDATE  theTable t
CROSS join ( SELECT @tmp_slot1:=0, @tmp_slot2:=0, @tmp_slot3:=0) AS init
set
    t.slot1 = @tmp_slot1 := t.slot1, -- save the val from slot1 into @tmp_slot1
    t.slot2 = @tmp_slot2 := t.slot2, -- save the val from slot2 into @tmp_slot2
    t.slot3 = @tmp_slot2 := t.slot3, -- save the val from slot3 into @tmp_slot3

    t.slot1= CASE WHEN @tmp_slot1= '".$value."' THEN @tmp_slot1
                  WHEN @tmp_slot2= '".$value."' THEN @tmp_slot2
                  WHEN @tmp_slot3= '".$value."' THEN @tmp_slot3 END,

    t.slot2= CASE WHEN @tmp_slot1= '".$value."' THEN @tmp_slot2
                  WHEN @tmp_slot2= '".$value."' THEN @tmp_slot1
                 WHEN @tmp_slot3 = '".$value."' THEN @tmp_slot2 END,

    t.pokemon3 = CASE WHEN @tmp_slot1= '".$value."' THEN @tmp_slot3
                      WHEN @tmp_slot2= '".$value."' THEN @tmp_slot3
                      WHEN @tmp_slot3= '".$value."' THEN @tmp_slot1 END
WHERE id = '".$id."'";

please let me know if it work for you. its nit tested
sample with 2 fields
mysql> SELECT * from theTable;
+----+-------+-------+
| id | slot1 | slot2 |
+----+-------+-------+
|  1 |     3 |     6 |
|  1 |     6 |    12 |
|  1 |     8 |    16 |
|  2 |     5 |    10 |
|  2 |     7 |    14 |
+----+-------+-------+
5 rows in set (0,00 sec)

mysql> update  theTable t
    -> CROSS join ( SELECT @tmp_slot1:=0, @tmp_slot2:=0) AS init
    -> set
    ->     slot1 = @tmp_slot1 := slot1,
    ->     slot2 = @tmp_slot2 := slot2,
    ->     slot1 = @tmp_slot2,
    ->     slot2 = @tmp_slot1;
Query OK, 5 rows affected (0,00 sec)
Rows matched: 5  Changed: 5  Warnings: 0

mysql> SELECT * from theTable;
+----+-------+-------+
| id | slot1 | slot2 |
+----+-------+-------+
|  1 |     6 |     3 |
|  1 |    12 |     6 |
|  1 |    16 |     8 |
|  2 |    10 |     5 |
|  2 |    14 |     7 |
+----+-------+-------+
5 rows in set (0,00 sec)

mysql>


text:
Q: Visualforce Page and Custom Component same record field update I've created a visualforce page and custom component that is referencing the same record, in which I've passed the record from the standardController to the custom component via apex:atttribte.
I have input fields on both the Main Visualforce page and Custom Component page but when I'm trying to save the record(The save button and method is in the main page) the update from the custom component is not being saved.
Here's my code:
Main Visualforce Page:
  <apex:page standardController="Account" extensions="AccountTestController">
            <apex:form>
                <apex:messages/>
                <apex:pageBlock title="Page Section">
                    <apex:pageBlockButtons>
                        <apex:commandButton action="{!saveAcc}" value="Save"/>
                    </apex:pageBlockButtons>
                    <apex:pageBlockSection>
                        <apex:inputField value="{!acc.LastName}" required="true"/>
                    </apex:pageBlockSection>
                </apex:pageBlock>
            </apex:form>
            <c:AccoutnComponent accRecord="{!acc}"/>
</apex:page>

Main Page Controller:
public class AccountTestController {

    public Account acc {get; set;}

    public AccountTestController(ApexPages.StandardController stdController) {
        if(stdController.getID() != null) {
            acc = [SELECT Id, LastName,Name, Phone, isPersonAccount FROM Account WHERE Id=: stdController.getID()];
        } else {
            acc = new Account();
        }

    }

    public PageReference saveAcc() {
        upsert acc;

        return new PageReference('/');
    }

}

Custom Component Page:
<apex:component controller="AccountComponentController">
    <apex:attribute name="accRecord" assignTo="{!pageAcc}" description="Account from Main Page" type="Account"/>
    <apex:form>
        <apex:pageBlock title="Component Section">
            <apex:pageBlockSection>
                <apex:outputField value="{!pageAcc.Name}"/>
                <apex:inputField value="{!pageAcc.Phone}" required="true"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:component>

Custom Component Controller:
public class AccountComponentController {
    public Account pageAcc {get; set;}

    public AccountComponentController() {

    }
}

Here's how it looks

It seems that I was able to retrieve the values from the main page since the Last Name is being reflected from the component page, it's just that the update from the field in the component section is not being saved upon clicking the Save button from the Main Page.
Am I doing something wrong here? Enlighten me please.
Thanks!

A: Always try avoiding duplicate forms in your maarkup.The code has two forms here and hence the issue .Use single form always .

A: You can leave the Form tag on both the main Visualforce page and the Component. Just move the call to the component within the Form tag of the main page not after the  tag.


text:
Q: Xpath for xml search I have xml file that I want to search for a word say searchTearm and then want to return names of tags surrounding that search term.
ex :- in below case searchTerm is surrounded by tags namespace, querySubject and queryItem, I am trying to return name of these tags. Name is enclosed in name tag.
Any help with single line xpath for this:
<namespace>
    <name locale="en">Test</name>
    <lastChanged>2016-01-12T12:42:46</lastChanged>
        <namespace><name locale="en">Database Layer</name>
            <querySubject status="valid"><name locale="en">qsxyz</name>
                <queryItem><name locale="en">qixyz</name>
                    <>...searchTerm..</>
                </queryItem>
            </querySubject>
        </namespace>
 </namespace>

below xpath doesn't seem to work :-
/namespace/namespace/querysubject/queryItem[contains(., 'searchTerm')]

A: if i understood correctly
/namespace/namespace/querySubject/queryItem[contains(., 'searchTerm')]/ancestor-or-self::*/name

selects name tags for all ancestor of queryItem with searchTerm
result
Element='<name locale="en">Test</name>'
Element='<name locale="en">Database Layer</name>'
Element='<name locale="en">qsxyz</name>'
Element='<name locale="en">qixyz</name>'

if you add trailing /text() you will receive not elements but there values


text:
Q: How to take user message and use it as command I use Python 3 and python-telegram-bot .
The user send a message like this "When i say ... say ...." example : "When i say Hi say Hello "
i can take "Hi and Hello" from the message
My problem is how to set Hi in bot to when user say hi my bot say Hello
i try to use MessageHandler for example :
MessageHandler(Variable,Callback)

Variable have hi for example
but when i send hi my bot does not send Hello
but when i send hi my bot does not send Hello

A: Well, you can use an event. on_message should work. Try this:(rewrite)
bot.msg = "Hi" #just create a command in which you would assign a text to bot.msg

   @bot.listen()
    async def on_message(message):
        if message.content.lower() == bot.msg.lower()   #you can set a bot variable, I'll use `bot.msg`
    await message.channel.send("Hello")


text:
Q: jquery not working in IE11 These are my methods for jQuery but it seems that it is not working in IE11, however the same code is working in firefox and chrome.
   function createCategory()
    {
    showLoading();

        $.post('<s:url value="/social/addEditCatSettings"/>',function(data){
                hideLoading();
                $.prompt(data, {
                        title: "Add Categories",
                        buttons: { "Add": true, "Cancel": false },
                        submit: function(e,v,m,f){
                            if(v){
                                e.preventDefault();
                                saveUpdateCat();
                                }
                        }
                 });
            });
    }

  function saveUpdateCat(id)
    {
       var name = $('#catName').val();
       var name_sanitized = name.replace(some scritp....);
       if(name !== name_sanitized)
       {
            ShowMessage('Invalid input. Please try again.',true);
       }
       else
       {
       var type = false;

       jsonObj = [];
       item = {}
       item ["name"] = name;
       item ["type"] = type;

       if(typeof id != 'undefined')
        {
           item ["id"] = id;
        };

       if( btrim(name).length >0 )
        {
           item["mytoken"]='<s:property value="#session.mytoken"/>';

           $.post('<s:url value='/social/saveOrUpdateCatSettings' />',item,function(data){

               if(data == 200)
                 {
                     hideLoading();
                     $.fancybox.close();

                    if(typeof id != 'undefined')
                    {
                        ShowMessage('category updated successfully',false);
                    }
                    else
                     {
                        ShowMessage('category saved successfully',false);
                     }
                     loadTabContent('MANAGECATS',profileId);
                 }
               else
                   {
                    ShowMessage('Please try again.',true);
                   }
             });

        }
        else
        {
            ShowMessage('Error,Please fill the required (*) fields',true);
            hideLoading();

        }
       }
    }

A: After hell of wasting hour,
i replaced $post by $ajax and modified lines accordingly, it worked for me.


text:
Q: Issues creating object literal using anonymous types in c# I'm trying to build the c# approximation of a JavaScript object literal to be passed to a view model in asp.net MVC:
var obj = new dynamic[]{
    new { name: "Id", index: "Id", width: 40, align: "left" },
    new { name: "Votes", index: "Votes", width: 40, align: "left" },
    new { name: "Title", index: "Title", width: 200, align: "left"}
};

The compiler is throwing:
"An anonymous type cannot have multiple properties with the same name"

Stab in the dark I'm guessing it can't distinguish between the which property goes with which anonymous object, I've seen a similar error using LINQ.
Is there a better way to accomplish what I'm trying to do?
EDIT: This is in VisualStudio 2010 and .net Framework 4. Bala R's Answer seems to address the problem for previous versions though.

A: Can you try this?
var obj = new[]{
    new { name= "Id", index= "Id", width= 40, align= "left" },
    new { name= "Votes", index= "Votes", width= 40, align= "left" },
    new { name= "Title", index= "Title", width= 200, align= "left"}
};

and you should be able to access the anonymous class array like this
if (obj[0].align == "left")
{
   ...
}


text:
Q: How to install a FindXXX.cmake to a correct location? I am developing a library which uses CMake to control it. It would be good to provide a "FindXXX.cmake" which locates the library and header files. This file would enable the users to use the command "find_package(XXX)" to find my library.
However, I don't know how to install my lib's "FindXXX.cmake" to an correct location. I failed to find a CMake's build-in mechanism to install a "FindXXX.cmake". In addition, CMake's variable "CMAKE_MODULE_PATH" is a list of directories, so I cannot install according to that vairable because I cannot decide which specific directory to use.

A: If the copy of CMake is installed to a standard location(i.e. use no prefix etc) then this can be done by placing the file in /usr/share/cmake/Modules/ directory.
If you are going to supply a bundle probably you can add some commands to check if the cmake is available. if yes you can check for cmake --system-information|grep _INCLUDED_SYSTEM_INFO_FILE value from that to get modules directory.
Otherwise there's no way you can do that.
A workaround can be done i.e. if there is a binary in your bundle then you can add a command line option for placing this file.


text:
Q: Is there a function to shift degrees of a circle past 0? I'm looking for a function somewhere in Delphi XE2 similar to Inc() which allows me to add/subtract a number of degrees from a current number of degrees and result in the new degrees. For example, if I have a point currently at 5 degrees around a circle, and I want to subtract 10, I should not get -5 degrees, but rather 355 (360 - 5). Same as adding past 360 - it should go back to 0 when it reaches 360.
Is there anything like this already in Delphi so I don't have to re-write it? Perhaps in the Math unit?

A: function WrapAngle(Value: Integer): Integer;
begin
  Result := Value mod 360;
  if Result < 0 then
    Inc(Result, 360);
end;

A: The code I use to perform this task is:
function PosFrac(x: Double): Double;
(* PosFrac(1.2)=0.2 and PosFrac(-1.2)=0.8. *)
begin
  Result := Frac(x); (* Frac(x)=x-Int(x) *)
  if Result<0.0 then begin
    Result := 1.0+Result;
  end;
end;

function ModR(const x, y: Double): Double;
(* ModR(1.2,1)=0.2 and ModR(-1.2,1)=0.8 *)
var
  absy: Double;
begin
  if y=0.0 then begin
    Result := 0.0;
  end else begin
    absy := abs(y);
    Result := PosFrac(x/absy)*absy;
  end;
end;

function Mod360(const x: Double): Double;
begin
  Result := ModR(x, 360.0);
end;

This code will bring all angles into the range 0 to 360. For example:
Writeln(Round(Mod360(5-10)));
Writeln(Round(Mod360(5-360)));
Writeln(Round(Mod360(5-720)));
Writeln(Round(Mod360(5+720)));

outputs:

355
5
5
5

A: uses
  System.SysUtils,Math;

Function WrapAngle( angle : Double) : Double;
Const
  modAngle : Double = 360.0;
begin
  Result := angle - modAngle*Floor(angle/modAngle);
end;

begin
  WriteLn(FloatToStr(WrapAngle(-5)));
  WriteLn(FloatToStr(WrapAngle(5-720)));
  WriteLn(FloatToStr(WrapAngle(360)));
  ReadLn;
end.

Produces result:
355
5
0

Update:
As @Giel found, in XE3 there is a new function DegNormalize() which does the job. Even about 25% faster. The trick is to replace the Floor() call with an Int() instead, and if the result is negative, add modAngle to the result.

A: I don't know any, but I'd prefer using a more general solution anyway ...
Procedure IncOverFlow(var Value:Double;Difference:Double;Limit:Double=360);
begin
   Value := Value + Difference;
   While Value < 0 do Value := Value + Limit;
   While Value >= Limit do Value := Value -Limit;
end;

A: procedure WrapAngle(var Degs: Integer);
begin
  Degs := Degs mod 360;
  if Degs < 0 then
    Inc(Degs, 360);
end;


text:
Q: How to pass authorization token in header for GET method using XMLHttpRequest in react native I am new to react-native. I am trying to pass the authorization token through a header in the GET method. But I am getting an unauthorized error.
I have already tried this code "Using an authorization header with Fetch in React Native" not working for me and also with XMLHttpRequest()
But the API works fine in postman, Java(core) and Android.
Do we have any special implementation in react-native to pass headers?
Could anyone can help me with this?
My code: Changed the server name.
getData() {
    var data = null;

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });

    xhr.open("GET", "https://xyz-test-server.server.com/api/v3/users/details/");
    xhr.setRequestHeader("Authorization", "Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2");
    xhr.setRequestHeader("User-Agent", "PostmanRuntime/7.17.1");
    xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
    xhr.setRequestHeader("Accept", "*/*");
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("Postman-Token", "d8ae56bf-1926-44e4-9e94-23223234,93a110a2-ee8e-42d5-9f7b-45645ddsfg45");
    xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
    xhr.setRequestHeader("Connection", "keep-alive");
    xhr.setRequestHeader("cache-control", "no-cache");

    xhr.send(data);
}

Fetch method:
async _getProtectedQuote() {
  fetch('https://xyz-test-server.server.com/api/v3/users/details/', {
    method: 'GET',
    headers: new Headers({
      'Authorization': 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2',
      'Content-Type': 'application/x-www-form-urlencoded'
    }),
  }).then(responseJson => {
    alert(JSON.stringify(responseJson));
    console.log(responseJson);

  });
}

A: You can try interceptor for pass token into header.
Put all requests in one service file name service.js then import Interceptor from '../interceptor';

make one interceptor.js file and write below code in file.
import axios from 'axios';

axios.interceptors.request.use(async (config) => {

if (config.method !== 'OPTIONS') {

        config.headers.Authorization = 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2';

    }

    return config;

}, function (error) {

// Do something with request error

console.log('how are you error: ', error);

return promise.reject(error);

});

axios.interceptors.response.use(

(response) => {

    return response

},

async (error) => {

    // const originalRequest = error.config

    console.log("error in interceptors=============>", error);

    if (error.response.status === 500) {

        alert(error.response.data.message);

        NavigationService.navigate('Login');

    } else {

        return Promise.reject(error)

        }
    }
)

export default axios;

When api calls header will pass through by interceptor automatically.

A: Fetch Api converts all headers into lower-case. We need to do case-insensitive server side parsing.


text:
Q: From parent component give style to child customized component in styled component TodoListContainer is a styled component, So Inside this container, I would like to give style to the Footer component which I import from other places.
My goal is to access different Footer inside TodoListContainer and give different CSS styles.
It is straightforward to access the regular dom element, I have a hard time accessing customized component.
Thanks for the help!
const TodoListContainer = styled.div`
`

  <TodoListContainer>
            <input
                className=" task-input"
                aria-label="Create a new todo..."
                type="text"
                value={text}
                placeholder="Create a new todo..."
                onChange={handleChange}
                onKeyDown={handleKeyDown}
            />

                {renderedListItems}

                        {todosRemaining} item{suffix} left

                    <button
                        aria-label="Clear Completed"
                        className="clear-all-btn"
                        onClick={handleClearComplete}>
                        Clear Completed
                    </button>

        </TodoListContainer>


text:
Q: Stream zip file in, pipe to unzip, pipe out? I've done quite a bit of googling on this, and have come up short.
I currently have a Lambda function that streams a file from ftp (using promise-ftp) then pipes it to s3 (using s3-streams). This works just fine.
I've come across an issue where the files are zipped, and I would like to unzip them before I upload them to s3. I've had 0 luck getting any of the unzip utilities (which are all really just node-unzip under the hood) to work with local files. I've had even worse luck piping things through to unzip (at the best, I've made it save files recursively inside directories with the same name on my local machine during testing).
The relevant code I've tried is:

stream.pipe(unzip.Extract({path: '/tmp/'}).pipe(toS3Stream)

Which gives me ENOENT. The same thing with unzip.Parse() gives me 'unreadable' errors. I've had unlink permissions errors. I'm at a loss...
I'm willing to save items to the lambda temporarily, but I can't even seem to get that to work.
Edit: Also, to be very clear: these are .zip files, not .gz, so zlib will not work.

A: Apparently following node-unzip's examples with the if/else blocks was my issue. The following works (tested locally and on Lambda with 30+ files):

ftp.connect({ host: ftpHost, user: ftpUser, password: ftpPassword })
                .then(serverMessage => {
                    return ftp.get('/directory/' + fileName);
                })
                .then(stream => {
                    return new Promise((res, rej) => {
                        logger.info('Streaming file from FTP')
                        stream.once('error', rej);
                        stream.once('close', res);
                        stream.pipe(FS.createWriteStream('/tmp/'+fileName));
                    });
                }).then(() => {
                    logger.info('Closing FTP connection')
                    // Unzip the file and pipe it to S3
                    FS.createReadStream('/tmp/'+fileName).pipe(UNZIP.Parse())
                    .on('entry', obj => obj.pipe(toS3Stream))
                    .on('close', () => {
                        resolve('File unzipped and written to S3.')
                    })
                    resolve('FTP closed');
                    return ftp.end();
                })


text:
Q: Interpret the problem as solving k linear systems sequentially I am studying mathematical programming in Matlab,
I just understand questions in the point of view from a mathematician. (My real task is writing code in Matlab)
I have $A^k x=b$ where A is any square matrix, b is a vector and k is a positive number. I am solving this by LU factorization.
My real question to you is
How can I Interpret the problem as solving k linear systems sequentially?
Please help me to do its mathematical demonstration? Thanks a lot

A: Let $x_1$ be the solution to $Ax=b$ and let $x_2$ be the solution to $Ax=x_1$.  Then $A^2x_2=A(Ax_2)=Ax_1=b$, so that $x_2$ is the solution to $Ax=b$.  Get the idea?

A: It is probably not the best idea to perform $k$ systems resolutions, this is a costly operation. In addition, you must do this sequentially, i.e. $k$ times, which is a lot.
Another option is to compute $A^k$ before the resolution, which can be done by successive squarings and products, in $O(\log(k))$ steps, which can be much better than $k$.