text:
Q: storing multidimensional array in session in codeigniter and retrieving it using foreach This is my code in controller
function index()
{

$data=array();
$data = array('product_id'=>$this->input->post('product_id'),
                'quantity'=>$this->input->post('quantity'),
                'unit'=>$this->input->post('unit'),
                'unit_rate'=>$this->input->post('unit_rate'));

                $this->session->set_userdata('data',$data);
                    $post_array[]=$this->session->userdata('data');

?>

Product  Name
Quantity
Unit
Unit Rate
Action

<?php
$i=0;
foreach($post_array as $cart)
{
    //echo "
"; print_r($cart); echo "
";
    $query = $this->db->query("SELECT product_name FROM phppos_product WHERE
 product_id='".$post_array[$i]['product_id']."'");
    foreach ($query->result() as $row)
{
$product_name=$row->product_name;

}
    echo "
";
    echo "".$product_name."	";
    echo "".$post_array[$i]['quantity']."	";
    echo "".$post_array[$i]['unit']."	";
    echo "".$post_array[$i]['unit_rate']."	";
    echo "	";
    echo "
";
    $i++;
    }
?>

<?php
 }

I am storing $data array i.e single dimensional array in session and trying to append it to two dimensional array i.e. $post_array['cart'][]. And I am trying to retrieve it using foreach loop. It gives me errors like undefined index and illegal offset string etc. So how do I solve this??
I edited my code. This gives me exactly what I want but it's somewhere wrong. I dont know can anyone tell me?
This is my print_r($post_array) output
 Array
(
  [0] => Array
    (
        [product_id] => 2
        [quantity] => 1
        [unit] => 12
        [unit_rate] => 100
    )

)

A: You need your index() function to return your $post_array array to the main script, otherwise it's not visible in the main script's scope; to do so you need first of all to change your index() function definition accordingly, by adding this at the end:
return $post_array();

Then you can call index() into your main script before your foreach statement in order to store its return value into $post_array:
$post_array = index();

A: Its Always better to serialize any data before storing it to session, it can the be put to a session simply as a string. It can easily be accessed and de-serialized whenever needed.


text:
Q: Rails 4, PostgreSQL: convert results of find_by_sql aggregate functions into OpenStruct Working on a report/metrics page and I need to optimize the queries as much as I can so I am using find_by_sql for efficiency.
One of my queries is doing some aggregate functions where I return a count and some sums.  I'm assigning the results of this query into instance variables for a model.
I have working code, but the code scares me.  I have read the official Ruby/Rails docs on the methods used, but I still think there's something wrong with what I'm doing.
def initialize(args)
  @loans_count           = stats.loans_count
  @total_fees_in_cents   = stats.total_fees_in_cents
  @total_amount_in_cents = stats.total_amount_in_cents
end

def stats
  @stats ||= find_stats
end

def find_stats
  if single_year?
    loans = Loan.find_by_sql(["SELECT count(*) as loans_count, sum(amount) as total_amount_in_cents, sum(fee) as total_fees_in_cents FROM loans WHERE account_id = ? AND year = ? LIMIT 1", @account_id, @year]).first
  else
    loans = Loan.find_by_sql(["SELECT count(*) as loans_count, sum(amount) as total_amount_in_cents, sum(fee) as total_fees_in_cents FROM loans WHERE account_id = ? LIMIT 1", @account_id]).first
  end

  # Store results in OpenStruct for ease of access later on
  OpenStruct.new(
    loans_count: loans.loans_count || 0,
    total_fees_in_cents: loans.total_fees_in_cents || 0,
    total_amount_in_cents: loans.total_amount_in_cents || 0
  )
end

Concerns

*

*find_by_sql is supposed to return an array; the SQL will always return a row, even if no matches are found (null values, but a valid row). However, is there a reason I shouldn't call .first on the returned array? I'm afraid of hitting [].first => nil in some case I didn't anticipate.

*Is my method of "caching" the result using the stats method an appropriate method of only querying the DB 1 time? It seems like a lot of code and methods just to get some aggregate data.

A: Dan,
There is two ways to look at this problem...
Method 1
I think I can address both questions with one answer here (^_-), and the key is to address your fear.
You're mainly worried about the whole [].first => nil. Second your worried about DB efficiency. Thirdly, you want to make this clean and re-factored (Good for you!).
Your answer...let PostgreSQL do this work for you, and force it to return a non-nil answer every time.  Get it?

*

*There's no need for the OpenStruct because your labels in your SQL query are the same.

*Use the PostgreSQL function COALESCE() to force the null to be a zero.

*You 'could' make all of this a one-liner, but let's chop it up a bit for ease of the reader.

*This is already a summation query, you don't need the LIMIT 1.

Let's rewrite the code:
def initialize(args)
  @loans_count           = stats.loans_count
  @total_fees_in_cents   = stats.total_fees_in_cents
  @total_amount_in_cents = stats.total_amount_in_cents
end

def stats
  loans = Loan.select("count(*) as loans_count, COALESCE(sum(amount), 0) as total_amount_in_cents, COALESCE(sum(fee), 0) as total_fees_in_cents").where(account_id: @account_id)

  loans = loans.where(year: @year) if single_year?

  loans.first
end

Method 2
I personally think you are overly worried about the DB efficiency thing. You can always look at your development/production logs to read what is actually being outputted to the PSQL server, but I'm pretty sure it's close to the same thing your doing here.
Also, if I remember correctly, the DB query isn't actually executed UNTIL you want the data. During that time, ActiveRecord is just preparing the QUERY string.
.to_i will convert your null to zero.
Let's rewrite the code:
def initialize(args)
  stats = Loan.where(account_id: @account_id)
  stats = stats.where(year: @year) if single_year?
  stats.first

  @loans_count           = stats.count
  @total_fees_in_cents   = stats.sum(:fee).to_i
  @total_amount_in_cents = stats.sum(:amount).to_i
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Maps Issue for ICS devices; Binary XML file line #8: Error inflating class fragment Crashlytics is reporting a common crash that I have not been able to successfully diagnose and correct. It looks like it may be an issue with google Maps, but I am not certain of why. This only occurs on 4.1.2 (69%) and 4.4.2 (31%) devices. I feel that I have to tweak my code to accommodate these versions for google maps.
For all other versions everything works fine. No crashes occur past ICS. I will post the main components of my implementation.
I have a class that extends SupportMapFragment
public class MapFragment extends SupportMapFragment {
    private TouchableWrapper mTouchView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View originalContentView = super.onCreateView(inflater, parent, savedInstanceState);
        mTouchView = new TouchableWrapper(getActivity());
        mTouchView.addView(originalContentView);
        return mTouchView;
    }

    @Override
    public View getView() {
        return mTouchView;
    }

    /**
     * MapOnTouchListener callback
     *
     * @param listener
     */
    public void setMapTouchListener(MapOnTouchListener listener) {
        mTouchView.setMapOnTouchListener(listener);
    }
}

In XML my map is referenced as such
<fragment
    android:id="@+id/map"
    android:name="<package name>.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

I have seen as a suggestion to confirm the addition of specific meta-data in the manifest, I have this already
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="${google_map_key}"/>
<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version"/>

Anyone have further solutions or suggestions?
Crash log:
Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{<package name>.MapActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)
       at android.app.ActivityThread.access$800(ActivityThread.java:139)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5057)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
       at dalvik.system.NativeStart.main(NativeStart.java)
Caused by android.view.InflateException: Binary XML file line #8: Error inflating class fragment
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
       at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
       at android.app.Activity.setContentView(Activity.java:1929)
       at com.ztrip.refresh.activity.MapActivity.onCreate(Unknown Source)
       at android.app.Activity.performCreate(Activity.java:5231)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)
       at android.app.ActivityThread.access$800(ActivityThread.java:139)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5057)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
       at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.NullPointerException
       at maps.dz.o.a(Unknown Source)
       at maps.dg.e.a(Unknown Source)
       at maps.dg.p.a(Unknown Source)
       at maps.ei.ag.a(Unknown Source)
       at maps.ei.bu.a(Unknown Source)
       at maps.ei.n$1.a(Unknown Source)
       at maps.ei.n.a(Unknown Source)
       at com.google.android.gms.maps.internal.i$a.onTransact(:com.google.android.gms.alldynamite:107)
       at android.os.Binder.transact(Binder.java:361)
       at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
       at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
       at com.google.android.gms.a.f.a(Unknown Source)
       at com.google.android.gms.a.b.zza(Unknown Source)
       at com.google.android.gms.a.b.onCreateView(Unknown Source)
       at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
       at com.ztrip.refresh.fragments.MapFragment.onCreateView(Unknown Source)
       at android.support.v4.app.Fragment.performCreateView(Unknown Source)
       at android.support.v4.app.ag.a(Unknown Source)
       at android.support.v4.app.ag.b(Unknown Source)
       at android.support.v4.app.ag.a(Unknown Source)
       at android.support.v4.app.ag.a(Unknown Source)
       at android.support.v4.app.ac.a(Unknown Source)
       at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(Unknown Source)
       at android.support.v4.app.t.onCreateView(Unknown Source)
       at android.support.v4.app.FragmentActivity.onCreateView(Unknown Source)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:839)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
       at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
       at android.app.Activity.setContentView(Activity.java:1929)
       at com.ztrip.refresh.activity.MapActivity.onCreate(Unknown Source)
       at android.app.Activity.performCreate(Activity.java:5231)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)
       at android.app.ActivityThread.access$800(ActivityThread.java:139)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5057)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
       at dalvik.system.NativeStart.main(NativeStart.java)


text:
Q: How do i make a simple word counter in javascript and display it to a  tag function countWords(){
    var sentence = document.getElementById("sentence-input").value;

    var text = sentence.split(" ");

    var lengthofString = text.length;

    document.getElementsByClassName("word-count").innerText = lengthofString;

    console.log(text);
    console.log("length of string " + lengthofString);

}

Here is my current code, I'm able to get the length of the current string but i dont know how to simply display that number in my paragraph element.


text:
Q: Append digit to a prefix string using Regular Expression I need to have a Regular Expression for the below Input and Output
Sample Input:
TEST_ABC
TEST_DEF
TEST_XYZ
Sample Output:
TEST1_ABC
TEST2_DEF
TEST3_XYZ
No Restrictions on sequencing the input parameters.

A: Replace
(?=_)

with
1

(?=_) "matches" the position before the _ using a positive look-ahead. It doesn't match any actual characters.
Replacing with 1, inserts it at the matched position.
See it here at regex101.

A: Regular expressions do not support incrementing numbers, because regular expressions are about patterns not numbers.
However, perl can do something like this:
#!/usr/bin/env perl
use strict;
use warnings;

my $count;

while (<DATA>) {
   s/(?=_)/++$count/e;
   print;
}

__DATA__
TEST_ABC
TEST_DEF
TEST_XYZ

Which inserts an incrementing count before the first underscore in each line.
As a one liner, this'd be;
perl -pe 's/(?=_)/++$c/e'


text:
Q: How to Properly Read Unicode from InputStream? I found others having the same issue and their problems were solved by specifying UTF-8 in the InputStreamReader constructor:
Reading InputStream as UTF-8
https://www.mkyong.com/java/how-to-read-utf-8-encoded-data-from-a-file-java/
This is not working for me and I don't know why. No matter what I try, I keep getting the escaped unicode values (slash-U + hexadecimal) instead of the actual language characters. What am I doing wrong here? Thanks in advance!
// InputStream is is a FileInputStream:
public void load(InputStream is) throws Exception {

    BufferedReader br = null;

    try {
        // Passing "UTF8" or "UTF-8" to this constructor makes no difference for me:
        br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String line = null;
        while ((line = br.readLine()) != null) {
            // The following prints "got line: chinese = \u4f60\u597d" instead of "got line: chinese = 你好"
            System.out.println("got line: " + line);
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }
}

Please note: This is not a font issue. I know this because if I use a ResourceBundle against the same file, I correctly get the Chinese characters printed in the IDE console. But whenever I try to read the file manually using the FileInputStream, something keeps converting the characters into the slash/u convention. Even though I'm telling it to use UTF-8 encoding. I also tried tinkering with the project's encoding JVM parameters, but still no joy. Thanks again for any advice.
Also, using the ResourceBundle as a final solution is not an option for me. There are legitimate reasons for this particular project why it's not quite the right tool for the job, and why I'm trying to do this explicitly myself.
EDIT: I tried pulling the bytes from the InputStream manually, completely bypassing the InputStreamReader and its constructor which seems to be ignoring my encoding parameters. This just results in the same behavior. Slash+U convention instead of correct characters. It's hard to understand why I can't get this to work the same way it works for seemingly everyone else. Do I maybe have a system/OS setting somewhere that's overriding Java's ability to properly handle unicode? I'm using Java version 1.8.0_65 (64-bit) on Windows 7 version 6.1 (also 64-bit).
public void load(InputStream is) throws Exception {
    String line = null;
    try {
        while ((line = readLine(is)) != null) {
            // The following prints "got line: chinese = \u4f60\u597d" instead of "got line: chinese = 你好"
            System.out.println("got line: " + line);
        }
    } finally {
        is.close();
    }
}

private String readLine(InputStream is) throws Exception {
    List<Byte> bytesList = new ArrayList<>();
    while (true) {
        byte b = -1;

        try {
            b = (byte)is.read();
        } catch (EOFException e) {
            return bytesToString(bytesList);
        }
        if (b == -1) {
            return bytesToString(bytesList);
        }
        char ch = (char)b;
        if (ch == '\n') {
            return bytesToString(bytesList);
        }
        bytesList.add(b);
    }
}

private String bytesToString(List<Byte> bytesList) {
    if (bytesList.isEmpty()) {
        return null;
    }
    byte[] bytes = new byte[bytesList.size()];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = bytesList.get(i);
    }
    return new String(bytes, 0, bytes.length);
}

A: In case anyone else out there encounters the same troubles, I was able to find a solution. Since the ResourceBundle was always doing the right thing for me, I dug into why that is and found that java.util.Properties is doing all the magic with a loadConvert() function. After the BufferedReader gives me a line of text from the file, I need to explicitly decode the Unicode escaped characters in that String, kind-of like this:
public void load(InputStream is) throws Exception {

    BufferedReader br = null;

    try {
        // Passing "UTF8" or "UTF-8" to this constructor makes no difference for me:
        br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String line = null;
        while ((line = br.readLine()) != null) {
            // The following prints "got line: chinese = \u4f60\u597d" instead of "got line: chinese = 你好"
            System.out.println("got line: " + line);
            line = decodeUni(line);
            // The following prints "decoded line: chinese = 你好" exactly as it should!
            System.out.println("decoded line: " + line);
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }
}

// Converts encoded "\\uxxxx" to unicode chars
private String decodeUni(String string) {

    char[] charsIn = string.toCharArray();
    int len = charsIn.length;
    char[] charsOut = new char[len];
    char ch;
    int outLen = 0;
    int off = 0;
    int end = off + len;

    while (off < end) {
        ch = charsIn[off++];
        // Does aChar start with "\\u" ?
        if (ch == '\\') {
            ch = charsIn[off++];
            if(ch == 'u') {
                // Yep! Convert the hex part to the correct character.
                int value = 0;
                for (int i = 0; i < 4; i++) {
                    ch = charsIn[off++];
                    switch (ch) {
                        case '0': case '1': case '2': case '3': case '4':
                        case '5': case '6': case '7': case '8': case '9': {
                            value = (value << 4) + ch - '0';
                            break;
                        }
                        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': {
                            value = (value << 4) + 10 + ch - 'a';
                            break;
                        }
                        case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': {
                            value = (value << 4) + 10 + ch - 'A';
                            break;
                        }
                        default: throw new IllegalArgumentException("Malformed \\uxxxx encoding: " + string);
                    }
                }
                charsOut[outLen++] = (char)value;
            } else {
                // Starts with a slash but not "\\u", handle the other possible escaped characters.
                switch (ch) {
                    case 't':
                        ch = '\t';
                        break;
                    case 'r':
                        ch = '\r';
                        break;
                    case 'n':
                        ch = '\n';
                        break;
                    case 'f':
                        ch = '\f';
                        break;
                    default:
                        break;
                }
                charsOut[outLen++] = ch;
            }
        } else {
            // Doesn't start with a slash, leave as-is.
            charsOut[outLen++] = ch;
        }
    }
    return new String(charsOut, 0, outLen).trim();
}


text:
Q: Adaptive Performance Installation Error (Unity 2D) When trying to build my Unity 2D project, I keep encountering this error:

"No Adaptive Performance provider package installed. Adaptive Performance requires a provider to get information during runtime. Please install a provider such as Adaptive Performance Samsung (Android) from the Adaptive Performance Settings."

I have checked under project settings and package manager and Adaptive Performance 3.0.2 is installed, so I don't know why I keep encountering this error.
I have already tried uninstalling it and reinstalling it.
Any advice would be appreciated.

A: In "Untity 2021.3.4f1 Personal":

Current setup:

This worked for me:

That is, remove it. Note! I am working with WebGL as target platform but got this error regardless target type.
(And yes, there are surely some drawbacks with this solution BUT just to get rid of the problem can make anyone a little bit happier...)
Best of luck!


text:
Q: decrypt C# encrypted string in PHP I'm trying to decrypt a string in PHP.
I use this code for encrypting the string in C#:
    public string EncryptMessage(string text, string key)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(text);
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Padding = PaddingMode.Zeros;
        aes.Mode = CipherMode.CBC;

        aes.Key = Encoding.Default.GetBytes(key);
        aes.GenerateIV();

        string IV = ("specialstring" + Encoding.Default.GetString(aes.IV));

        ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        byte[] buffer = plainTextBytes;

        return
    Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV));

    }

I also use this code for decrypting the string in PHP:
function decrypt($text, $pkey)
{
    $key = $pkey;
    $text = base64_decode($text);
    $IV = substr($text, strrpos($text, "specialstring") );
    $text = str_replace("specialstring".$IV, "", $text);
    $res = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $IV), "\0");
    return $res;
}

The PHP code always return empty string. Whats wrong in my code and how can I fix it?


text:
Q: Using complete option for jquery animate I have a gif image in my html. I want to make the image "walk" so I'm using jquery .animate() the walking is fine, now, once it reaches the other side of the screen, I'd like to hide the image so I'm trying to use the complete option. My code looks like so:
$(document).ready(function() {
for(var i = 0; i < 500; i = i + 20) {
         $("#animate-gif").animate({backgroundPositionX: i}, 50,
             function() { alert("finished"); }); }
});

However, the alert does not show. I've also tried doing the following:
duration : 50, complete : function()

{backgroundPositionX: i}, {duration : 50, complete :function()

But neither worked and I'm getting a warning in my debugger "Unexpected token :". So my question is, how exactly do you add a complete option for the animate function in jquery? I've tried looking through the documentation and some examples and what i've tried are pretty much what I've seen.

A: I don't understand the purpose of the for loop. Try just calling animate() once:
http://jsfiddle.net/W5SjR/1/
$(document).ready(function() {
    $("#animate-gif").animate({backgroundPositionX: "100%"}, 500, function() { alert("finished"); });
});

Your complete function looks fine. Is it possible that you checked "don't allow this page to show popups"?
I would also suggest using console.log() instead of alert().

A: the general syntax of .animate is
$("selector").animate({"param":"value","param","value"},time,callback_function);

The callback function will be called after the completion of the animation
there are also other options like "step", "complete" and much more
You can check this fiddle where i would used some of them


text:
Q: Fancybox 2 global event error when launching without an element I'm launching fancybox dynamically. I have been using this method with jquery less than 1.9.0 for a while with no problems.
However, now in JQuery 1.9.0 global events are not supported. It seems like fancybox tries to broadcast a global event when launched dynamically (not attached to a dom element like a button).
This fiddle will show you the jquery migrate error in your console.
http://jsfiddle.net/gMeFT/2/
$.fancybox({
    openEffect: 'none',
    closeEffect: 'none',
    autoScale: true,
    href: 'http://jsfiddle.net/echo/jsonp/',
    type: 'ajax'
});

Does anyone know of a way around this?

A: I had the same issue. I think I've found the solution, but unfortunately you need to hack one line in the source code.
Line 764 contains something like:
$.event.trigger(event + '.fb');

Changing it to following should do the job:
D.trigger(event + '.fb');


text:
Q: AWS Cognito User Management For the last few years, I've built a PHP and MySQL based website where users can submit reprographics and IT requests. I'm hoping to make this cloud-based rather than running it from a local webserver. My initial idea was to have an EC2 instance running as a web server for each company which uses my system, but as the system is PHP session based I'm assuming the security would not be great so I think I need to move towards more of an AWS system using Cognito for user management and the API Gateway with Lambda to do the job of getting the data from the databases. My question is, my current system has an admin console where the admin user can access the lists of users, and assign them permissions (session variables) which allows them access to specific pages. How would I make a webpage where users can manage the users in a Cognito user pool without giving them access to the AWS console.

A: Implement a Cognito AdminAddUserToGroup operation in your Lambda function for admin users to manage what Cognito Groups your users belong to. Your admins will be the only ones that are able to invoke the API call to the Lambda function because they'll be included in the Cognito Admin Group with appropriate permissions to invoke the Lambda function that you specified as the developer.
Specify permissions of what each Congito Group has access to by assigning roles for each Cognito Group.
You can also decode the jwt on the backend to determine what Cognito Group the user belongs to that made the request and use Amplify on the FrontEnd to manage the FrontEnd's display of content based on the Group (links, etc). More info about that can be found in this thread: How do I access the group for a Cognito User account?
I do not have enough points to comment on the CLI update-user-pool suggestion, but wanted you to know that wouldn't work because 1.) It would impact the entire user pool and affect ALL users in the user pool and 2.) It would make no difference in regards to what your users were able to have permission to access in your application.


text:
Q: How to change a value rank in a column MS SQL I've a table with a column which is defining a rank value for display position:
Unid | Rank | Name
10   |  1   | A
20   |  2   | B
30   |  3   | C
40   |  4   | D
50   |  5   | E

How to update the table for have Name E on the top of the list and followed by the A, B , C , D names ?

A: One possible solution is to use ROW_NUMBER() with appropriate ORDER BY clause:
Table:
CREATE TABLE Data (
   [Unid] int,
   [Rank] int,
   [Name] varchar(1)
)
INSERT INTO Data ([Unid], [Rank], [Name])
VALUES
   (10, 1, 'A'),
   (20, 2, 'B'),
   (30, 3, 'C'),
   (40, 4, 'D'),
   (50, 5, 'E')

Statement:
UPDATE d
SET d.[Rank] = d.[NewRank]
FROM (
   SELECT
      [Rank],
      ROW_NUMBER() OVER (ORDER BY CASE WHEN [Name] = 'E' THEN 0 ELSE 1 END, [Name]) AS [NewRank]
   FROM Data
) d

Result:
Unid Rank Name
10   2    A
20   3    B
30   4    C
40   5    D
50   1    E


text:
Q: RethinkDB changefeed filtering using `now()` I was hoping to create a sort of 'time tigger' using RethinkDB changefeeds:
        return r.
            Table("Checks").
            Filter(r.Row.Field("ScheduledFor").Le(r.Now())).
            Changes(r.ChangesOpts{
                    IncludeInitial: true,
            }).Run(db)

However, while it picks up things that initially fulfill the Filter predicate, it does not appear to pick up records where ScheduledFor goes from being in the future to being in the past.
i.e. r.Now() appears to be evaluated upon being received by the server and never again.
Is there any way to make the Now() term dynamically evaluated? Or should I just do a table scan?

A: Currently r.now always evaluates to the time the server received the query.  It's probably best to repeatedly do a table scan for any documents scheduled between the last table scan and the current time.


text:
Q: How come Verbose=True does not show any output with VotingClassifier? It's in the documentation that verbose=True will output time elapsed, but it is not doing so for me:
from sklearn.ensemble import VotingClassifier

voting_c_all = VotingClassifier(
    estimators=[
        ('random_forest', gs_forest2),
        ('grid_search', gs),
    ],
    voting='soft',
    verbose=True,
    n_jobs=-1
)

voting_c_all.fit(X_res, y_res)

A: Using the example from the manual:
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
clf1 = LogisticRegression(multi_class='multinomial', random_state=1)
clf2 = RandomForestClassifier(n_estimators=50, random_state=1)

X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
y = np.array([1, 1, 1, 2, 2, 2])
eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2)], voting='soft',verbose=True)
eclf1 = eclf1.fit(X, y)

[Voting] ....................... (1 of 2) Processing lr, total=   0.0s
[Voting] ....................... (2 of 2) Processing rf, total=   0.1s

But once you set n_jobs to be more than 1, the job should be sent to other cores and you don't see the print, hence doesn't keep track of the time:
eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2)], voting='soft',verbose=True,n_jobs=2)
eclf1 = eclf1.fit(X, y)


text:
Q: What does `import type {Node} from 'react';` and usage in App: () => Node Running this command:
npx react-native init AwesomeProject

In the App.js file I don't understand 2 lines:
import React from 'react';
import type {Node} from 'react';  // 1
import {
  SafeAreaView,
  ScrollView,
 // ..... Code ....

const App: () => Node = () => {  // 2
   // ..... Code ....

export default App;

*

*Importing type Node
Following Is there a point to doing 'import type' rather than 'import' with Flow?, I understand that such import is used to import a type of object, for instance:
import type { Array, Object, ... } from 'wherever';

To be honest I am more concerned on the next point (probably If I understand that I would automatically get the this as well).

*const App: () => Node = () =>
All that I see is that App is a variable which references a function that returns an Object of type Node which this Object s also a function. Does it wrap the App into a 'React' instance or something?

A:
What does const App: () => Node = () => do and why you would want to use it?

If we remove the types, the code is:
const App = () => {
  // ... code
}

This is a react functional component.
Then on top of that is added a type: () => Node. This means it's a function that takes no parameters and returns a react Node. Types help with development by letting the computer analyze the code better, and point out bugs sooner (before even running the code)


text:
Q: Number of elements of each order in a cyclic group
Theorem:
If d is a positive divisor of n, the number of elements of order d in a cyclic group of order n is $\phi \left ( d \right )$ where $\phi$ is the euler-phi function defined as the number of elements less than d and relatively prime to d. This by definition is $gcd\left (  d,n\right ) \equiv \phi\left ( d \right )$

The author provides the proof as follows.
Proof:
By the Fundamental theorem of cyclic group, there exists exactly one subgroup of order d-say, $\left \langle a \right \rangle$.
Then, every element of order d also generates the subgroup $\left \langle a \right \rangle$
The proof continues.
There is an underlying subtlety with the bold. I am unsure if my understanding of the bold is correct.
Note: $\left | a \right |=\left | \left \langle a \right \rangle \right |=d$.
This implies $a=\left \langle a \right \rangle$. Thus, a has order d and any element of order d generates $\left \langle a \right \rangle$

A: If $C$ is the unique subgroup of order $d$ and $g$ is any element of order $d$, then $|\langle g\rangle|=|C|$ implies $\langle g\rangle=C$ implies $g\in C$. If this is what you mean, then yes.


text:
Q: Is a graph 1 particle irreducible if the split would change the number of external legs? Is a graph 1 particle irreducible if the split would change the number of external legs? For example;
http://www.stevepur.com/physics/matter/matter40.gif
(sorry, image upload is giving errors)
The graph could be split by cutting one propagator, but the resulting graph would have a different number of external legs. Is it 1PR or not?


text:
Q: are these two fractions a record for m, n<559? $\dfrac 1{344}$ has a recurring decimal period which is $906976744186046511627$.
$\dfrac 1{559}$ has a recurring decimal period which is $178890876565295169946332737030411449016100$
I note that $$\gcd(178890876565295169946332737030411449016100,  906976744186046511627)=\\
  23255813953488372093,$$ which is a big number.
Does other two fractions $\frac{1}{m}$ and $\frac{1}{n}$ for $n$, $m$ integers $m\neq n$ <559 exist such the gcd of their recurring decimal period is greater than $23255813953488372093$?


text:
Q: MATLAB: Generate same Random Number sequence I want to use the mersenne twister to generate 'N' random numbers between 10 to 50. I want to be able to generate the same sequence over and over again.
I wrote the following code: (seed = 50, a = 10, b = 50, N = number of required random numbers)
s = rng(seed, 'twister');
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

Now even I print
r1 - r

I don't get zero. I expect to get zero as I have reset the random number generator to it's initial state in the third line of my code.
My question is where am I going wrong?

A: From the rng documentation:

sprev = rng(...) returns the previous settings of the random number generator used by rand, randi, and randn before changing the settings.

So your s is the previous state, not the set state.  Changing things to
rng(seed, 'twister');
s=rng();
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

should produce the desired behavior.
This may seem cumbersome, but it arises since rng is meant to be treated like a toggle: you set your state while storing the previous one for future restoration.  After all, immediately resetting the state appears to be more diagnostic than practical.


text:
Q: Per App setting for 'Use font smoothing when available'?
Historically this setting (System Preferences -> General) controls
  subpixel font anti-aliasing.
Since Mojave deprecates subpixel rendering, it controls how much
  greyscale anti-aliasing is applied. That is, the text looks more bold
  when this is checked.

Is it possible to tweak this setting per app (defaults write stuff), especially for the menu bar?


text:
Q: GET with request params or POST I have a GET endpoint to get a set of resources and a custom request param 'filter' to filter the said resources.  This param is a stringified array of filters.  Due to the length limitation in request param, I couldn't provide large filters.  So, I had to opt for POST with filters in body.  But, as POST requests are not idempotent, it seems highly deviating from API standards. I have searched a few sites and couldn't come up with a solution.  Please assist.

A: If you're concerned about hitting the length limitation, then you have to use POST. Yes, that means you lose idempotence and safety, which is unfortunate, but there aren't other good choices.


text:
Q: Error installing python-snappy: snappy-c.h: No such file or directory I am using amazon ec2 ubuntu 11.04 server
 sudo pip install python-snappy

also I tried to downloaded package and entered "sudo python setup.py install"
I got the error:
  running build
  running build_ext
  building 'snappy' extension
  gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c snappymodule.cc -o build/temp.linux-x86_64-2.7/snappymodule.o
  cc1plus: warning: command line option '-Wstrict-prototypes' is valid for Ada/C/ObjC but not for C++ [enabled by default]
  snappymodule.cc:31:22: fatal error: snappy-c.h: No such file or directory
  compilation terminated.
  error: command 'gcc' failed with exit status 1

How i could get rid of this error?
source: https://github.com/andrix/python-snappy

A: According to the repo
How to install it on Mac OS X?
It has been reported a few times (Issue #7 and #23) that it can't be installed correctly the library in Mac.
The procedure should be,
$ brew install snappy # snappy library from Google
$ CPPFLAGS="-I/usr/local/include -L/usr/local/lib" pip install python-snappy

A: *

*You download snappy lib at here: https://code.google.com/p/snappy/

*Extract it

*Install by command lines follows:
$: ./configure
$: make
$: make install

*Install python-snappy:
$: pip install python-snappy

A: I had some trouble getting snappy to install. Finally downloaded the pre-build stuff as offered by https://www.lfd.uci.edu/~gohlke/pythonlibs/ and all went well.
(Unofficial Windows Binaries for Python Extension Packages)

A: for Oracle Linux with Python 3.X:
you need to enable optional_latest repository as a first step,

*

*use for enabling the following repo
$ yum-config-manager --enable ol7_optional_latest
"ol7_optional_latest" repo will be enabled for yum lookup.

*then install packages using,
$ yum -y install gcc gcc-c++ snappy snappy-devel

*then with pip install the python-snappy package,
$ pip3 install python-snappy

A: You need Snappy C library
Then you have to install python-snappy wrapper.
It seems you didn't install Snappy-C library
Try it ..as already a fellow commented for your post

UPDATE: See more highly upvoted post below, which includes instructions to install on DEB-based, RPM-based, and Mac OS (Brew).

A: had lots of issues installing on El Capitan, with an error saying that the snappy-c.h file was not found.
Had to install snappy from tar.gz file
https://github.com/google/snappy/releases/download/1.1.3/snappy-1.1.3.tar.gz
untar and run
./configure
make
make install

it will put the header file in
/usr/local/include
then needed to set FLAGS for the cc compiler to find the header file:
export DYLD_LIBRARY_PATH=/usr/local/include
export CPPFLAGS="-I/usr/local/include/snappy-c.h"
export CFLAGS="-I/usr/local/include/snappy-c.h"
export CXXFLAGS="-I/usr/local/include/snappy-c.h"
export LDFLAGS="-L/usr/local/lib"

and then I installed python-snappy from the egg file
https://pypi.python.org/packages/b1/fe/1d632cdac5dbb5ce84db778af7f733eb469130d8cf4c02f6cd9057a96768/snappy-2.4.1-py2.7-macosx-10.5-intel.egg#md5=b76558c71f1d97feeb8402c345e466bf
you can try with pip install python-snappy
but it originally failed to find the header file, so i went for the egg file
to install the egg:
easy_install <eggfile>
python setup.py build
python setup.py install

A: You need to check the output for
rpm -q snappy-devel

If it is not present, then install it using this command:
yum install snappy-devel

A: If you are on Mac OS X Catalina, you can install with
brew install snappy
CPPFLAGS="-I/usr/local/include -L/usr/local/lib -stdlib=libc++ " pip install python-snappy

as suggested by https://github.com/andrix/python-snappy FAQ

A: Fix for macOS M1. You have to define absolute path to lib and include for snappy.
brew install snappy
pip install \
  --upgrade --ignore-installed \
  python-snappy==0.5.4 \
  --global-option=build_ext \
  --global-option="-I/opt/homebrew/Cellar/snappy/1.1.9/include" \
  --global-option="-L/opt/homebrew/Cellar/snappy/1.1.9/lib"

A: You can install Snappy C library with following commands:
DEB-based: sudo apt-get install libsnappy-dev
RPM-based: sudo yum install csnappy-devel
Alpine (Docker) apk add --no-cache snappy-dev g++
MacOS: See Riley's answer below.

A: This fixed my issue:
yum install gcc-c++

A: I was having troubles with this for a while. FYI I'm trying to install Crossbar (https://crossbar.io/docs/Installation-on-Linux/)
I did a bunch of googling and messed around quite a bit. I'm using Python 3.7.4 and what I think solved my problem is this :
sudo yum install python-devel
if that doesn't work try
sudo yum install python3-devel
source:
https://github.com/giampaolo/psutil/issues/1143#issuecomment-475354786
https://github.com/giampaolo/psutil/issues/1143

A: To solve this issue in Mac OS X with MacPorts installed, you can do:
$ sudo port install snappy
$ CPPFLAGS="-I/opt/local/include -L/opt/local/lib" pip install python-snappy

A: For Windows

*

*Download from here

*Extract the Zip.

*Copy the .h files from include folder. Paste in to the python installation folder
C:\Users\user\AppData\Local\Programs\Python\Python310\include\

*Copy snappy64.lib from native folder. Paste in to python installation folder
C:\Users\user\AppData\Local\Programs\Python\Python310\libs\

*Rename snappy64.lib to snappy.lib

*you are good to go. Re-try command pip install -r .\requirements.txt


text:
Q: Creating a Circular Reference Based On Table I have a database with separate tables for national tax rates and county tax rates and I'd like to create objects to represent these that look something like...
create type county as object
(
  my_nation nation,
  local_taxRate number
);

create type counties as table of county;

create type nation as object
(
  national_taxRate number
  my_counties counties
);

This is impossible though since it creates a circular definition. Is there someway to handle this problem?

A: According to the documentation:
http://docs.oracle.com/cd/E11882_01/appdev.112/e11822/adobjmng.htm#ADOBJ7651

Types that depend on each other for their definitions, either directly
  or through intermediate types, are called mutually dependent. For
  example, you might want to define object types employee and department
  in such a way that one attribute of employee is the department the
  employee belongs to and one attribute of department is the employee
  who manages the department.
If you visualize a diagram with arrows showing the relationships among
  a set of mutually dependent types, the connections form a loop. To
  define such a circular dependency, you must use REFs for at least one
  segment of the circle.

You need to use REF somewhere in the definition, for example:
create type nation /* empty type placeholder */
/

create type county as object
(
  my_nation REF nation,
  local_taxRate number
);
/

create type counties as table of county
/

/* redefinition of "empty" nation */
create type nation as object
(
  national_taxRate number,
  my_counties counties
)
/


text:
Q: Roku: How to change Poster-Grid Captions Font size Bright script using scene graph. i want to change size of default font without Font node. I used "SmallestBoldSystemFont" font. It appears large font then actual require size.
  <PosterGrid
  id = "example"
  basePosterSize="[150,150]"
  itemSpacing="[27,27]"
  caption1NumLines="2"
  caption1Font = "font:SmallestBoldSystemFont"
  numColumns="10"
  numRows="1" />

A: As you can see in docs caption1Font field accept Font object, so you have to create an object and just set the role for that font:
    <PosterGrid
        id = "example"
        basePosterSize="[150,150]"
        itemSpacing="[27,27]"
        caption1NumLines="2"
        numColumns="10"
        numRows="1">

    </PosterGrid>

A: Using Font Node. you can change any component Font Like Below.
First Scenario :
Here you can download ttf file from google and add it in your application. Here change Size in Pixel Wise.

Second Scenario:
You Can Change Font write inside a Component Like below. Here Different Size Provide By Roku documentation.


text:
Q: Laravel Entrust - add support for guest role I am using Entrust middleware from here. Everything goes fine except when I want to expose a certain page to admin when logged in  and to any user who is NOT logged in .
With the help from here , I added the following middleware, but when I hit the url , it says, too many redirections.
namespace App\Http\Middleware;

use App\Models\User;
use App\Models\Role;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Collection;

class CheckPermission {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct( Guard $auth )
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( $request, Closure $next )
    {
        if ( $this->auth->guest() )
        {
            $user = new User;
            $user->id = 0;
            $user->username = 'Guest';

            $role = Role::find(9);// EXPLANATION OF 9 IS GIVEN BELOW UNDER CODE

            $user->roles = new Collection;
            $user->roles->add( $role );
        }
        else
        {
            $user = $this->auth->user();
        }

        // Automatically check permission based on route name
        /*
          if ( !$user->can( $request->route()->getName() ) )
         {
            // Handle denied permission, e.g. abort(401)
         }
        */

        return $next( $request );
    }

}

Database change : in roles table I added a row with id 9 and name guest.
How can I add a guest support in Entrust so that any user who is not logged-in will be considered as a guest and he will be allowed to visit certain routes as well.

A: I'd personally avoid any global middleware dealing with authorization as to not block your application from having publicly accessible pages.  Use route groups to assign middleware to protected routes.
While it may not fit into Entrust's design, you could also write a custom middleware to only allow guests and admins.  Something like this:
class AdminOrGuestMiddleware {

   /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($request->user() && !$request->user()->hasRole('admin')) {
            return redirect('/home');
        }

        return $next($request);
    }


text:
Q: How would I setup a HTML page to have a new title each new day? So my ultimate goal here is to have the site have a new title each day (24 hours).
I am not a very experienced program, but, I am aware something similar could be done with JS.
I saw this idea:
setInterval(function() {
    //change title
    //document.title = "Some new title";
}, 3000);

I'm not sure how I can take this idea above, which I do not fully understand and make it use, for example, a large array or predefined titles and select one at random each day.
Would it be possible to select the title out of another file or should I have them all in the JS file?  On the question just asked, should I have the JS code in the HTML file itself or referenced as a file like a CSS file?
I really appreciate any walkthrough/help I can get on this.  I hope your days are well all.

A: found the solved problem with running code once per day:
Run code once a day
When you will have a function that runs once per day, you just have to reference the title from DOM inside the function and define new title.
var titles = ["title1", "title2", "title3"];
var iterator = 0; // this variable should be incremented every day

// somewhere inside the function that runs once per day
document.title = titles[iterator];

There are 2 ways to import a script on html page.
Inline: https://www.w3schools.com/tags/tag_script.asp
External: https://www.w3schools.com/tags/tag_link.asp
U can even read external file (.txt e.g.) in js, you can look that up, but it's bit more complicated than this.


text:
Q: Scala dispatch: Set default hostname verifier? For my development machine, I'd like to disable SSL hostname checks for HTTPS connections. The exception that comes out of the dispatch code is this:
javax.net.ssl.SSLException: hostname in certificate didn't match: <localhost> != <*.mydomain.com> OR <*.mydomain.com> OR <mydomain.com>
        at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:228) ~[httpclient-4.1.3.jar:4.1.3]
        at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54) ~[httpclient-4.1.3.jar:4.1.3]
        at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:149) ~[httpclient-4.1.3.jar:4.1.3]
        at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:130) ~[httpclient-4.1.3.jar:4.1.3]
        at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:397) ~[httpclient-4.1.3.jar:4.1.3]
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148) ~[httpclient-4.1.3.jar:4.1.3]

I'm looking for a way to set the default hostname verifier in a way that will be used by dispatch. There's a method on the deprecated HttpsURLConnection to set the default hostname verifier, but that whole class is apparently deprecated. Is there a current correct way to do this?

A: It's com.sun.net.ssl.HttpsURLConnection that was deprecated in favor of javax.net.ssl.HttpsURLConnection; the latter isn't deprecated.
As to the ways to bypass this check, you could:

*

*Modify the certificate store (see this question)

*Use a JVM option (see this question)


text:
Q: How can I get my iPhone to sync with a new computer without being erased? For some reason, Apple has imposed a most absurd restriction where the only way to get an iPhone (or other iDevice) to sync with a different computer is by erasing it first. I haven't verified first-hand that this process actually erases the entire iPhone, because, naturally, I'm too afraid to try it.
So I spent a long time scouring the web trying to find a way around this ridiculous (and artificial) limitation. I spent literally hours over the course of several days and eventually found a combination of web pages that finally allowed me to do what I needed. I'll summarize the steps here for others who have banged their heads over this one.

A: By design, the iPhone will sync iTunes content with one computer at a time. Any attempt to sync such content with a second computer will result in ALL iTunes content being first erased from your phone & then replaced with the content from the second computer. This is a design feature and cannot be overridden. Because you replaced your computer, or hard drive, your phone will see this as a "new" computer. The iTunes content sync is one way: computer to phone. If you have photos that were synced to your iPhone or music ripped on your own, you will first have to copy them from your iPhone using third party software, such as TouchCopy, before you do anything else, as Apple makes no provision to do so.
Once you've done that, do the following in the order specified:

*

*Disable auto sync when an iPod/iPhone is connected under iTunes>Preferences>Devices(under Edit menu if using Windows).

*Make sure you have one contact & one event in the supported applications on your computer(iCal & Address Book on a Mac, Windows Address Book or Outlook if using Windows). These entries can be fake, doesn't matter, the important point is that these programs not be empty.

*Connect your phone, iTunes running, do not sync at this point.

*Store>Authorize this computer.

*File>Transfer Purchases. Also read here:
http://support.apple.com/kb/HT2519

*Right click your phone in the left device pane & select "Reset warnings".

*Right click again and select "Backup".

*Right click again & select "Restore from Backup", select the backup you just made. When prompted to create another backup, decline. Note music is not part of your iTunes backup and needs to be restored as above.

*This MUST be followed by a sync to restore your iTunes content, which you select from the various tabs, You'll get a popup regarding your contacts & calendars asking to merge or replace, select "Merge".
Your phone should look just like it did when you started, with no data loss.

A: Theres an easier method.  MUCH easier.  Cancel that window.  Your iPhone stays mounted in iTunes.  Right click and choose backup.  After the backup is complete, unplug your iphone and plug it back in.  Then allow it to erase your iPhone, and just restore from your backup.

A: The first thing to be aware of is that iTunes uses a unique "Library Persistent ID" to identify the pairing of an iDevice to an installation of iTunes. This 16-digit hexadecimal id is stored on both the device and the computer it is paired with. iTunes generates a new id when it is installed (or more accurately, when it builds its library). If you plug in an iPhone that has a different persistent id than the copy of iTunes installed on that computer, you will get the warning dialog shown above.
The only thing standing in your way, however, is that darn persistent id. To get things working smoothly, we need to hack the installation of iTunes so that it thinks its id is the same as the one on our iPhone.
To do that, we first need to figure out what our phone's persistent id is. There are a couple options here, depending on whether or not you have the original synced copy of iTunes still available.
Step 1: Getting the Persistent ID
If you still have the original installation of iTunes that your iDevice is synced with, you can grab the persistent id from the "iTunes Music Library.xml" file in your iTunes directory. Just search for the "Library Persistent ID" tag.
If you no longer have access to that previous installation (as was my case), you need to get the id from your iPhone itself. Luckily there is a sneaky way to do this without having to jailbreak your phone. [If your phone is already jailbroken, you can read it from one of the .plist files in your iTunes directory on the phone, I believe.]
The trick is that you need to do a backup of your phone using iTunes and then dig into the backup files to find the persistent id. Fortunately iTunes lets you perform backups without being synced, so you can backup an iPhone on any copy of iTunes.
Unfortunately, the id is not plainly visible in the backup files. You will need to use a free web script to determine your persistent id from an Info.plist file you upload.
Full instructions are on this page.
Now that you have your library persistent id, you need to trick your installations of iTunes into thinking that that id is actually the id it has.
Step 2: Changing iTunes' Persistent ID
iTunes stores the persistent id in two places, just to make it trickier for us to change: once in the "iTunes Music Library.xml" file already mentioned, and once more in the "iTunes Library.itl" file, which is a binary file and much trickier to edit.
Although it is (or at least was) supposedly possible to edit the binary file and get it to accept the change, I have not been able to get this to work, so I don't recommend bothering since there is an easier way that doesn't require it.
First, backup the two aforementioned files. Next, open the xml file and paste in your library persistent id obtained from step 1 over the existing id in the <Library Persistent ID> tag and save.
Now create an empty file and name it "iTunes Library.itl". It won't work if you just delete or rename the file. iTunes needs to think it's become corrupt, not just disappeared.
Now when you start iTunes, it will see the "corrupt" library file and will rebuild it for you, from the xml file which contains your new persistent id.
If all goes well, after a few minutes of rebuilding your library file (it can take quite a while if you have a large library, mind you), you should be able to plug in your iPhone and sync as if nothing were wrong in the world!
For more details (including how to find the iTunes directory on your computer), read this page.
Good luck!


text:
Q: Injecting React Component Into Chrome Extension For context, I am building a React/Redux chrome extension that is a sit/stand timer. When an interval is up, the extension will pop up and give the options to stay in that posture for longer, or log that they have changed positions.
Since I cannot programmatically open the popup.html, I am thinking that I can use a content script to inject a modal into whatever tab the user is currently on.
I've been googling "Injecting React Component Into Chrome Extension" for a couple of hours now, and most of the articles are a couple of years old and have not worked for me.
If anyone has knowledge, a tutorial, or an alternative solution, that would be amazing. Thanks!


text:
Q: Formatting points in TextView for Android I'm trying to convert an excel sheet of data into Sqlite database format. However in the excel sheet, there are columns which are in bullet forms. The number of bullet per row is subjective. Therefore i could not assign the columns to achieve this.
Does SQLite support point form formatting or is there any other way i can achieve the same results?
I want to be able to display the data in bullet form in the app itself as well.


text:
Q: How to show build time with react using vite? `
buildTime:{}

`
I have try using `import.meta`,but no time.thanks for your help.

A: ok,just do it like this

*

*add define in vite.config.ts

define: {
    '__APP_VERSION__': JSON.stringify('your version')
  }

*declare APP_VERSION in vite-env.d.ts then you can use APP_VERSION in global

/// <reference types="vite/client" />

declare var __APP_VERSION__:string;


text:
Q: her vs she usage after the word "except" Sentence in concern:

I ordered the sort of dessert that no one except her could finish.

Should her be she because the person is doing an action instead of serving as an object or being done on?

A: In

I ordered the sort of dessert that no one except her could finish.

except her is a prepositional phrase, so you should use her. It would be similar to writing but her.


text:
Q: How to dynamically configure relation with different entities depending upon column property How to configure User entity, to have OneToOne() relation with Profile entity with a extra condition. ie
if the User type is TYPE_A, then the User entity should have relation with ProfileA
or
if the User type is TYPE_B, then the User entity should have a relation with ProfileB
and so on...
Is it possible to achieve something like this?


text:
Q: Android - How to set typeface to bold on clicking a list item I am trying to set a row to bold on clicking it. But it gives me a ClassCastException when I try to convert view into TextView like the following -
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
  int position, long id) {
            TextView tv = (TextView)view;
            tv.setTypeface(null, Typeface.BOLD);
        }
        });

What am I doing wrong? How should I go about it?
EDIT:
My adapter looks like -
public class CountryListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> names;

public CountryListAdapter(Activity context, ArrayList<String> names) {
    super(context, R.layout.rowlayout, names);
    this.context = context;
    this.names = names;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.rowlayout, null, true);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    textView.setText(names.get(position));

    return rowView;
}
}

A: Your adapter code shows the main cause of failure:
According to your adapter code the view you cast is the rowView, not the textView.So you should access it also that way. That's why you get ClassCastException.
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
        View rowView = view
        TextView tv = (TextView) rowView.findViewById(R.id.label);
        tv.setTypeface(null, Typeface.BOLD);
    }
    });

A: Are you sure your list item is a TextView? Usually it is a more complex structure (e.g. a LinearLayout). And if this is the case you need to find out the TextView in question within that layout using findById().


text:
Q: Get ID of SVG element after mouse click using POST method and process it with PHP I would like to get the id of the svg element after a mouse click and process it using a PHP script. This needs to be done without the use of javascript. The html page contains inline svg.
In the following example, I would like to get the ID of circle element (#mycircle) when clicked with a mouse using POST method. Then process it with a PHP script with the value from $_POST['mycircle'].
Eg (may not be a valid svg or html code for the sake of brevity):
<html>
    <head>
        <title>SVG_id to PHP</title>
    </head>
    <body>
        <div class="container">
            <svg>
                 <symbol id=colony_circle><circle cx=10 cy=10 r=4 /></symbol>
                 <use xlink:href=#colony_circle id="mycircle" x="10" y="10"/>
            </svg>
       </div>
    </body>
</html>

A: Using the svg's foreignObject element and positioning it exactly on top of the desired svg element (Eg: circle). When you click the circle, the submit button is activated. The svg_action.php processes it and prints the value of the hidden input type.
svg_view.php file:
<?php
echo "<svg id=svg1 version=1.1";
echo " xmlns=http://www.w3.org/2000/svg";
echo " xmlns:xlink=http://www.w3.org/1999/xlink";
echo "x='0px' y='0px'";
echo " viewBox='0 0 400 160'";
echo "enable-background='new 0 0 400 160'";
echo " xml:space=preserve>";
?>
<circle cx="60" cy="80" r="30" fill="#00ff00" fill-opacity="0.5" />
<foreignObject x="32" y="53" width="200" height="150">
<body xmlns="http://www.w3.org/1999/xhtml">
    <form method=post action="svg_action.php">
        <input type="hidden" name="hidden" value="circleXYZ" />
        <input type="submit" style="background-color: #00ff00; width: 55; height: 55; border-radius: 50%;" value="" />
    </form>
</body>
</foreignObject>

</svg>

svg_action.php file:
<?php
var_dump($_POST['hidden']);
?>

Probably, there may be a better way to solve it without javascript!


text:
Q: Version property on jars in Web Start In a JNLP file, is the version property for a jar resource related to any metadata (e.g. manifest) or is it just arbitrarily set by the user creating the JNLP file?

A: Section 6 of the JNLP Specification gives the following information under section 6.3 "Version-based Download Protocol".

For the version-based download protocol, all resources are uniquely identified by a URL/version-id pair. Thus, a JNLP Client can at any given time request a specific version of a resource located at a specific URL.

The JNLP Client issues an HTTP GET request that includes the specific version of the resource that it needs. The request includes the field version-id, which specifies the requested version. For example, given the following jar element:
<jar href="http://www.mysite.com/b.jar" version="2.3+"/>

then the JNLP Client must issue the following HTTP GET request14:
http://www.mysite.com/c.jar?version-id=2.3%2B

The JNLP Client must examine the HTTP response status code and MIME type to determine if the result was successful. The valid responses are described in section 6.1.2. For the above jar element, the application/x-java-archive-diff MIME type cannot be returned. It can only be returned for incremental requests.
The version string used in the request is not necessarily exact, e.g., 2.3+. The Web server must specify the exact version-id of the resource that is returned in the response by setting the HTTP header field: x-java-jnlp-version-id. The exact version returned must be one that matches the requested version string.

Unfortunately the Spec. is not available for online browsing, but it can be downloaded.  I have found it to be invaluable for JWS development.


text:
Q: contextual meaning of "integrate" In the following sentence, what does "integrate" means?

Beyond the fact that these processes exacerbate inequalities among
individuals – those with the most valuable assets are more likely to
profi t from these new models – they contain the seeds of a
transformation of individuals, who increasingly integrate financial
and managerial logics in their own way of functioning.To extract value
from platform capitalism, individuals must constantly monetize and
maximize the value of their own assets. This means, for example, that
individuals may, when buying a new property, integrate the
potential profit that could be obtained by regularly listing their
property on Airbnb or another rental platform.

A dictionary meaning of "integrate" is "to combine two or more things in order to become more effective", but I'm not sure what individuals combine the potential profit with.
I'm confused about contextual meaning of "integrate" in the quoted sentence.
Thank you in advance!

A: In this case it means that individuals are adding the potential profit from renting out the new property to the change in their wealth by acquiring the property.  (This is clearly speculative as the property may fail to rent, or may fail to rent for the expected value, or may be even accrue costs from rental not covered by it).
For example: if the property were to cost 200,000 (pick your favourite currency) and you expect to rent it out for 2,000 per month, then you might integrate that 2,000 per month into your overall wealth (treating the property as an asset worth 200,000) and say that you are 2,000 per month richer.


text:
Q: Inner Proxies with Selenium Preface:  While this question includes a lot of WebDriver terminology, it's really a Java proxies question, which I am still trying to wrap my head around.  If you don't understand WebDriver, skip down, and I'll post a simplified problem
I currently have a wrappers around WebElement and List<WebElement>, namely EnhancedWebElement and WebElementList.  It is for quite a few reasons, and has allowed me quite a bit of flexibility.  I also use the page object pattern, and declare all of my elements as the two wrappers I have created (which works great).
However, I recently asked this question.   I wanted to find an element within an element, and still keep the entire thing within a proxy.  The answer worked great, and I made it generic and put it in my EnhancedWebElement class.  It looks like this:
public EnhancedWebElement findEnhancedWebElement(final By by){
        return (EnhancedWebElement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { WebElement.class }, new InvocationHandler() {
            // Lazy initialized instance of WebElement
            private EnhancedWebElement webElement;

            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                if (webElement == null) {
                    webElement = new EnhancedWebElement(findElement(by), driver);
                }
                return method.invoke(webElement, args);
            }
        });
    }

However...this has one problem.  If I find an element within an element within an element, I lose the first proxy.  This is because it instantiates the element in order to perform the next findEnhancedWebElement() function.
While you may think my crazy, my goal is to have a set of functions so I could do something like this:
EnhancedWebElement newElement = element.findElements(By.foo).getElementFoundBy(By.bar).findElement(By.foobar);

and still not performed any selecting on the page until I do newElement.click() or whatever action on the element.
(If you are really wondering why, it is because I have quite a few functions in EnhancedWebElement and WebElementList that depend on it not being instantiated.  If I was just going to perform a click(), then I wouldn't need all this)
For all people that don't understand WebDriver.  I have Object X.  It has a function that can return another object X, but only after doing some processing.  Object X also has other functions.  If I do X someObject = new X().getX().getX().getX(), I don't want any of the processing to be done until I do someObject.otherFunction()

A: I figured it out.  I needed to create a proxy around the original WebElement, not the new EnhancedWebElement, and then create a new instance of EnhancedWebElement wrapped around it.  That way, when I am using the findEnhancedWebElement(), I never touch the original WebElement.


text:
Q: Manually editing systemd files I am new to Linux. I have installed Arch Linux on a new machine.
Yesterday I tried to install GNOME (on top of Xorg). When I enabled gdm.service and then rebooted, I was met with a black screen. I think either I messed this up or because my machine has an NVIDIA card.
I have a bootable USB. I realize that I can simply chroot into my machine and then just use systemctl to disable gdm.service BUT I was wondering if I can edit my systemd files to disable it myself and learn a bit about service management in the meantime.
Is this feasible/a good idea? I found the gdm.service file in /lib/systemd/system. Can I change one of the variables or delete the file altogether to have the same effect? For example, there is a variable in this file, Restart=always. If I change this value will I prevent the service from being run during the boot process?
Are there any good resources which explain what is really going on when using systemctl commands? I'm guessing that enabled services have a larger footprint then just these files in the /lib/systemd/system directory.
start a service a at bootime in systemd states that systemctl enable creates symbolic links to the /lib/systemd/system files. Where are these symbolic links and can I edit them manually?

A: When systemd disables masks a service, it actually sets a symlink to /dev/null instead - see How to disable a service without using 'systemctl disable'
Additionally, don't edit the files in /lib/systemd/system/ - instead you make a copy in /etc/systemd/system/ and then edit your copy. That allows the other ones to be owned by your system's package manager, etc. See RHEL docs for more info. I know you said Arch, but systemd is systemd.


text:
Q: SQL Server: how to set return format? Question: The new SQL Server 2008 database returns me values formatted English (date/float).
Is there a way I can set the return format ?
For example temporarely switching the database language?
Or just set the language for the current query ?

A: BOL: Specifies the language environment for the session. The session language determines the datetime formats and system messages.
DECLARE @Today DATETIME
    SET @Today = '12/5/2007'

    SET LANGUAGE Italian
    SELECT DATENAME(month, @Today) AS 'Month Name'

    SET LANGUAGE us_english
    SELECT DATENAME(month, @Today) AS 'Month Name'
    GO

A: You cannot switch the language in SQL Server for just a single statement or specify a different language for a select.
What you need to do is:

*

*either convert DATETIME to string using an appropriate "style" value in your CONVERT statement (see the MSDN docs on CONVERT for details)

*have a batch to switch to the language needed, execute your statement, and then switch back

*don't do the switching on the SQL Server side, but in your application


text:
Q: how to convert multiple file into PDF I'm trying to convert a list a file Informix4gl report file in a folder into PDF file.
I'm using java with iText to convert the file. I've only succeeded converting one file at the moment. This is how I get the file from a folder.
    //File directory
    public static final String TEXT
    = "O:\\CONVERT\\FOLDER ORI\\BL2054.801";

    //Where file will be stored after conversion
    public static final String DEST
    = "O:\\CONVERT\\FOLDER PDF\\BL2054.801.pdf";

Problem with this is, I have to define the input file name and output file name in the code. What i wanted to do is add loop so that the program automatically get file one from the folder and convert to PDF. Then repeat for the next file.

A: getPathFilesFromFolder().stream().forEach({
    file -> convertToPdf(file, generateDestinationPathFile(file))
    //convertToPdf is a method from your lib
})

generateDestinationPathFile(File file) {
    // rename file
}
List<Path> getPathFilesFromFolder() throws IOException {
        return Files.list(Paths.get("D:\\Example"))
                    .collect(Collectors.toList());
}

We will loop all files in the folder, then put it to your method that need two params (sourceFile, destinationFile).


text:
Q: sqoop export for hive views I am trying to sqoop hive view to SQL server database however i'm getting "object not found error". Does sqoop export works for hive views?
sqoop export --connect 'jdbc:jtds:sqlserver:<Connection String>' --table 'tax_vw' --hcatalog-database default --hcatalog-table tax_vw --connection-manager org.apache.sqoop.manager.SQLServerManager --driver net.sourceforge.jtds.jdbc.Driver --username XXX  --password YYY --update-mode allowinsert

INFO hive.metastore: Connected to metastore. ERROR tool.ExportTool:
Encountered IOException running export job: java.io.IOException:
NoSuchObjectException(message:default.tax_vw table not found)

Need help on this.

A: Unfortunately, this is not possible to do using sqoop export, even if --hcatalog-table specified, it works only with tables and if not in HCatalog mode, it supports only exporting from directories, also no queries are supported in sqoop-export.
You can load your view data into table:
create table tax_table as select * from default.tax_vw;

And use --hcatalog-table tax_table


text:
Q: Update Already opened Google Map by sending new destination address from our service String uri = "http://maps.google.com/maps?saddr=" + strlat + "," + strlon + "&daddr=" + strDlat + "," + strDlon;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setComponent((new ComponentName("com.google.android.apps.maps",
    "com.google.android.maps.MapsActivity")));
startActivity(intent);

This code opens a google map and We can navigate to the destination address without any problem.
My Question is if the destination address also keeps changing (say user 2 is moving to another location and I have the location) how can we update that on google map?
Is there any way to inform google map that please update the destination location too.
I don't want to add google map in my activity.
Please help me out.

A: No, you can't inform Google Maps about location changes. It will automatically track user location.
However, you can only pass one location (e.g. destination) and let user decide what to do with it.

A: We cannot update the google map started by the following code
String uri = "http://maps.google.com/maps?saddr=" + strlat + "," + strlon + "&daddr=" + strDlat + "," + strDlon;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setComponent((new ComponentName("com.google.android.apps.maps",
    "com.google.android.maps.MapsActivity")));
startActivity(intent);`

I have acheived this task by
1. create GoogleMapActivity with a map
2. draw markers two markers on it with lat,long
3. get dirctions
using following code
`
 private String getDirectionsUrl(LatLng origin,LatLng dest){

              // Origin of route
              String str_origin = "origin="+origin.latitude+","+origin.longitude;

              // Destination of route
              String str_dest = "destination="+dest.latitude+","+dest.longitude;

              // Sensor enabled
              String sensor = "sensor=false";

              // Building the parameters to the web service
              String parameters = str_origin+"&"+str_dest+"&"+sensor;

              // Output format
              String output = "json";

              // Building the url to the web service
              String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
       Log.i("MAP", "url="+url);
              return url;
          }
          /** A method to download json data from url */
          private String downloadUrl(String strUrl) throws IOException{
              String data = "";
              InputStream iStream = null;
              HttpURLConnection urlConnection = null;
              try{
                  URL url = new URL(strUrl);

                  // Creating an http connection to communicate with url
                  urlConnection = (HttpURLConnection) url.openConnection();;
                  urlConnection.setReadTimeout(10000);
                  urlConnection.setConnectTimeout(10000);
                  // Connecting to url
                  urlConnection.connect();

                  // Reading data from url
                  iStream = urlConnection.getInputStream();

                  BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                  StringBuffer sb = new StringBuffer();

                  String line = "";
                  while( ( line = br.readLine()) != null){
                      sb.append(line);
                  }

                  data = sb.toString();

                  br.close();

              }catch(Exception e){
                  Log.d("Exception while downloading url", e.toString());
              }finally{
                  iStream.close();
                  urlConnection.disconnect();
              }
              return data;
          }
`

then draw the lines on google map


text:
Q: Как сделать, чтобы цикл работал определённое время? Есть вещественное t (от 1 до 10), время в минутах. В цикле от 1 до 100500 (с 4 присваиваниями внутри), надо сделать задержку sleep(). Какая величина параметра в миллисекундах должна быть в sleep(), для того, чтобы цикл продлился ровно t минут?
A: Во время выполнения цикла проверять, сколько он длится, допустим n, после выполнения цикла сделать задержку t-n единиц времени, если же указанное время t меньше времени выполнения цикла, прервать его во время вышеописанной проверки.
A: Вообще говоря, о точности в Windows говорить нельзя. Функция Sleep() погружает поток в "сон" на заданный интервал, но выйти из него он может и позднее (это как планировщик "решит"). Функция Win32 API GetTickCount() или ее эквивалент для быстрых итераций может не подойти (данная функция возвращает время прошедшее со старта Windows в ms). Если тело цикла исполняется очень быстро можно рекомендовать QueryPerformanceFrequency/QueryPerformanceCounter


text:
Q: Can't make android buttons touch each other I have 5 buttons lined up in a row inside a linear layout and I cannot get them to touch each other. For some reason there is a padding between the buttons.
The above image shows what my current android application is displaying when it runs. Can someone please help with what I have to do to make them touch while also filling the screens width? I have included the XML code below:
<LinearLayout
    android:id="@+id/LinearLayout02"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_gravity="bottom"

    android:layout_alignParentBottom="true">
    <Button
        android:minHeight="0dp"
        android:minWidth="0dp"
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/options_selected">
    </Button>
    <Button
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/stats_unselected">
    </Button>
    <Button
        android:id="@+id/stats"
        android:layout_width="wrap_content"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/camera_unselected">
    </Button>
    <Button
        android:id="@+id/shop"
        android:layout_width="wrap_content"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/shop_unselected">
    </Button>
    <Button
        android:id="@+id/Button03"
        android:layout_width="wrap_content"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/profile_unselected">
    </Button>
</LinearLayout>

A: Try this layout: use weightSum property on parent layout
and for child element use: android:layout_width="0dp" with android:layout_weight="1".
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom"
    android:orientation="horizontal"
    android:weightSum="5">

    <Button
        android:id="@+id/Button02"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:drawableTop="@mipmap/ic_launcher"
        android:padding="0dp"></Button>

    <Button
        android:id="@+id/camera"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:drawableTop="@mipmap/ic_launcher"
        android:padding="0dp"></Button>

    <Button
        android:id="@+id/stats"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:drawableTop="@mipmap/ic_launcher"
        android:padding="0dp"></Button>

    <Button
        android:id="@+id/shop"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:drawableTop="@mipmap/ic_launcher"
        android:padding="0dp"></Button>

    <Button
        android:id="@+id/Button03"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:drawableTop="@mipmap/ic_launcher"
        android:padding="0dp"></Button>
</LinearLayout>

Output:

A: Try this (I cleaned a bunch of wrong attributes & set the height in one place alos when using weights, it is better to give width 0dp):
<LinearLayout
    android:id="@+id/LinearLayout02"
    android:layout_height="53dp"
    android:layout_width="match_parent"
    android:layout_gravity="bottom"
    android:weightSum="5">
    <Button
        android:id="@+id/Button02"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/options_selected">
    </Button>
    <Button
        android:id="@+id/camera"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/stats_unselected">
    </Button>
    <Button
        android:id="@+id/stats"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/camera_unselected">
    </Button>
    <Button
        android:id="@+id/shop"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/shop_unselected">
    </Button>
    <Button
        android:id="@+id/Button03"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/profile_unselected">
    </Button>
</LinearLayout>

A: *

*Add attribute android:orientation="horizontal" and android:weightSum="5" to LinearLayout02.

*Use Button width as android:layout_width="0dp" instead of android:layout_width="wrap_content"

*Remove redundant attributes android:layout_alignParentLeft="true", android:layout_alignParentTop="true" from all buttons.

Here is the working XML:
<LinearLayout
    android:id="@+id/LinearLayout02"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal"
    android:weightSum="5">

    <Button
        android:id="@+id/Button02"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/options_selected">
    </Button>

    <Button
        android:id="@+id/camera"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/stats_unselected">
    </Button>

    <Button
        android:id="@+id/stats"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/camera_unselected">
    </Button>

    <Button
        android:id="@+id/shop"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/shop_unselected">
    </Button>
    <Button
        android:id="@+id/Button03"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/profile_unselected">
    </Button>
</LinearLayout>

OUTPUT:

Hope this will help~


text:
Q: How spring open transaction with readonly=true if there is exsiting transaction with readonly=false How spring open transaction with readonly=true if there is exsiting transaction with readonly=false
    public void second(){...}

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void first(){
second();
}


text:
Q: Passing int array from C (JNI) to Java and return back an int array from Java to C? I am new to java here. I am working on Calling Java methds from C using JNI. I can successfully pass and return int values from  C to Java but I am not able to pass Int array from  C to Java and return back an int array from Java to C. Please let me know how to do so?
Below I have mentioned my generic code. Please let me know how to modify it and acheive ? I have came across many articles for the opposite (passing int array from Java to C). Sorry if it looks like a basic question.
My C code:
jclass cls = (*env)->FindClass(env,"Simple");
jmethodID mid = (*env)->GetStaticMethodID(env,cls, "main", "([Ljava/lang/String;)V");
jmethodID addnumber_method=(*env)->GetStaticMethodID(env , cls, "add" , "()V");

 (*env)->CallStaticVoidMethod(env,cls, mid, NULL);
  printf("sum is %d\n",(*env)->CallStaticIntMethod(env, cls, addnumber_method , a_num , b_num));

My java code:
public class simple
{
  public static int add(int a , int b)
  {
    int sum = a+b;
    return sum;
   }

  public static void main(String[] args)
  {
    System.out.println("C calling java");

  }
}


text:
Q: How does the 'key' prop work in a non-dynamic child component and why is it essential for rendering updates? I understand that the special 'key' prop when used with child components that are created dynamically from arrays helps React to uniquely identify components and render updates efficiently. But I would like to know when and why would it be necessary to use the key prop for a 'non-dynamic' component.
My application uses a Reducer and useContext hook to manage state for a Functional Component A. The state object has a maximum 3 levels of nesting. Component A updates state and passes part of the state object as props to two instances of a child component B. B uses these props to render a switch component and 2 input components. Here's the simplified code for this hierarchy.
Component A:
const A: FC = () => {
// ....
// graphql queries to get data and update state using reducer
// ...
return (

  );
};

Component B:
  const B: FC = props => {
  const { value1, value2, enabled} = props;  // there are other props as well

  return (
    <>

        <Switch
          onChange={onValueChange}
          isChecked={enabled}
          disabled={disabled}
        />

          <Input
            input={value1}
            disabled={disabled}
          />

        <Input
          input={value2}
          disabled={disabled}
         />

    </>
  );
};

A tablerow click event is used to update the state and the component B displays the 'settings' of this selected item which the user can mutate using the component B.
Here's the problem I'm facing- when the state is updated by a user action (selecting a row from a table, not shown in the snippet), I can see that both A and B receive the new data in the react developer tools and by printing to the console. But, a render does not take place to show the new data. I would like to understand why this is the case.
After looking up this issue, I figured I need a key prop while instantiating component B (the answers don't clearly explain why). With the following addition, the values did render correctly. Why is a key necessary here and why does it only work when the key contains all props that can change values? If I only use the uniqueId as the key, the value1 and value2 do not render correctly again. If I have many changing-props, do I have to them to add the key as well? Isn't there a less clumsy approach?
Updated Component A:
const A: FC = () => {

return (

  );
};

Also, I noticed that although clicking on a table row rendered the correct value in component B now, but clicking on a row that is not changed by the user so far would cause the previously rendered values to remain on the Input1 and Input2 components (instead of blank). So I had to add keys to the Inputs as well with the enabled state attached to it which fixed this issue.
Updated Component B:
  const B: FC = props => {
  const { value1, value2, enabled} = props;  // there are other props as well

  return (
    <>

        <Switch
          onChange={onValueChange}
          isChecked={enabled}
          disabled={disabled}
        />

          <Input
            key={`value1-${enabled}`}
            input={value1}
            disabled={disabled}
          />

        <Input
          key={`value2-${enabled}`}
          input={value2}
          disabled={disabled}
         />

    </>
  );
};

Here again, why is a key needed? Doesn't react figure out that the props have changed and automatically render again?