text:
Q: Scanning and Displaying WiFi Results I am attempting to scan for all available WiFi networks and determine their signal strength from the device. My code runs however doesn't produce any results.
WifiManager wifiManager;
List<ScanResult> scanResults;

Button button;
TextView textView;
String Display = "";

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

    button = findViewById(R.id.button);
    textView = findViewById(R.id.textView);

    button.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0) {
            wifiManager = WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager.startScan();
            scanResults = wifiManager.getScanResults();
            for(ScanResult sc:scanResults ){
                Display += "BSSID" + sc.BSSID;
            }
            textView.setText(Display);
        }
    });
}

A: Fixed code
MainActivity
public class MainActivity extends AppCompatActivity {

    private WifiManager wifiManager;
    private Button btnSearchWifi;
    List<ScanResult> results;
    List<String> level;
    List<String> bssid;
    List<String> ssid;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSearchWifi = (Button) findViewById(R.id.btnSearchWifi);

        btnSearchWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkLocationPermissions();
                detectWifi();

            }
        });
    }

    private void checkLocationPermissions() {
        Log.d(TAG, "checkBTPermissions: checking permission");
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            Log.d(TAG, "checkBTPermissions: build is less than lollipop");
            int permissionCheck = this.checkSelfPermission("Mainifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Mainifest.permission.ACCESS_COARSE_LOCATION");
            if(permissionCheck != 0){
                Log.d(TAG, "checkBTPermissions: permission check failed");
                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }else{
                Log.d(TAG, "checkBTPermissions: no need to check permission. SDK version < Lollipop.");
            }
        }
    }

    public void detectWifi(){
        this.wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if(this.wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            Log.d(TAG, "Wifi State is enabled");

            IntentFilter filter = new IntentFilter();
            filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

            bssid = new ArrayList<>();
            ssid = new ArrayList<>();
            level = new ArrayList<>();

            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context context, Intent intent) {

                    results = wifiManager.getScanResults();
                    final int N = results.size();

                    Log.v(TAG, "Wi-Fi Scan Results ... Count:" + N);
                    for(int i=0; i < N; ++i) {
                        Log.v(TAG, "  BSSID       =" + results.get(i).BSSID);
                        bssid.add(results.get(i).BSSID);
                        Log.v(TAG, "  SSID        =" + results.get(i).SSID);
                        ssid.add(results.get(i).SSID);
                        Log.v(TAG, "  Level       =" + results.get(i).level);
                        level.add(String.valueOf(results.get(i).level));
                    }
                    SendToLists();
                }
            }, filter);

            // start WiFi Scan
            wifiManager.startScan();

        }else {
            Log.d(TAG, "Wifi State is not enabled");
        }
    }

    public void SendToLists(){
        AdapterElement adapterElements = new AdapterElement(this,ssid,bssid,level);
        ListView netList = (ListView) findViewById(R.id.listView);
        netList.setAdapter(adapterElements);
    }

}

ListView Adapter
public class AdapterElement extends BaseAdapter {
private List<String> one;
private List<String> two;
private List<String> three;

LayoutInflater mInflater;

public AdapterElement(Context context, List<String> SSID, List<String> BSSID, List<String> Level){

    one = SSID;
    two = BSSID;
    three = Level;

    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {
    return one.size();
}

@Override
public Object getItem(int position) {
    return one.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public View getView(int position, View view, ViewGroup parent){

    View v = mInflater.inflate(R.layout.items,null);

    TextView tvSSID = (TextView) v.findViewById(R.id.tvSSID);
    tvSSID.setText(one.get(position));

    TextView tvSecurity = (TextView) v.findViewById(R.id.tvSecurity);
    tvSecurity.setText(two.get(position));

    TextView tvLevel = (TextView) v.findViewById(R.id.tvLevel);
    tvLevel.setText(three.get(position));

    return v;

}

}


text:
Q: kdeinit5 crashes while taking screenshot When i try to take screenshot and save it, kdeinit5 crashes because of segmentation fault.
Here is backtrace:
Application: kdeinit5 (kdeinit5), signal: Segmentation fault

[KCrash Handler]
#4  0x00007f36253eb566 in __memmove_avx_unaligned_erms () from /usr/lib/libc.so.6
#5  0x00007f36262bd492 in ?? () from /usr/lib/qt/plugins/kf5/kio/thumbnail.so
#6  0x00007f36217ee6ef in KIO::SlaveBase::dispatch(int, QByteArray const&) () from /usr/lib/libKF5KIOCore.so.5
#7  0x00007f36217ef016 in KIO::SlaveBase::dispatchLoop() () from /usr/lib/libKF5KIOCore.so.5
#8  0x00007f36262bb026 in kdemain () from /usr/lib/qt/plugins/kf5/kio/thumbnail.so
#9  0x000055aff48775bd in ?? ()
#10 0x000055aff4878a59 in ?? ()
#11 0x000055aff4879237 in ?? ()
#12 0x000055aff4874b54 in ?? ()
#13 0x00007f36252aeb25 in __libc_start_main () from /usr/lib/libc.so.6
#14 0x000055aff48756be in ?? ()
[Inferior 1 (process 1113043) detached]
`

A: I have similar bug. This is reported here and will be fixed in KDE Frameworks version 5.81. For your info the current version is 5.80.0. The version with bug fix will be released on 10 April 2021 according to this source.
Sources: Reddit Post
KDE bug report
KDE release report

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to upload files to SFTP server using Parallel.ForEach loop for better perfomance I have tried Parallel.ForEach, but some files uploaded with zero sizes. Uusing normal for each loop working fine. But it is slow. There are 4 million files. Size of each file is 4 MB.
public static bool UploadFiles(
    string ftpDirectory, string filePath, ConnectionInfo coninfo, string pattern)
{
    using (var client = new SftpClient(coninfo))
    {
        client.Connect();
        client.ConnectionInfo.Timeout = TimeSpan.FromDays(2);
        client.KeepAliveInterval = TimeSpan.FromSeconds(60);
        // 4 millions files
        var files = Directory.GetFiles(filePath, pattern , SearchOption.AllDirectories);
        foreach (var file in files)
        {
            try
            {
                using (Stream inputStream = new FileStream(file, FileMode.Open))
                {
                    client.UploadFile(inputStream, ftpDirectory + Path.GetFileName(file));
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        };
        client.Disconnect();
    }
    return true;
}

A: I have used the WinSCP library for Parallel.ForEach loop. It is working fine.
https://winscp.net/eng/docs/library_example_parallel_transfers
public void UploadFiles(string remotePath, string localPath, string pattern)
{
    try
    {
        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = _sftpConfig["Host"],
            UserName = _sftpConfig["UserName"],
            Password = "",
            SshHostKeyFingerprint = "ssh-rsa 2048 xxx",
            SshPrivateKeyPath = _sftpConfig["SftpPrivateKeyPath"]
        };

        const int batches = 3;

        DateTime started = DateTime.Now;
        int count = 0;
        Int64 bytes = 0;

        Console.WriteLine("Starting files enumeration...");
        IEnumerable<string> files = Directory.GetFiles(localPath, pattern, SearchOption.AllDirectories);

        IEnumerator<string> filesEnumerator = files.GetEnumerator();

        List<Task> tasks = new List<Task>();

        HashSet<string> existingRemotePaths = new HashSet<string>();

        for (int i = 1; i <= batches; i++)
        {
            int no = i;

            Task task = new Task(() =>
            {
                using (Session uploadSession = new Session())
                {
                    while (true)
                    {
                        string localFilePath;
                        lock (filesEnumerator)
                        {
                            if (!filesEnumerator.MoveNext())
                            {
                                break;
                            }

                            localFilePath = filesEnumerator.Current;
                            bytes += new FileInfo(localFilePath).Length;
                            count++;
                        }

                        if (!uploadSession.Opened)
                        {
                            Console.WriteLine("Starting upload {0}...", no);
                            uploadSession.Open(sessionOptions);
                        }

                        string remoteFilePath = Path.Combine(remotePath,Path.GetFileName(localFilePath)) ;

                        Console.WriteLine("Uploading {0} to {1} in {2}...",localFilePath, remoteFilePath, no);

                        uploadSession.PutFiles(
                            localFilePath, RemotePath.EscapeFileMask(remoteFilePath)).
                            Check();
                    }

                    if (uploadSession.Opened)
                    {
                        Console.WriteLine("Upload {0} done", no);
                    }
                    else
                    {
                        Console.WriteLine("Upload {0} had nothing to do", no);
                    }
                }

            });

            tasks.Add(task);
            task.Start();
        }

        Console.WriteLine("Waiting for uploads to complete...");
        Task.WaitAll(tasks.ToArray());

        Console.WriteLine("Done");

        DateTime ended = DateTime.Now;
        Console.WriteLine("Took {0}", (ended - started));
        Console.WriteLine("Uploaded {0} files, totaling {1:N0} bytes", count, bytes);
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: {0}", e);
    }
}


text:
Q: Java - Is string object internally referred string pool? I know the difference of the String instance creation and String literal.
What I know is, when we create new string object i.e
 String str= new String("xyz");

A new object will be created in heap and assigned to local variable str and along with this a string literal will be created in string pool(correct me if I am wrong).
Here what I wanted to know is, does that newly created object in heap, it self holds the value or it internally points to the string pool? or The new object created in heap is holding the value or it just wrapping the value of object which is already there in string pool?

A: At least in the Open JDK and in Oracle's implementation, the String object internally holds a private char[] which contains the actual data (up to jdk1.8 at least). When you say new String("literal") a new object is created which has a char[] field that refers to the same array as the one in the interned string pool.


text:
Q: How can a Haskell Async reliably run a cleanup action after an interrupt? For the sake of discussion, here's a brief example. It spawns an Async with 26 concurrent child Asyncs.
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async, cancel, forConcurrently_)
import Control.Exception (finally)
import Data.Char (toUpper)
import Prelude ((*), (*>), ($))
import System.IO (IO, hPutStr, stderr)

main :: IO ()
main = do
    a <- async $ forConcurrently_ ['a'..'z'] $ \c ->
        (print c *> delay 2) `finally` print (toUpper c)
    delay 1
    cancel a
  where
    delay sec = threadDelay (sec * 1000000)
    print c = hPutStr stderr [c]

Each child

*

*Prints a letter (indicating that the process has begun)

*Pauses

*Using finally, should always end by printing the capital version of that letter (representing the "cleanup" action).

We then pause long enough for all of the Asyncs to start but not long enough for any of them to complete, and then call cancel on the parent, thus throwing an exception to each of the Asyncs.
I expected each finally action to run, producing the output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

but instead I get
abcdefghijklmnopqrstuvwxyzABC

How can I reason about what's going on in this example, and what's the correct way to get the sort of reliable cleanup behavior I'm looking for?

A: What version of async are you using? The behavior of cancel changed in 2.1.1 to wait for the thread to actually exit. In earlier versions it just throws an asynchronous exceptions and exits. In your case, all threads received an exception, but not all had a chance to handle it (print the upper char) because main already exited. Try to add e.g. delay 10 after cancel. If you are using 2.1.1, then it may (or may not) indicate a bug in async.
ADDED: It indeed looks like a bug: https://github.com/simonmar/async/issues/59#issuecomment-289894612


text:
Q: How to debug apk signed for release? I have an apk which I've signed and uploaded to Android Market, and installed on my phone. I would like to debug this release apk (by means of Eclipse) whilst it is running on my phone. I have done this before (and remember it being with one of the Android development tools; perhaps Dalvik Debug Monitor) but unfortunately cannot remember how to do it and have been unable to find any articles online. Does anyone know how this can be done?

Note: I have set android:debuggable="true" in the manifest and have enabled USB Debugging on my phone.

A: Be sure that android:debuggable="true" is set in the application tag of your manifest file, and then:

*

*Plug your phone into your computer and enable USB debugging on the phone

*Open eclipse and a workspace containing the code for your app

*In Eclipse, go to Window->Show View->Devices

*Look at the Devices view which should now be visible, you should see your device listed

*If your device isn't listed, you'll have to track down the ADB drivers for your phone before continuing

*If you want to step through code, set a breakpoint somewhere in your app

*Open the app on your phone

*In the Devices view, expand the entry for your phone if it isn't already expanded, and look for your app's package name.

*Click on the package name, and in the top right of the Devices view you should see a green bug along with a number of other small buttons. Click the green bug.

*You should now be attached/debugging your app.

A: Besides Manuel's way, you can still use the Manifest.
In Android Studio stable, you have to add the following 2 lines to application in the AndroidManifest file:
    android:debuggable="true"
    tools:ignore="HardcodedDebugMode"

The first one will enable debugging of signed APK, and the second one will prevent compile-time error.
After this, you can attach to the process via "Attach debugger to Android process" button.

A:
Add debuggable true in release in buildTypes and turn on 'release' in botton left Build Variants on Android studio
Source: https://mobikul.com/release-variant-of-app-enable-logcat-running-release-build-application/
It work me!
Can you try it

A: I know this is old question, but future references. In Android Studio with Gradle:
buildTypes {
    release {
        debuggable true
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

The line debuggable true was the trick for me.
Before Gradle 1.0 it was runProguard instead of minifyEnabled. Look at here.

A: I tried with the following and it's worked:
release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

A: Add the following to your app build.gradle and select the specified release build variant and run
signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

A: In case of you decided the debug your apk which is already in market but not assigned to be debuggable and you do not want to publish it again. So follow the below steps;

*

*Decompile the Apk with ApkTool(eg. apktool d <APK_PATH>)

*Open the AndroidManifest.xml from decompiled files

*Set android:debuggable="true" in application tag

*Compile the modified source with ApkTool (eg. apktool b <MODIFIED_PATH>)

*Debuggable apk ready(which unsigned means cannot publish store). You can debug as you wish.


text:
Q: IIS6 - associating an application pool with an application using adsutil I'm attempting to do some IIS 6 setup programatically. I've successfully created an app pool:
adsutil create w3svc/apppools/myapppool iisapplicationpool

and created an application:
mkwebdir -c localhost -w 1 -v "myapp","c:\inetpub\myapp"
adsutil appcreateinproc w3svc/1/root/myapp

But what I haven't been able to figure out is how to associate the app pool with the application. My first thought was that it would be an additional parameter to the appcreateinproc command but I haven't had any luck in that regard. So then I started playing around with the set command but haven't had any luck there yet either.
I've found examples of associating app pools to sites but nothing for applications.
Thanks in advance.

A: This should help you in creating an application, application pool and assigning the application to the pool.
http://ayesamson.com/2010/06/14/create-virtual-directory-in-iis-6-0-via-command-line/


text:
Q: JCIFS: file retrieval is too slow to be usable I was just testing JCIFS for accessing Windows shares. It is very slow to the point of being completely unusable.
import jcifs.smb.*;

class First {
    public static void main(String[] args) throws Exception {
    try {
        //jcifs.Config.setProperty( "jcifs.netbios.wins", "192.168.1.220" );
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain.com", "Administrator", "password");

        SmbFile f = new SmbFile("smb://10.17.15.12/Share/xml/file.xml", auth);
        SmbFileInputStream in = new SmbFileInputStream(f);
        byte[] b = new byte[8192];
        int n;
        while(( n = in.read( b )) > 0 ) {
        System.out.write( b, 0, n );
        }
    } catch (SmbException smbe) {
        System.err.println(smbe.getNtStatus());
        System.err.println(smbe.toString());
        System.err.println(smbe.getCause());
    }
    }
}

It takes very long time for initial output to come and subsequent reads are also very slow. Any ideas how to use it? Any alternatives by which I can write Java code to access the Windows shares in a portable way are also welcome

A: What I noticed is that jCIFS does "something" (afair jcifs.smb.SmbTransport.checkStatus(..)) for every chunk it reads - i.e. for each chunk that is read into the buffer. That means using a BufferedInputStream might really speed things up, but the real problem still exists. It only doesn't occur as often as before and therefore has a lower impact on the overall time ..
It helps a lot to set "jcifs.util.loglevel=3" and have a look what's really wrong!
In my case I had to set "jcifs.smb.client.dfs.disabled=false" in the end, as "jcifs.resolveOrder=DNS" didn't help..

A: I found somewhere that SmbFileInputStream doesn't do its own buffering and hence the reason for being slow. Wrapping SmbFileInputStream in a BufferedInputStream solved the problem.
 SmbFile sFile = new SmbFile(path, authentication);

 BufferedInputStream buf = new BufferedInputStream(new SmbFileInputStream(sFile));

A: If you can rely on "something else" to mount the share as a local directory for you, then reading files in the mounted share in Java should be portable.
Even if this is not a real solution, it would be worth trying this to see if you get a faster read rate.  A significantly faster read rate might change your mind about the relative importance of portability.  And if you don't get a significant speedup, then you'll know that JCIFS is not to blame ...

A: Even with the existing suggestions I still found JCIFS too slow to stream videos over my local network. It seems to be do with the overhead per buffer read from the network, even reading into large buffers JCIFS itself had a limited buffer size which was the problem.
If you look in https://jcifs.samba.org/src/patches/ there's a patch, LargeReadWrite.patch. You'll need to apply the patch and rebuild the code to use it, but it made a big difference for me.

A: In my own case, pushing files TO a Windows share via JCIFS was too slow to be usable.
The solution turned out to be defining the property

-Djcifs.resolveOrder=DNS

The default inclusion of BCAST -- broadcasting a NetBIOS name query to 255.255.255.255 -- was needlessly resulting in a lengthy delay. (Link above de-framed from the top-level API docs.)

A: The solution added by @Xolve0 worked for me as well. The buffer issue in the SmbFileInput is also present when trying to write files. I used the same BufferedInputStream(new SmbFileInputStream(sFile)) to make the time execution decrease from 90secs to less than a second for a plain text file.
A quick way to identify this specific issue would be to track the time between the opening of the JCIFS path and the write of the file itself.

A: I know this is an old question, but for anyone else who has tried the other solutions to no avail:
In my case, I was able to track the slowdown to jcifs' heavy use of SecureRandom, which blocks if /dev/random reports insufficient entropy.
Installing rng-tools and configuring and enabling rngd brought performance up to acceptable levels.
You can check the available entropy (on RHEL at least) with the following command:
cat /proc/sys/kernel/random/entropy_avail


text:
Q: Kern Individual Letters With JavaScript (using Generated Content) I have an anchor tag which is generated with Wordpress from the database, and the font the client uses has poor kerning. I need to be able to select individual letters on the anchor link and add a margin-right CSS value to certain letters in the generated text.
How would I go about selecting the 2nd, 3rd, 4th letter etc of the text with Javascript and then add a margin-right value? I really don't know where to start with this?
var anchorTag = document.querySelectorAll(".taxonomy a");

NOTE - I don't have access to the HTML, so cannot wrap the letters in span elements etc. I need to find a way of selecting individual letters with JavaScript if this is possible.

A: You could wrap each character in a span element with a custom class:

function wrapCharacters(element, prefix) {
  element.innerHTML = element.textContent
    .split('')
    .map(function(char, index) {
      return '' + char + '';
    })
    .join('');
}

document.querySelectorAll('.taxonomy a').forEach(function(element) {
  wrapCharacters(element);
});
.taxonomy a .span_3 { margin-right: 1px; }
.taxonomy a .span_4 { margin-right: 3px; }
.taxonomy a .span_5 { margin-right: 3px; }
.taxonomy a .span_6 { margin-right: 7px; }

   SampleText

Now you can access the individual characters with CSS like this:
.taxonomy a .span_0 { margin-right: 1px; }
.taxonomy a .span_1 { margin-right: 4px; }
.taxonomy a .span_2 { margin-right: 2px; }

ES6 Version
const wrapCharacters = (element, prefix) =>
  element.innerHTML = element.textContent
    .split('')
    .map((char, index) => `<span class="${prefix || 'span'}_${index}">${char}</span>`)
    .join('');


text:
Q: The joint of two events is less than the marginal? Consider two events $A,B$. Is it true that
$$
Pr(A,B)\leq Pr(A)
$$
Can you give some explanations and a counterexample, in case the inequality is not verified?

A: $A\cap B \subseteq A$, and thus $P(A,B)=P(A\cap B)\leq P(A)$.


text:
Q: Right way to set microdata for Q&A HTML Say one has a simple question and answer HTML and would like to add microdata, how should one proceed?

My Question

My Answer

I am aware of the schema.org example, but I don't find it very clear. It looks like overkill. I need a simple solution. Can I proceed this way?

My Question

My Answer

I just want to tell what the question is and what the answer is. Is this enough for search engines? Or should I have something more sophisticated like:

My Question

My Answer

Is using itemprop="name" the right way to tell what the question is? What is the difference between itemprop="name" and itemprop="text" in the schema.org example mentioned above?

A: From your first example, Microdata parsers will only learn that there is a Question and an Answer item, without any further content. Microdata doesn't specify that the content of HTML elements with itemscope attributes has to be considered, it only cares about property values.
Testing your example with some online Microdata parsers:

*

*W3C's Microdata to RDF Distiller extracts this RDF (in Turtle):
<> md:item ( [ a schema:Question ] [ a schema:Answer ] );
    rdfa:usesVocabulary schema: .

*The Structured Data Linter has almost the same output.

*Yandex's Structured data validator has similar output.

*Google's Structured Data Testing Tool doesn't extract anything.

name vs. text
For this very question, the name would be "Right way to set microdata for Q&A HTML" and the text would be the question body ("Say one has a simple question …").
If the whole question consists only of such a single, short line, I'd use the text property instead of name (*). name could, principally, also be something like "Question 1", if you want/need it.
But you could also use both properties for a short question, i.e., itemprop="name text", but this is maybe not very elegant (but it can make sense especially if you know that some data consumer makes use of the name property).
* The example for Answer also uses text (and has no name).

You might also want to use Question's suggestedAnswer property and/or Answer's parentItem property to relate these two items.
So for a short question it could look like:

My Question

My Answer


text:
Q: Does it help to replace the battery if phone is slow? Some people I know say that replacing the battery helped their smart phone improve its decreased speed resulting of two years of use.
My initial guess is that this would not have any influence because the speed is mostly about the phone's processor and built-in memory.
But then I got to wonder if I'm mistaken. Maybe if the battery is old, it does not deliver sufficient power and forces the processor, and thus the whole system, to work slower. Or maybe even, that the smart phones switch to "economy mode" (does that even exist in a smart phone?) when it detects that the power delivery is not sufficient.
Any thoughts?
Thanks

A: First of all, a phone would not just run slower like an old cassette tape deck. Either it has sufficient power to run, or it has dropouts - though mobiles switch off before dropouts occur.
My Android Phone can switch to some kind of "economy mode" either manually or automatically when battery charge falls below a given threshold.
This mode includes dimmer display, shorter display-on time and reduced background functionality (i.e. processes running in the background like position tracker, messenger, email, ...)
However, the phone notifies me about this, and I'm not aware of any phone that would switch to "eco mode" silently just because the battery is worn out. Also, many phones even don't know if their battery is worn.
A new battery will help if the time the old one lasts until charging is required has decreased a lot.
The main reason for a slow phone is that the old phone seems slow compared to new phones with faster hardware. Also, apps tend to need more and more resources from version to version, so a current version may run slower than an old one. Plus, all the stuff you installed over time may slow down the phone.

A: The cell phone would have no way of knowing the battery is old. When battery's age they just hold less of a charge. From what I understand as a battery dies they produce slightly less voltage. The battery is effectively "dead" when its output voltage is less then the rated voltage of the smart phone. This shouldn't have any effect on performance. However if the phone is placed in some sort of power saving mode Its possible for the CPU's oscillator frequency to decrease in order to save power which would defiantly effect performance But I think that power saving feature is Mostly just in laptops


text:
Q: How many parts can an atom be split into? I know how a nuclear explosion is made, but can an atom be split further than ionising?

A: Ionising an atom is not the same as "splitting" it. When an atom is ionised, that means that one or more electrons are removed (or added) from the electron shells around the nucleus. When ionised, an atom does not become a different element, not even a different isotope, because the nucleus of the atom does not change. Ionisation only affects the chemical activity of the atom.
When a heavy nucleus like $^{235}U$ (uranium-235)is split (fissions), the nucleus itself breaks up into smaller pieces, such as Krypton and Barium nuclei. This is what releases the energy in an atom bomb. Note that in a hydrogen bomb fission is only used to trigger the fusion of Hydrogen nuclei into Helium nuclei.
Radioactive nuclei also undergo decay, in which the nucleus releases particles like electrons (beta radiation) or helium nuclei (alpha radiation). In this case the nucleus does change and you get a different isotope or element. However, this is not considered fission. With fission the pieces are much larger: alpha particles have a mass of 4 atomic units, Krypton has mass 92 and barium is 141.


text:
Q: add_settings_section() order I made on a custom theme for a client. For this theme I created a settings page so that the client could edit some variables to his liking. This part is working properly.
For this same site, I created a custom post type as a plugin. I need the client to be able to edit some variables for this custom post type as well. So, I would like my plugin to add an other settings section to my settings page. I'm using this code in my plugin:
function dr_issue_settings_init() {

    add_settings_section(
        'dr_issue_section', //$id
        __( 'Issue settings' ), //title
        'dr_issue_section_callback', //callback
        'mytheme_settings' // page
    );

}
add_action( 'admin_init', 'dr_issue_settings_init' );

The problem is; this section appears before the theme settings I created before.
In the global $wp_settings_sections this plugin section is the first value of the array, before the theme section.
How can I make my plugin section be underneath the theme section?

A: You can adjust the priority of dr_issue_settings_init() so that it fires after the default of 10. This should make it appear after the existing settings on the same settings page.
function dr_issue_settings_init() {

    add_settings_section(
        'dr_issue_section', //$id
        __( 'Issue settings' ), //title
        'dr_issue_section_callback', //callback
        'mytheme_settings' // page
    );

}
add_action( 'admin_init', 'dr_issue_settings_init', 100 );


text:
Q: Struggling to change font with GD imagestring been messing with imagestring trying to change font & font size but i really dont have a clue, i'm new to php and have worked on some code that i came across on a forum and have made it work for me just need to find a way to change font and font size but everything i've tried hasn't given me a good outcome.. any solutions? Please bare in mind i'm new to php and if you could explain as much as possible for your answer thank you so much

$im = imagecreatefrompng("image.png");
// if there's an error, stop processing the page:
if(!$im)
{
    die("");
}
// define some colours to use with the image
$black = imagecolorallocate($im, 80, 77, 77);
$font = 'cour.ttf';
// get the width and the height of the image
$width = imagesx($im);

$height = imagesy($im);

$textt = $_GET['textt'];
$dealer = $_GET['dealer'];
$purchase = $_GET['purchase'];
$name = $_GET['name'];
$address = $_GET['address'];
$address1 = $_GET['address1'];

// store the text we're going to write in $textt
putenv('GDFONTPATH=' . realpath('cour.ttf'));

// calculate the left position of the text:
$leftTextPos = ( $width - imagefontwidth($font)*strlen($textt) )/2;
$leftTextPos = ( $width - imagefontwidth($font)*strlen($dealer) )/2;
// finally, write the string:

imagestring($im,$font,$leftTextPos-210,$height-295,$textt,$black);
imagestring($im,$font,$leftTextPos-210,$height-165,$dealer,$black);
imagestring($im,$font,$leftTextPos-200,$height-115,$purchase,$black);
imagestring($im,$font,$leftTextPos-130,$height-70,$name,$black);
imagestring($im,$font,$leftTextPos-100,$height-50,$address,$black);
imagestring($im,$font,$leftTextPos-00,$height-50,$address1,$black);
// output the image
// tell the browser what we're sending it
Header('Content-type: image/png');
// output the image as a png
imagepng($im);
// tidy up
imagedestroy($im);
?>

A: You should try to use imagettftext function.


text:
Q: How to make Rails as_json faster I'm working on a REST server on Rails in which users can have a friendship relationship with other users. To represent this relationship I'm using a join table "friendships", which has an "status" attribute to indicate if the relationship has been accepted, refused, canceled, or is pending.
On my User model I have something like this:
has_many :friendships
has_many :friends, -> { where(friendships: {status: 2})}, through => :friendships
has_many :requests, -> { where(friendships: {status: 1})},
                   :class_name => "Friendship", :foreign_key => "friend_id"
has_many :pending_friends, :through => :requests, :source => :user

and other few more relationships to represent the inverse (when the user is the one that is asking and so). On my Friendship model:
belongs_to :user
belongs_to :friend, :class_name => "User"

Now what I want to do is to have a service in which an user can check all his friendships and friendship requests, and of course some data of the other user so I don't have to do extra requests for that. So what I am doing is this:
friendships = current_user.friendships.where(status: 2).includes(:friend)
              .as_json(include: {friend: {only: [:id, :username, :photo_url]}})

requests = current_user.requests.includes(:user)
           .as_json(include:  {user: {only: [:id, :username, :photo_url]}})

render json: {friendships: friendships, requests: requests}, status: 200

Now I have been testing and when a user has 1000 friendships relationships it can take up to 5 seconds to load this. But if I take away that only: [:id,..] from as_json it will run around 1 sec but it will have all the user's information. And if I completely remove the as_json it will run in 0.4 secs, but I will only have the information of the friendship, and will not include the information of the other user.
For the record I am building the same app on Laravel, I'm supposed to find out which framework/language is the best for our case. And in that Laravel app, since the ORM builds the objects in array structures and lets you decide what data to bring from the join table, it is easier to accomplish this in 0.5 seconds. So telling me that Rails is not so good for what I want to do and switch to Laravel is an acceptable response I guess.

A: we had the same problem and switched to OJ (https://github.com/ohler55/oj).
its faster than the other engine. there are some performance tests on the github page
best


text:
Q: Tool to automatically reformat whole C# source tree in VS2008? I have inherited a large source tree, C#, Visual Studio 2008.
It has many quality issues, one of them is that the code is generally badly formatted.
I am looking for a tool, preferably a plugin for Visual Studio, that will go over the whole solution and apply the same basic formatting that Visual Studio itself applies when, for example, you close a curly brace around a block of code.
Any suggestions?

A: In vs2005, you can do Edit->Advanced->Format Document for a single file, which will (I believe) do what you're asking. I assume vs2008 has a similar function somewhere.

A: ok, so why not try a macro, if you want to do the entire solution, there is a vb example here
http://blogs.msdn.com/kevinpilchbisson/archive/2004/05/17/133371.aspx
it opens each file and applies the same formatting that VS does, but the macro will work across an entire solution (may not be that wise to run it if your solution is huge), beyond reflecting the internals of the format document code in VS and inling it into some sort of stream, this appears to be the easiest way to make use of what i consider to be a very useful feature in visual studio

A: ReSharper should do what you're looking for. Have a look at their Code Cleanup Feature. This can be applied to multiple files including the whole solution.

A: if you have already set your preferences in the vs editor options, you should be able to hit CTRL K, CTRL D which will tidy the code based upon your preferences

A: Here's the simple way (for me)...
I have my Visual Studio set to reformat on "Paste"
Tools | Options | Text Editor | C# | Formatting

**Automatically format on paste** (checked)

When I hit an ugly file, I do CTRL-A, CTRL-X, CTRL-V -- poof, instant format :)
Hope this helps.
Kevin


text:
Q: Adding punctuations inside dictionary values? I have a dictionary as output that has some numerics:
example_dict = dict{'X': OrderedDict, 'Y': OrderedDict}

print(example_dict)

example_dict = {'X': OrderedDict(['Value1', '100000',
                                  'Value2', '10000',
                                  'Value3', '1000'])
                'Y': OrderedDict(['Value4', '2000',
                                  'Value5', '20000',
                                  'Value6', '200000'])}

And I would like Python to print this output with commas automatically assigned to the proper places so that the new output becomes:
example_dict = {'X': OrderedDict(['Value1', '100,000',
                                  'Value2', '10,000',
                                  'Value3', '1000'])
                'Y': OrderedDict(['Value4', '2000',
                                  'Value5', '20,000',
                                  'Value6', '200,000'])}

These values can be random throughout the dictionary and not in the fashion that I described above. In some places hundred thousands are altogether missing while some have only numerals in thousands. That is, I need to define the function such that any value in the dictionary that has 5 digits inserts a ',' between the forth and the third digit and so on.

A: Not sure of kind of OrderedDict you have, but I've made an attempt as per my understanding.
You can add commas with custom function and replace innerdict values as needed.
Hopefully this helps.
Sample Code
from collections import OrderedDict

#Build your dict (sort of)
x = ['Value1', '100000', 'Value2', '10000', 'Value3', '1000']
y = ['Value4', '2000', 'Value5', '20000', 'Value6', '200000']

z = {'X': OrderedDict([x[i:i+2] for i in range(0, len(x),2)]),
     'Y': OrderedDict([y[i:i+2] for i in range(0, len(y),2)]),
     }

#function to set commas, you can expand as needed
def getNum(a):
    if len(a)   == 5: return a[0:2] + ',' + a[2:]
    elif len(a) == 6: return a[0:3] + ',' + a[3:]
    else: return a

#Add commas to inner dict
for k,innerdict in z.iteritems():
    for k2,v2 in innerdict.iteritems():
        innerdict[k2] = getNum(v2)

Result
#`z` before changes
    >>>
    {'Y': OrderedDict([('Value4', '2000'), ('Value5', '20000'), ('Value6',   '200000')]),
    'X': OrderedDict([('Value1', '100000'), ('Value2', '10000'),   ('Value3', '1000')])}

#`z` after changes
    {'Y': OrderedDict([('Value4', '2000'), ('Value5', '20,000'), ('Value6', '200,000')]),
     'X': OrderedDict([('Value1', '100,000'),
 ('Value2', '10,000'), ('Value3', '1000')])}
    >>>


text:
Q: git rebase -i with squash cannot detach HEAD Using the latest git (2.1.0.24), whenever I try to git rebase -i to squash some commits, the squash cannot detach HEAD state. I expect it to squash the commits and put me back on my branch as I expected. There are no unstaged files, changes in my working tree, or anything in the stash. Why is it doing this?
> [master] » git rebase -i HEAD~3

(I squash a few commits)...
pick c9e9b62 Fixes super important bug #123.
squash c0dc9f9 wip
pick 5385a37 wip2

# Rebase fb83e59..5385a37 onto fb83e59

(Then it gives me)
Note: checking out 'c9e9b62'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at c9e9b62... Fixes super-important bug #123.
could not detach HEAD

It appears to rebase successfully, but for some reason won't put me back on the branch.
> [c9e9b62] » git rebase --continue
No rebase in progress?

git graph log BEFORE the rebase attempt:
* 5385a37 (HEAD, master) wip2
* c0dc9f9 wip
* c9e9b62 Fixes super-important bug #123.
* ff80ed9 random commit msg
* 1f407d5 random commit msg
...
* ef106db random commit msg
*   6c244ef Merge branch 'sentences'
|\
| * a641cbf (origin/sentences) random commit msg
| * bfe8eae random commit msg
| ...

git graph log AFTER the rebase attempt:
* c9e9b62 (HEAD) Fixes super-important bug #123.
* ff80ed9 random commit msg
* 1f407d5 random commit msg
...
* ef106db random commit msg
*   6c244ef Merge branch 'sentences'
|\
| * a641cbf (origin/sentences) random commit msg
| * bfe8eae random commit msg
| ...

A: The message could not detach HEAD comes from the interactive rebase script, specifically right here:
GIT_REFLOG_ACTION="$GIT_REFLOG_ACTION: checkout $onto_name"
output git checkout $onto || die_abort "could not detach HEAD"
git update-ref ORIG_HEAD $orig_head
do_rest

The curious part here is that the git checkout $onto step appears to have succeeded: right before the failure, you got:
HEAD is now at c9e9b62... Fixes super-important bug #123.

as output, and that's from the git checkout that happened here.  Then, after apparently succeeding, git checkout apparently exited non-zero as if it had failed.  This invoked die_abort which terminated the rebase attempt.
Now, the documentation claims that a post-checkout hook

cannot affect the outcome of git checkout.

However, in the source, near the bottom of switch_branches, we have:
    ret = post_checkout_hook(old.commit, new->commit, 1);
    free(path_to_free);
    return ret || writeout_error;

where post_checkout_hook runs the post-checkout hook and grabs its exit code.  So there appear to be two ways for git checkout to return a failure status here: either there's an error writing the tree (e.g., the disk has filled up), or you have a post-checkout hook and it is exiting non-zero.  The latter seems more likely.  (And, I tested this and it does in fact cause the checkout to "fail".  Since the source uses ||, any nonzero exit in the hook turns into an exit status of 1 for git checkout itself.)
Do you have a post-checkout hook?  If so, what does it do?
(It's not clear which is wrong here, the documentation or the git checkout command, but at least one is wrong.  I'd say probably the documentation, which should say something more like "cannot affect the files that git checkout will write, but can make the command itself return a failure status".)

A: This can also happen if a file that has been marked assume-unchanged or skip-worktree has also been modified:

*

*You won't see the changes in git status.

*You might be used to  git rebase autostashing all changes for you but it doesn't seem to deal with these ones (as of Git 2.21 and no mention of it changing in subsequent release notes).

You can list such files if you want confirm this but the error message should already alert you to something strange because it will show a filename that doesn't appear in git status.

A: As the previous comments hint to, maybe you have a post-checkout hook that is making a non-zero exit. I had one where the last command could have a different exit based on an if switch:
if false
  command-that-exits-with 0
else
  command-that-exists-with 5
  # hook will exit with 5
end

# EOF

even though my script was still happy if the condition wasn't satisfied. And indeed:
$ .git/hooks/post-checkout
doing stuff!
$ echo $?
5

I added exit 0 at the end of the script, et voilà.

A: Another possible reason is if moving around the commits create some inconsistencies... eg. let's say you have:
HASH2 change line in file b
HASH1 rename file a to b

where of course HASH1 is the oldest. If you try to move HASH2 before HASH1 you will get could not detach HEAD.
Of course it seems obvious here, but in a longer real-life example with multiple commits and squashes being rebased, you might overlook this type of inconsistencies!!


text:
Q: Build body string I am looking to build a body string as described below.
Question:
How can I achieve same result assuming that key value pairs is fetched from a list and key value pairs are 3 or more?
Note:
Some characters are only set once e.g. square brackets, and that the colon is used once per key value pair.
The content and key-value pair are only to describe the structure, the final solution will have other values, e.g epic = sweden, currency = USD, etc.
Current ideas for solving the issue:
Handle the data in 3 steps.
1) Each key and value needs to have escaped quotation.
2) Each key-value-pair should have colon as separator.
3) The complete string should be wrapped with curly brackets.
4) The last key-value-pair should not end with comma.
# Characters for building string.

curly_bracket_left  <- "{"
curly_bracket_right <- "}"
colon               <- ": "
comma               <- ", "

escaped_quotation   <- "\""

# Key-value-pairs data.

key_title_1         <- "epic"
value_title_1       <- "sweden"

key_title_2         <- "currency"
value_title_2       <- "SEK"

# Build string.

string <- paste0(
    curly_bracket_left,

        escaped_quotation,
        key_title_1,
        escaped_quotation,
    colon,

        escaped_quotation,
        value_title_1,
        escaped_quotation,
    comma,

        escaped_quotation,
        key_title_2,
        escaped_quotation,
    colon,

        escaped_quotation,
        value_title_2,
        escaped_quotation

    curly_bracket_right
)

print(string)

Outcome (as expected):
[1] "{\"epic\": \"sweden\", \"currency\": \"SEK\"}"

Wanted outcome when having 3 value-pairs:
[1] "{\"epic\": \"sweden\", \"currency\": \"SEK\", \"resolution\": \"minutes_5\"}"

A: You can use the collapse arguement in paste0 like so:
keys <- state.abb
vals <- state.name

# Characters for building string.

curly_bracket_left  <- "{"
curly_bracket_right <- "}"
colon               <- ": "
comma               <- ", "

escaped_quotation   <- "\""

paste0(
  curly_bracket_left,

  paste0(escaped_quotation,
         keys,
         escaped_quotation,

         colon,

         escaped_quotation,
         vals,
         escaped_quotation,
         collapse = comma
  ),

  curly_bracket_right
)

#output:
# [1] "{\"AL\": \"Alabama\", \"AK\": \"Alaska\", \"AZ\": \"Arizona\", \"AR\": \"Arkansas\", \"CA\": \"California\", \"CO\": \"Colorado\", \"CT\": \"Connecticut\", \"DE\": \"Delaware\", \"FL\": \"Florida\", \"GA\": \"Georgia\", \"HI\": \"Hawaii\", \"ID\": \"Idaho\", \"IL\": \"Illinois\", \"IN\": \"Indiana\", \"IA\": \"Iowa\", \"KS\": \"Kansas\", \"KY\": \"Kentucky\", \"LA\": \"Louisiana\", \"ME\": \"Maine\", \"MD\": \"Maryland\", \"MA\": \"Massachusetts\", \"MI\": \"Michigan\", \"MN\": \"Minnesota\", \"MS\": \"Mississippi\", \"MO\": \"Missouri\", \"MT\": \"Montana\", \"NE\": \"Nebraska\", \"NV\": \"Nevada\", \"NH\": \"New Hampshire\", \"NJ\": \"New Jersey\", \"NM\": \"New Mexico\", \"NY\": \"New York\", \"NC\": \"North Carolina\", \"ND\": \"North Dakota\", \"OH\": \"Ohio\", \"OK\": \"Oklahoma\", \"OR\": \"Oregon\", \"PA\": \"Pennsylvania\", \"RI\": \"Rhode Island\", \"SC\": \"South Carolina\", \"SD\": \"South Dakota\", \"TN\": \"Tennessee\", \"TX\": \"Texas\", \"UT\": \"Utah\", \"VT\": \"Vermont\", \"VA\": \"Virginia\", \"WA\": \"Washington\", \"WV\": \"West Virginia\", \"WI\": \"Wisconsin\", \"WY\": \"Wyoming\"}"


text:
Q: Requiring a file in ROR I have a controller which wish to include a file in another folder, how do I do that? I am using Ruby 1.9.2 and Rails 3.2.6. Thanks
Controller file is in
/project/app/controllers/examples_controller.rb

and the required file is in
/project/example_folder/example.rb

A: require File.join(Rails.root, "example_folder", "example")

assuming /projects/ is your rails application root folder

A: according to here
more info here Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?
requie_relative '../../example_folder/example.rb'

A: You can   auto load custom directories with classes and modules you want to be.
So you can Edit config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/example_folder)

A: It would be something like this:
require "#{Rails.root}/example_folder/example.rb"

just before the declaration of your controller.


text:
Q: Looking to convert String Column to Integer Column in PySpark. What happens to strings that can't be converted? I'm trying to convert a column in a dataframe to IntegerType. Here is an example of the dataframe:

+----+-------+
|From|     To|
+----+-------+
|   1|1664968|
|   2|      3|
|   2| 747213|
|   2|1664968|
|   2|1691047|
|   2|4095634|
+----+-------+

I'm using the following code:

exploded_df = exploded_df.withColumn('From', exploded_df['To'].cast(IntegerType()))

However, I wanted to know what happens to strings that are not digits, for example, what happens if I have a string with several spaces? The reason is that I want to filter the dataframe in order to get the values of the column 'From' that don't have numbers in column 'To'.
Is there a simpler way to filter by this condition without converting the columns to IntegerType?
Thank you!

A: Values which cannot be cast are set to null, and the column will be considered a nullable column of that type. Here's a simple example:
from pyspark import SQLContext
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.types import IntegerType

spark = SparkSession.builder.getOrCreate()

sql_context = SQLContext(spark.sparkContext)

df = sql_context.createDataFrame([("1",),
                                  ("2",),
                                  ("3",),
                                  ("4",),
                                  ("hello world",)], schema=['id'])

print(df.show())

df = df.withColumn("id", F.col("id").astype(IntegerType()))

print(df.show())

Output:
+-----------+
|         id|
+-----------+
|          1|
|          2|
|          3|
|          4|
|hello world|
+-----------+

+----+
|  id|
+----+
|   1|
|   2|
|   3|
|   4|
|null|
+----+

And to verify the schema is correct:
print(df.printSchema())

Output:
None
root
 |-- id: integer (nullable = true)

Hope this helps!

A: We can use regex to check does To column have some alphabets,spaces in the data, Using .rlike funtion in spark to filter out the matching rows.
Example:
df=spark.createDataFrame([("1","1664968"),("2","3"),("2","742a7"),("2"," "),("2","a")],["From","To"])

df.show()
#+----+-------+
#|From|     To|
#+----+-------+
#|   1|1664968|
#|   2|      3|
#|   2|  742a7|
#|   2|       |
#|   2|      a|
#+----+-------+

#get the rows which have space or word in them
df.filter(col("To").rlike('([a-z]|\\s+)')).show(truncate=False)
#+----+-----+
#|From|To   |
#+----+-----+
#|2   |742a7|
#|2   |     |
#|2   |a    |
#+----+-----+

#to get rows which doesn't have any space or word in them.
df.filter(~col("To").rlike('([a-z]|\\s+)')).show(truncate=False)
#+----+-------+
#|From|To     |
#+----+-------+
#|1   |1664968|
#|2   |3      |
#+----+-------+


text:
Q: Flexbox divs resized by image Example page
Firefox/IE10/Opera, upong shrinking the window, maintain the images at the current size, no scaling done at all.
Chrome is the only one that will shrink everything down proportionally as I'd like. I can't tell if Chrome is doing something wrong, or all the other browsers are, or how to go about fixing it.
HTML

CSS
section {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-flow: row nowrap;
  -moz-flex-flow: row nowrap;
  -ms-flex-flow: row nowrap;
  flex-flow: row nowrap;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  justify-content: center;
  -webkit-box-align: end;
  -ms-flex-align: end;
  -webkit-align-items: flex-end;
  -moz-align-items: flex-end;
  align-items: flex-end;
}

.card {
  margin: 0 5px;
  position: relative;
}
.card img {
  box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  display: block;
  max-height: 100%;
  max-width: 100%;
}

A: The flexbox spec has gone through a number of changes over the last few years and various browsers have implemented different versions of the spec.  It's unlikely you'll see much in the way of compatible behaviour at this point.  In particular IE10 and Safari both have mostly working implementations of an old version of the spec.  Firefox has recently implemented support but it is not enabled by default.
In particular note that the original design of flexbox, based off the Mozilla CSS extension for XUL, was for distributing empty space, not re-sizing elements which already had an innate size.  For this reason it may not be possible to achieve what you're aiming for in all browsers.
If you're still interested in using flexbox in a real website check out Modernizr, specifically the tests for flexbox and flexboxlegacy, you will almost certainly end up writing a set of rules for both cases.
Here are some screenshots in browsers I have installed:
Firefox 21:

Firefox 22:

Chrome 28:

Opera 15:

Given that the more recent versions of Firefox and Opera look the same as Chrome I would assume that this is the correct behaviour as per the current status of the spec.  The other browsers are therefore doing it wrong.  As for what you can do about it, I would say not much other than what I've already said above - use an alternative approach based on detected support in older browsers.


text:
Q: Adding two PHP array and echo Json I have below code for controller,
 public function user_ajaxtest()
 {
    $userlistingx = $this->model_usermanage->viewuserlisting();
    $userlistingy = array(
            array('select' => '<input type="checkbox" name="id[]" value="">')
            );

    $userlisting1['data'] = array_merge($userlistingx, $userlistingy);
    echo json_encode($userlisting1);
}

With this AJAX i am sending user list to DataTables.
$userlistx giving me users array and i could able to see everything,
But i would like to add checkbox for each row of datatable,
For that i had created one more array $userlistingy, and then merge this two array,
With this, i am getting one more row instead of column in datatable,
See below ajax response which i am getting normally without merging array means, only echo json $userlistingx.
data: [{test_id: "8", user_id: "28", usernote: "1 image 1 attachment", department_id: "21",…},…]
0: {test_id: "9", user_id: "29", usernote: "1 image 1 attachment"
1: {test_id: "10", user_id: "30", usernote: "1 image 1 attachment"
But when i merget and send Json i get below,
data: [{test_id: "8", user_id: "28", usernote: "1 image 1 attachment", department_id: "21",…},…]
0: {test_id: "9", user_id: "29", usernote: "1 image 1 attachment"
1: {test_id: "10", user_id: "30", usernote: "1 image 1 attachment"
2: {select: "<input type="checkbox" name="id[]" value="">"}
In short question, How do i add select checkbox array to all my datarows?

A: you can try this
 $userlistingx = $this->model_usermanage->viewuserlisting();
 for($i=0;$i<count($userlistingx);$i++)
  {
      $userlistingy[]='<input type="checkbox" name="id[]" value="">';
  }
$userlisting1['data'] = array_merge($userlistingx, $userlistingy);
echo json_encode($userlisting1);

A: There is no need to pass the checkbox in the response. Add them to the table you are using.
Check this out
HTML

            name
            option

Script
$('#example').dataTable( {
    ajax: "yourpage.php",
    columns: [
        { data: "name" },
        {
            data:   "your_data",
            render: function ( data, type, row ) {
                return '<input type="checkbox" name="name_check" value="">';
            },
        }
    ],

} );


text:
Q: persistent local variable in c Are persistent variables not widely used?  I couldn't find much info about them online or in the index of my C textbook - the Art and Science of C.
Anything you can share about them, especially their scope and example declaration would be helpful.   I'm guessing to declare them you use 'persistent' as the keyword?
static void foo( void ) {
  persistent unsigned int width = 5;
}

This is the only other helpful reference I could find:
"Persistent variables keep their state when the board is turned off and on, when main is run, and when system reset occurs. Persistent variables will lose their state when code is downloaded as a result of loading or unloading a file."
http://www.newtonlabs.com/ic/ic_5.html#SEC9
thanks!

A: Interactive C (the link you provided) provides the persistent keyword, but that is not standard C. Particularly since guarantees like "keep their state when the board is turned off and on, when main is run, and when system reset occurs".
persistent is provided with the Interactive C compiler and works with dedicated hardware, Motorola chip in this case, storing the variable value in non-volatile memory to achieve persistence over restarts.

Interactive C is a C compilation environment for many Motorola 6811 based robots and embedded systems. Originally developed for the MIT LEGO Robot Design Contest (6.270), Interactive C has enjoyed widespread distribution and use. Interactive C's claim to fame is its interactivity: users can type in expressions and have them compiled on the fly and run immediately, rather than waiting for lengthy compile and download cycles. IC currently supports the 6.270, the HandyBoard and the RugWarrior and RugWarrior Pro.
  source.

To achieve variable persistence in a local scope (e.g. function), use the static keyword.

A: The keyword you want is static in local (not global) context.
The context thing is important:
#include <stdio.h>

static int foo;

int main(int argc, char **argv){
  //...
}

Here static means that foo has file scope (i.e. is not extern).
Whereas in
char *strtok(char *str, char *sep){
  static char *last;
  //...
}

last is persistent between calls to strtok.
All that said, they are rarely used because they are rarely useful, and are totally unacceptable in a multi-threaded context (where they are a race condition waiting to happen).

A: As jkerian mentioned, persistent variables keep their state when the board is turned off and on ... but are excluded by the C startup code (which is compiler dependent) because the only memory that can be used for this, is the EEPROM.
Like other variables, persistent variables stored in volatile memory lose content on a power lost. But this kind of variable is useful on device with FRAM. FRAM is an acronym for ferroelectric RAM whitch is a non-volatile memory that can hold data even after it is powered off.
Note: on CCS in COFF mode, uninitialized variables weren't set to 0 (to save startup time) and therefore were always persistent.

A: I often use Persistent variables in my PIC MCU software. For instance, I would define an integer array for holding error codes, that I would want to retain after a reset (whether hardware, instruction, watchdog etc.). In addition I would define an integer variable for checking the integrity of all the persistent data. When the program starts I would compare the contents of the check variable with a particular value. This could be any pre-defined value, but I would choose something that the ram is unlikely to power-up with, such as 0xA5F0. If the check variable contains this value, then I can assume all the other persistent variables have retained their data, and move on. However, if the check variable does not compare with 0xA5F0, then I assume all the other persistent variables contain invalid data, so I would initialise them all, and set the check variable to 0xA5F0.


text:
Q: Golang unix sockets: registering same type for RPC on different sockets? I'm working in Go and a bit new to working with unix sockets. Tried searching for a similar question, but couldn't find anything, so apologies if this has been answered before.
I want to use unix sockets to simulate a cluster of machines for testing. I'm testing my implementation of Raft, so I want to register the multiple objects of the same type (a hefty struct) on different unix sockets. But looking at a simple example I wrote, the effect seems to be not what I want: dialing different sockets for the same exported method seems to collapse on a single port:
package main

import (
    "net"
    "fmt"
    "net/rpc"
    "log"
    "sync"
)

type Server struct {
    name string
}

type SpeakArgs struct {
}

type SpeakReply struct {
    Success bool
}

type AddArgs struct {
    A, B int
}

type AddReply struct {
    Answer int
    Success bool
}

func (s *Server) Add(args *AddArgs, reply *AddReply) error {
    reply.Answer = args.A + args.B
    reply.Success = true
    return nil
}

func (s *Server) Speak(args *SpeakArgs, reply *SpeakReply) error {
    fmt.Printf("My name is %v.\n", s.name)
    reply.Success = true
    return nil
}

func main() {
    var wgMain, wgRegister, wgCall sync.WaitGroup
    wgMain.Add(3)
    wgRegister.Add(2)
    wgCall.Add(1)

    go func() {
        server := &Server{name: "RICHARD"}
        rpc.Register(server)
        la, e := net.Listen("unix", "/tmp/example1.sock")
        if e != nil {
            log.Fatal("listen error:", e)
        }
        wgRegister.Done()
        go rpc.Accept(la)
        wgCall.Wait()
        la.Close()
        wgMain.Done()
        fmt.Println("Server exited.")
    }()

    go func() {
        server := &Server{name: "BENNY"}
        rpc.Register(server)
        lb, e := net.Listen("unix", "/tmp/example2.sock")
        if e != nil {
            log.Fatal("listen error:", e)
        }
        wgRegister.Done()
        go rpc.Accept(lb)
        wgCall.Wait()
        lb.Close()
        wgMain.Done()
        fmt.Println("Server exited.")
    }()

    go func() {
        wgRegister.Wait()
        oneclient, err1 := rpc.Dial("unix", "/tmp/example1.sock")
        twoclient, err2 := rpc.Dial("unix", "/tmp/example2.sock")
        if err1 != nil {
            log.Fatal("listen error:", err1)
        }
        if err2 != nil {
            log.Fatal("listen error:", err2)
        }

        addArgs := &AddArgs{1, 2}
        addReply := &AddReply{}
        speakArgs := &SpeakArgs{}
        speakReply := SpeakReply{}
        oneclient.Call("Server.Add", addArgs, addReply)
        oneclient.Call("Server.Speak", speakArgs, speakReply)
        twoclient.Call("Server.Speak", speakArgs, speakReply)

        fmt.Printf("Added numbers! %v + %v = %v.\n", addArgs.A, addArgs.B, addReply.Answer)
        wgCall.Done()
        oneclient.Close()
        twoclient.Close()
        wgMain.Done()
        fmt.Println("Client exited.")
    }()
    wgMain.Wait()
}

I expect this to print both RICHARD and BENNY in console when Speak() is called on the different clients, but instead it prints one of them twice, seemingly randomly. Is there something I'm missing here? Example output, this time RICHARD seemed to come out, but sometimes it is BENNY.
My name is RICHARD.
My name is RICHARD.
Added numbers! 1 + 2 = 3.
Client exited.
Server exited.
Server exited.

Edit: Fix thanks to Pavlo Strokov! rpc.Register defaults to DefaultServer if not specified, so both were getting registered on the same RPC server: correction is to call rpc.NewServer() and register each server on that one.
package main

import (
    "net"
    "fmt"
    "net/rpc"
    "log"
    "sync"
)

type Server struct {
    name string
}

type SpeakArgs struct {
}

type SpeakReply struct {
    Success bool
}

type AddArgs struct {
    A, B int
}

type AddReply struct {
    Answer int
    Success bool
}

func (s *Server) Add(args *AddArgs, reply *AddReply) error {
    reply.Answer = args.A + args.B
    reply.Success = true
    return nil
}

func (s *Server) Speak(args *SpeakArgs, reply *SpeakReply) error {
    fmt.Printf("My name is %v.\n", s.name)
    reply.Success = true
    return nil
}

func main() {
    var wgMain, wgRegister, wgCall sync.WaitGroup
    wgMain.Add(3)
    wgRegister.Add(2)
    wgCall.Add(1)

    go func() {
        rpcServer := rpc.NewServer()
        server := &Server{name: "RICHARD"}
        rpcServer.Register(server)
        la, e := net.Listen("unix", "/tmp/example1.sock")
        if e != nil {
            log.Fatal("listen error:", e)
        }
        wgRegister.Done()
        go rpcServer.Accept(la)
        wgCall.Wait()
        la.Close()
        wgMain.Done()
        fmt.Println("Server exited.")
    }()

    go func() {
        rpcServer := rpc.NewServer()
        server := &Server{name: "BENNY"}
        rpcServer.Register(server)
        lb, e := net.Listen("unix", "/tmp/example2.sock")
        if e != nil {
            log.Fatal("listen error:", e)
        }
        wgRegister.Done()
        go rpcServer.Accept(lb)
        wgCall.Wait()
        lb.Close()
        wgMain.Done()
        fmt.Println("Server exited.")
    }()

    go func() {
        wgRegister.Wait()
        oneclient, err1 := rpc.Dial("unix", "/tmp/example1.sock")
        twoclient, err2 := rpc.Dial("unix", "/tmp/example2.sock")
        if err1 != nil {
            log.Fatal("listen error:", err1)
        }
        if err2 != nil {
            log.Fatal("listen error:", err2)
        }

        addArgs := &AddArgs{1, 2}
        addReply := &AddReply{}
        speakArgs := &SpeakArgs{}
        speakReply := &SpeakReply{}
        oneclient.Call("Server.Add", addArgs, addReply)
        oneclient.Call("Server.Speak", speakArgs, speakReply)
        twoclient.Call("Server.Speak", speakArgs, speakReply)

        fmt.Printf("Added numbers! %v + %v = %v.\n", addArgs.A, addArgs.B, addReply.Answer)
        wgCall.Done()
        oneclient.Close()
        twoclient.Close()
        wgMain.Done()
        fmt.Println("Client exited.")
    }()
    wgMain.Wait()
}

which prints
My name is RICHARD.
My name is BENNY.
Added numbers! 1 + 2 = 3.
Client exited.
Server exited.
Server exited.

A: I think it is because you are using DefaultServer as your RPC server. Instead you should create different servers for each: RICHARD and BENNY.
Please take a look on your code modified by me to work as expected here: RPC calls on one machine


text:
Q: Pinging a number of servers to determine the best one to connect to We are developing a website that will run on 5 different sub-domains throughout Asia.
When a client comes to the site, they can find the best server to connect to in relation to them. So this will need to be done on the client. So I guess javascript is the only option.
I was thinking to have a small image on each server which the client can download via ajax and then we can work out the response times (we do have server access). I know this isn't ideal, but can't really think of anything better.


text:
Q: mysql ETIMEDOUT when connect from Cloud Functions The following code is to issue mysql query with Firebase Cloud Functions.
The code works when running on the local machine. ( $ firebase serve )
But when running on the Google Cloud Platform, the error ETIMEDOUT occur. ( $ firebase deploy )
I want you to tell me the possible causes.
NOTE
- Cloud Functions runtime config is Node.js 8 and my local env is also Node.js 8.0.0
Code:
const mysql = require('mysql')
const pool = mysql.createPool({
  host: '10.20.30.40',
  user: 'user',
  password: 'pass',
  database: 'db',
  connectTimeout : 10000
})

pool.query('SELECT * FROM table', (error, rows, fields) => {
  if (error) {
    console.error(error)
    throw error
  }

  console.log('The solution is: ', rows)

  pool.end()
})

Error:
{ Error: connect ETIMEDOUT
    at PoolConnection.Connection._handleConnectTimeout (/srv/node_modules/mysql/lib/Connection.js:411:13)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at Socket.emit (events.js:208:7)
    at Socket._onTimeout (net.js:420:8)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
    --------------------
    at Protocol._enqueue (/srv/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Protocol.handshake (/srv/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at PoolConnection.connect (/srv/node_modules/mysql/lib/Connection.js:118:18)
    at Pool.getConnection (/srv/node_modules/mysql/lib/Pool.js:48:16)
    at Pool.query (/srv/node_modules/mysql/lib/Pool.js:202:8)
    at Promise (/srv/lib/modules/myCellar.js:32:14)
    at new Promise (<anonymous>)
    at Object.exports.get.uid [as get] (/srv/lib/modules/myCellar.js:31:12)
    at Object.<anonymous> (/srv/lib/index.js:14:36)
    at Generator.next (<anonymous>)
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true }


text:
Q: If statement in MySQL I would like to use an if statement in a MySQL query to SELECT all of the information in a database where... if it returns true, or return the COUNT of the column named aid.
Pseudocode:
IF (COUNT(`AID`) > 0) {
  SELECT * FROM `a_votes` WHERE `aid` = '1'
} ELSE {
  RETURN 'No Rows'
}

Please could you tell me how I could do this?
Edit---
I tried the following query, but I am receiving the error Operand should contain 1 column(s)
SELECT IF( (

SELECT COUNT( aid ) AS  `count`
FROM  `a_votes`
WHERE  `aid` =1 ) =0,  'true', (

    SELECT *
    FROM  `a_votes`
    WHERE  `aid` =1
  )

) AS message

A: SELECT * FROM (
    SELECT COUNT(*) as COUNT FROM a_votes WHERE aid = '1'
) x WHERE COUNT > 0;

If no rows match, a simple COUNT(*)) will returns a single row with 0 for the count. Wrapping the usual COUNT(*) query in an outer query that eliminates that condition will return no rows.
Edited:
Thanks to @bisiclop, this is a better solution:
SELECT COUNT(*) as COUNT
FROM a_votes
WHERE aid = '1'
HAVING COUNT(*) > 0;

A: If I wanted to transcribe your pseudocode to SQL, this would be the result, but I think it is unnecessarily complex, so it is just a demonstration:
/* this query might return zero rows, so beware */
SELECT
  (SELECT COUNT(`aid`) > 0 FROM `a_votes`) AS the_count,
  the_row.*
FROM
  (SELECT * FROM `a_votes` WHERE `aid` = '1') AS the_row

The same using LEFT JOIN, it must return at least one row:
SELECT *
/* count will create exactly 1 row */
FROM      (SELECT COUNT(`aid`) > 0 FROM `a_votes`)    AS the_count
/* this is allowed to return 0,1,...N rows */
LEFT JOIN (SELECT * FROM `a_votes` WHERE `aid` = '1') AS the_row


text:
Q: Which sorting algorithms have a different worst case complexity than their average case? I'v been working on sorting for a while now but I can't figure these two questions apart,  I'm kind of getting mixed up somewhere ... Somebody help
a) Which sorting algorithms have a different worst case complexity than their average case?
b) Which sorting algorithms have a different best case complexity than their average case?

A: The most obvious example would be Quicksort -- its average case is O(N log N), and worst case is O(N2). As its normally written, the best case is O(N log N), but some versions have included a pre-scan to exit early when data was sorted, which gives a best-base of O(N), though I suppose it's open to argument that it's no longer purely a Quicksort at that point.
I don't know whether it does any more, but the implementation of qsort in Microsoft's C standard library used to do that -- mostly to make up for a poor implementation (always used the first element as the pivot) that would otherwise have been O(N2) for sorted data.

A: Here's a complete overview of the complexities.
Some of the most popular ones:

*

*Quick sort: O(n²) in the worst case, O(n lg(n)) on average and in the best case.

*Insertion sort: O(n²) in the worst case & average case, O(n) in the best case.

A: Insertion sort is an example of a sort algorithm with a better best case than average case. Best case is O(n), average case and worst case are O(n²)

A: The crucial thing here is recognizing that the algorithm needs to take shortcuts to avoid having to compare each element to every other element (which would result in a O(N^2) algorithm) but only to some of the other elements and to do it again when sorting those elements.  This is the reason why "divide work in piles and handle each of those piles by dividing it in piles and handle each of those piles etc" ends up with O(N log N) complexity.
The hard part is picking those elements, and to handle working with those elements.  Picking is hard because you must choose well to get the subpiles equally sized.  Managing is hard because you cannot spend too much time moving things around if you want a fast algorithm.
For instance, QuickSort works by choosing an element (traditionally called "pivot") and divide the work in two piles.  One having elements smaller than the pivot, and the other having larger.  Then quicksort each pile, and merge the two sorted piles back.  If the pivot is the smallest element each time, you end up with an empty sub-pile and a big subpile with all the elements but the pivot.  This will result in a worst case of O(N^2).  If you choose well, you get half-sized sub-piles and a running time of O(N log N).
So a typical way to choose the pivot is to look at three randomly chosen values from the pile and choose the one in the middle.  This at least avoids the empty sub-pile.

A: Bubble Sort, O(N) in the best case, O(N ** 2) in the average and worst cases.
To get the O(N) behaviour, set a swapped boolean to false at the beginning of each pass, set it to true whenever you swap two elements. If you have swapped elements, you need to do another pass. This also works as a general termination criterion, as long as comparisons are deterministic, which means you can skip an O(N) counting pass before starting.

A: There are implementations that first check if the array starts or ends with a sequence of elements in ascending or descending order, and takes advantage if many such elements are found. So best case is linear (if the array is mostly sorted in ascending or descending order). What the average case would be can be highly debatable.


text:
Q: Android - App running even without required intent.action EDIT: Actually, it is solved in the comments, I was just curious how it could work but as I see there's nothing special about it. Thanks to Simon
I was looking for the answer quite long but found nothing, every question was about something NOT working, but this one is about how the hell it can work?
I made a little app which uses SDK 8 (Android 2.2) , and it is able to receive sms when it comes immediately and write it to a text file. Interesting thing is, it is working after reboot, which I believe it shouldn't because it does not have this line in manifest

action android:name="android.intent.action.BOOT_COMPLETED"

Why is that?
Main
public class Main extends Activity {

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

public void read()
{
    Cursor c;
    Uri uri = Uri.parse("content://sms");

    c = this.getContentResolver().query(uri,
            new String[] {"address", "date", "body" },
            null, null, null);

    startManagingCursor(c);

    while (c.moveToNext())
    {

        //write to file
        }
        c.close();
         writeToExternalStorage();
}

private void writeToFile(String data) {

}

    private void writeToExternalStorage() {

    }

private String getDate(long time) {

}
 }

Receiver
public class Receiver extends BroadcastReceiver{

@Override
public void onReceive(Context context,  Intent intent) {

    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs=null;
    String str = "";
    if (bundle!=null)
    {
        Object[] pdus = (Object[])bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for(int i = 0;i<msgs.length; i++)
        {
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }
}

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smslogger"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="8" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.smslogger.Main"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".Receiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Programmatically change Dropdown Menu Options in Unity3D i got Unity3D 5.2 and use the Dropdown GUI element for the first time. It is easy to use in the insepctor but i want the Options to show, be dependent of my files in Resources/Shapes/
So the dropdown should show all filenames i got in Resources/Shapes/ but i can not get a hold of this property in the attached C# script.
After reading the manual on Dropdown, there should be a property with the name "Options" and it should have a string and an image variable. (So for my understanding its a two dimensional array-ish type)
Unfortunately i cant use the following script (pseudo code since it doesnt work)
GameObject obj = GameObject.Find("Dropdown");

var info = new DirectoryInfo("Assets/Resources/Shapes");
var fileInfo = info.GetFiles();
foreach (var file in fileInfo)
{
    //Add OptionsString Pseudo-Code
    obj.Options += file; // Options doesnt exist
}

Can anyone explain to me how i can manipulate the Options property on my Dropdown menu pls, i cant find anything in google. Only old ways from before the time Unity had a built in Dropdown menu
Thanks in advance

A: List<string> list = new List<string> { "option1", "option2" };
var dropdown = GetComponent<Dropdown>();
dropdown.options.Clear();
foreach (string option in list)
{
    dropdown.options.Add(new Dropdown.OptionData(option));
}

A: Found the answer:
Dropdown.OptionData list = new Dropdown.OptionData("Name");
obj.GetComponent<Dropdown>().options.Add(list);

A: The answares are correct, but are missing one line of code:
dropdown.RefreshShownValue();

After you add the values and set the selected option, you should refresh whats shown.
The full code for a TextMesh Pro Dropdown would be like:
List<string> list = new List<string> { "option1", "option2" };
dropdown.options.Clear();
foreach (string option in list)
{
    dropdown.options.Add(new TMP_Dropdown.OptionData(option));
}
dropdown.value = 0;
dropdown.RefreshShownValue();


text:
Q: TextView not showing up in other activity I have been able to pass data to other activities except this one. Can anyone see what I'm doing wrong. The only error i'm getting is that my TextView showmsg is NOT showing up in the new activity. Does anyone know why?
 public class MyScanActivity extends Activity
{

private static final String MY_CARDIO_APP_TOKEN = "NOT THE PROBLEM";

final String TAG = getClass().getName();

private Button scanButton;
private TextView resultTextView;
private Button buttonBack;

private TextView showmsg;

private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myscan);

    Intent in = getIntent();
    if (in.getCharSequenceExtra("usr") != null) {
        final TextView setmsg = (TextView)findViewById(R.id.showmsg);
        setmsg.setText(in.getCharSequenceExtra("usr"));
    }

    resultTextView = (TextView)findViewById(R.id.resultTextView);
    scanButton = (Button)findViewById(R.id.scanButton);
    buttonBack = (Button)findViewById(R.id.buttonBack);
    showmsg = (TextView) findViewById(R.id.showmsg);

A: There are not too many options for how your text can be not shown.

*

*You have the view itself messed up:  Check this by putting some sample text in the XML file using android:text="TEST" in the TextView showmsg.  Your text should appear, unless your text is the wrong color or size, or something else happens to be above it.

*You aren't actually finding it with findViewById()  (I hope you've double checked that in a debugger) I agree with alex that you might not want R.id.showmsg.  Did you mean to put R.id.resultTextView there instead?

*Your passed text is not actually coming through.  You should do a log statement, like Log.v(TAG, "Passed text is " + in.getCharSequenceExtra("urs")); and make sure the text is actually coming through.

A: I haven't test it. but i think that is the reason.
change here:
if (in.getCharSequenceExtra("usr") != null) {
    final TextView setmsg = (TextView)findViewById(R.id.showmsg);
    setmsg.setText(in.getCharSequenceExtra("usr"));
}

with this:
showmsg = (TextView) findViewById(R.id.showmsg);
if (in.getCharSequenceExtra("usr") != null) {
    showmsg.setText(in.getCharSequenceExtra("usr"));
}


text:
Q: Angular 2+, rtlcss integration I have a task to add rtl support to the site by using some kind of a library to modify css which will swap left to right and vice versa and append [dir=rlt] [dir=ltr] to all selectors accordingly.
What I have done so far:

*

*called ng eject

*added rtlcss processor as postcss plugin, but it does not fit my requirements. I need it to append [dir=*] to selectors.

*tried other plugins but they did not work.

Possible solutions:

*

*make two css files and dynamically load them. (but then you need to add ViewEncapsulation.None to all components) BAD, not so much work, but can break layout

*make two css files and run as two different applications. One for rtl, one for ltr. BAD, no resources for that

*make rtl by hand. BAD, too much work

*

*forget about rtl processors and make sass mixins. BAD, too much work

*make one css file with correct prefixes generated, [dir=ltr] and [dir=rtl] which will result in a doubly sized css but it will eventually work. GOOD but no idea how to do it

*

*create custom library to do this, or fork existing to modify

*find working processor

Currently, I am trying to find working processor with no luck.
Are there any ideas on how to accomplish this?


text:
Q: PHP replacing break lines but still show new line I have a simple HTML text, each section divided with

.
*e.g. Lorem ipsum

Another lorem ipsum

Third section...*

I am sending this text via JSON to an android app, so it is sending it also with
 tags, because they are needed to show the sections correctly separated in the app.
The problem is, the Google text speech is reading also those  tags.
I want to get rid of them, but still keep the line breaks there.
I manage that text in PHP and I tried:
$txt = preg_replace('
', '\r\n', $mytxt);$final = strip_tags($txt);

But this removes the line breaks completely, so the final text is in one piece and it also replaces ANY br word in the text, even if I asked to replace
, so that is strange.
So how can I keep the line breaks but get rid of html tags?

A: Your regular expression is wrong. Try this:
/**
* Convert BR tags to nl
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl($string)
{
    return preg_replace('/\
/i', "\n", $string);
}

Credits: This code snippet comes from the comments from the php site. https://www.php.net/manual/en/function.nl2br.php

A: Strip tags might help you...
<?php

    $mytxt = '*e.g. Lorem ipsum

    Another lorem ipsum

    Third section...*';

    $final = strip_tags($mytxt);

If you were to echo this in your browser for example, it would appear that there are no new lines, but if you were to view the source of your page you would see that the newlines are infact still intact.
Further information: https://www.php.net/manual/en/function.strip-tags.php