text:
Q: CTR mode in Linux Kernel I am currently experiencing some Kernel development for filesystem purposes that requires AES ciphering and I encounter the following constraints :

*

*I must be able to cipher a plaintext of any length

*Padding (if any) is unnoticeable

*The overhead that might result of padding bytes is unacceptable
On the paper, there is an easy way to solve this : use the CTR encryption mode !
With that brilliant idea (hum...), I am happily diving into the crypto API sources of the Linux Kernel to learn how to get started.
At this point I notice that the ciphering function involves the use of miscellaneous functions :

*

*The crypt_inplace function. Its purpose is to handle the case when the user wants to store the cipher text in the same memory area as the given plaintext. (same as crypt_segment but with the memory constraint)

*The crypt_segment function. It is the standard ciphering function. It ciphers a whole block of data (that is 16 bytes for AES).

*The crypt_final function. When the given plaintext's length L is not a multiple of the underlying block cipher blocksize, this function performs the ciphering on the remaining bytes.

Thus with our L bytes long plaintext and with AES, the first L/16 blocks are processed using crypt_segment or crypt_inplace depending on what is requested. The remaining L mod 16 bytes are then ciphered using crypt_final.
The inner crypt_segment functions is defined as follows : (crypt_inplace is very similar)
static int crypto_ctr_crypt_segment(struct blkcipher_walk *walk,
                    struct crypto_cipher *tfm)
{
    void (*fn)(struct crypto_tfm *, u8 *, const u8 *) =
                   crypto_cipher_alg(tfm)->cia_encrypt;
    unsigned int bsize = crypto_cipher_blocksize(tfm);
    u8 *ctrblk = walk->iv;
    u8 *src = walk->src.virt.addr;
    u8 *dst = walk->dst.virt.addr;
    unsigned int nbytes = walk->nbytes;

    do {
        /* create keystream */
        fn(crypto_cipher_tfm(tfm), dst, ctrblk);
        crypto_xor(dst, src, bsize);

        /* increment counter in counterblock */
        crypto_inc(ctrblk, bsize);

        src += bsize;
        dst += bsize;
    } while ((nbytes -= bsize) >= bsize);

    return nbytes;
}

As you can see, the counter is incremented on a blocksize basis. On most use cases it will not be an issue but consider this scenario :

*

*Write request at a given place p (this can be a (sector,offset) particular value on a hard drive for instance) : 11-byte long plaintext

*Read request for 8 bytes at p+3 : here, we want to get back the 8 last bytes of the initial plaintext from the written ciphertext.

The first step will be done with a single call to crypt_final in the ciphering sequence. Then, the 11 ciphered bytes are written at the right place. But when we want to retrieve the last 8 bytes of this chunk of data, due to the "block-wide" ciphering, we need the 3 previous bytes, stored in p, p+1 and p+2 to perform the deciphering operation.
Obviously, in a filesystem point of view, when a read is requested, there is no way for the kernel to know this kind of things if it does not make some hardware-dependent assumptions.
Hence, here is my question : is there a way to set up the CTR mode to always perform (de)ciphering operations on a byte basis or should I create my own implementation of CTR mode to enforce this ? (I did not find any entry point in ctr source code to do this configuration operation, I might have missed something)
Thanks in advance, I hope I have not stunned you with the big post !
PS : The code snippet in this post can be found in the ctr.c file under the crypto directory of a Linux Kernel source tree. The displayed version comes from the 3.8-rc3 Kernel release.

EDIT :
In fact, the CTR mode is designed to handle any length of data. I will recall the description found in the ISO/IEC 10116 specification.
Let assume our plaintext P is divided into chunks ( Pi )0 < i < n of equal length (j bits).
Let K be the key supplied for the encryption and IV the initialization vector for the counter.
The ciphertext C will be divided into chunks ( Ci )0 < i < n like the plaintext P.
The CTR mode introduce a counter, which walks at each processed chunk. That said, we will call the counter block used for ciphering (resp. deciphering) the chunk Pi (resp. Ci) CTRi
Finally, let CTR1 = IV
With these notations, here is what the computation may look like :

FOR i from 1 to n DO

*

*Y = AES_encrypt(CTRi, K) <- Y is 16-bytes long

*E = Truncate(Y, j) <- Only keep the j leftmost bits of Y

*Ci = Pi XOR E

*CTRi+1 = ComputeNextCTR(CTRi) <- Usually ComputeNextCTR is a simple incrementation.

  DONE

In the CTR version found in the Linux Kernel, this behaviour is enforced with j taking the value of the underlying block cipher blocksize (128 bits with AES), except for the last step where a truncation occurs if the given plaintext has not a suitable length.
My question was : is there a way to tell the crypto API to apply the j parameter I want ?
To me, it seems like the answer is "No.", so I would have to "reinvent" the wheel and make a new implementation of the CTR mode to get this extra feature. Since I may have missed something, I would be grateful to the person who will clearly state this.
Bonus one : If the answer is "No.", a quick overview of how the algapi of the Crypto API works would be very very welcome (I am currently digging into this).
Thanks in advance again.

A: After having digged the crypto sources, I can say that ... No, I can't set up the j parameter I introduced in the question for the CTR mode.
Nonetheless, I will give a few details about the inner crypto API to make this answer relevant. The details exposed herein are describing the internal low-level API to add support for new algorithms/modes in the crypto API.

Crypto objects
First of all, the crypto API manages collection of various objects. I use the word object because even though it's C programming, the code is obviously kinda object oriented. There are three main objects :

*

*Algorithms : struct crypto_alg

*Templates : struct crypto_template

*Instances : struct crypto_instance and struct crypto_spawn

*Transforms : struct crypto_tfm and friends (struct crypto_blkcipher, ...).

The first category is the milestone of this inner beast. When one wants to create a new algorithm, he only has to create a struct crypto_alg, fill the appropriate fields and register it.
Templates are a bit different since they rely on an a given algorithm structure. The algorithm object is passed when needed at run time. Therefore, templates are the suitable object for creating custom modes of execution (like it is implied in my original question).
Then, instances and spawns are here to handle internally how this little world interacts with the outside and with itself.
Finally, transforms structures are the "one-use" specific structures exposed to the outer interface (these will be used from other modules which need to encrypt/decrypt something).

Creating a new template
Basically, the procedure is rather simple, one can start from an existing template such as the ones found under the ctr.c file. Nevertheless, I will show some details.

How is the above handled by the crypto API
This part will cover the way the inner crypto part handles template or algorithm creation and the way it offers cryptographic features to the user (by user, understand other modules).
Note: This answer is under construction, I will edit it regularly to add extra information.


text:
Q: libgdx blurred 2d graphics I am still getting to this problem, and i am feeling like my head is going to blow. Lets say, that i have this code for drawing a texture i created.
public MainMenuScreen(TheSpring game) {
    this.game = game;
    //camera for interface
    guiCam = new OrthographicCamera(1020, 640);
    guiCam.position.set(1020 / 2, 640/2, 0);
    //buttons
    play = new Button(10, 120, 400, 300, AssetLoader.play);
    highscores = new Button(460, 10, 82, 102, AssetLoader.highscores);
    sound = new Button(10, 10, 72, 72, AssetLoader.soundEnabled);
    sound.AddTexture(AssetLoader.soundDisabled);
    if (!Settings.soundEnabled)
        sound.SwitchTexture();
    help = new Button(120, 160, 80, 15, "Help", Color.WHITE);
    //enable buttons
    play.Enable(true);
    highscores.Enable(true);
    sound.Enable(true);
    help.Enable(true);
    //touchpoint for unproject
    touchpoint = new Vector3();

}`

The texture i created for play button is also 400x300.
The problem is, that when i try to run this "app" my textures are blurred.
The Button is my class, and I am using its drawing method.
public void Draw(SpriteBatch batcher) {
    if (enabled){
    if (text != null) {
        AssetLoader.ComicFont.setColor(clr);
        AssetLoader.ComicFont.setScale(ScaleWidth, ScaleHeight);
        AssetLoader.ComicFont.draw(batcher, text, x, y + height);
    }
    if (texture != null) {
        batcher.draw(texture, x, y, width, height);
    }
    }

}

And the result is this (please don't judge me for my drawing skills, its only testing version)

For example, on the right side of button, there should be also black line, and lines should be straight. Can you please help me? :)

A: one possible solution can be setting your texture filters to Linear
By default they are not linear.
try this out
    texture.setFilter(TextureFilter.Linear,TextureFilter.Linear);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter ListView.builder() is loading all items at once I have a ListView I'm initializing with ListView.builder() and it seems to be loading all items at once. This is the code:
ListView.builder(
  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  itemBuilder: (context, index) {
    if (index == length) {
      Future.delayed(Duration(seconds: 2)).then((value) {
        setState(() => length += 10);
      });
      return Center(child: CircularProgressIndicator());
    }

    return Container(
      color: Colors.red,
      padding: EdgeInsets.all(24.0),
      margin: EdgeInsets.all(12.0),
      child: Text(index.toString()),
    );
  },
  itemCount: length + 1,
)

This ListView is wrapped in another ListView. I'm trying to make a network call to load more items once I hit the bottom of the list, but it just gets called over and over again even when I haven't scrolled to the bottom. Is this because I have it nested in a second ListView?


text:
Q: Two recycler view in same layout as in flipboard app I want to use a RecyclerView(list like) below another RecyclerView(Grid like) as in flipboard

I tried two RecyclerView inside ScrollView with wrap content but nothing is showing.
I can able to see two views if it is placed in linear layout and equal weight is added to it. But that does not look like this app View.
This is my layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/parent_category_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minWidth="@dimen/default_small_padding"
        android:gravity="center"
        android:visibility="visible"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/category_grid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="150dp"
        android:gravity="center"
        android:visibility="visible"/>

</LinearLayout>

A: There's actually a really simple way to achieve the desired layout with just one RecyclerView!
The key is using a GridLayoutManager and its SpanSizeLookup.
First of all define your GridLayoutManager like this:
GridLayoutManager layoutManager = new GridLayoutManager(context, spanCount);

where spanCount is the maximum amount of spans/columns you want to have. In your case, spanCount should be 2;
Now you need a way to tell this layoutManager how many spans an item should span.
A simple way would be to use a viewtype/ViewHolder for items that should span just one column and another one for items that span the whole width.
Let's assume you define the viewtype for grid-items as VIEWTYPE_GRID_ITEM and the viewtype for standard listitems as VIEWTYPE_LIST_ITEM.
You can then use these viewtypes to tell the layoutManager when to use just one span:
layoutManager.setSpanSizeLookup(new SpanSizeLookup() {
    @Override
    public int getSpanSize(int position){
        return adapter.getItemViewType(position) == VIEWTYPE_GRID_ITEM ? 1 : spanCount;
    }
});

Finally, set the layoutManager to your RecyclerView:
recyclerView.setLayoutManager(layoutManager);

And that's it!

A: I don't think that they use two ListViews (or ListView + GridView).
I think they use a ListView ( the one in the bottom) and they add a custom Header to this list (the one in the top), which look like a GridView.
Or if they use a Recyclerview, they can achieve this by using a different layout in the adapter for the first item.

PS: it's not recommended to use two scrollable view inside each other (like Recyclerview inside ScrollView).

A: In android we are advise to use only one scrollable view at time , if you want to use one scrollable view inside other one refer below links.
1)Android list view inside a scroll view
2) https://stackoverflow.com/questions/6210895/listview-inside-scrollview-is-not-scrolling-on-android


text:
Q: What Cassandra Driver should I use for Scala? I am new to cassandra and scala. Please someone provide me an example on how to connect to cassandra database using scala API.

A: Use Phantom DSL.
Check out the Phantom DSL tag on Stack Overflow and the Phantom DSL Git repo:
https://github.com/outworkers/phantom
Check out some examples here:
https://github.com/iamthiago/cassandra-phantom
http://outworkers.com/blog/tag/phantom
I hope this helps,
Rhys


text:
Q: Select * into #Temp not working in dynamic SQL When I create a temporary table and insert data into that temporary table through dynamic SQL its work fine. But when I use select * into  #TempTable1 from YourTable in dynamic SQL it throw error. I am unable to understand the cause of this error.
Table:
create table YourTable(Id int identity(1,1),Col1 varchar(100));

insert into YourTable(Col1)
values('Stack'),('Over'),('Flow')

Working Code:-
Declare @SqlStr varchar(max)

create table #TempTable(Id int identity(1,1),Col1 varchar(100))
set @SqlStr='Insert into #TempTable(Col1) select Col1 from YourTable'
exec(@SqlStr)
select * from  #TempTable

Not Working Code:
Declare @SqlStr varchar(max)
set @SqlStr='select * into  #TempTable1 from YourTable'
exec(@SqlStr)
select * from  #TempTable1

Error:

Msg 208 Level 16 State 0 Line 4
  Invalid object name '#TempTable1'.

For Reference data is here.

A: The cause of this error is that a temp table is session bound and your dynamic SQL runs in a separate session.
Use a global temp table (prefix: ##) and make this one unique by naming (i.e. add a guid to the name). This way the dynamic SQL can see it.
Different types temporary tables: http://www.sqlines.com/articles/sql-server/local_and_global_temporary_tables


text:
Q: Dart PaperDropdownMenu getting selected item I'm kind of struggling getting the selected item id or even the text displayed in a dropdown menu list. Here's my code:
HTML:
      <paper-dropdown-menu  label="Currency" on-core-select="{{selectCurrency}}">
        <paper-dropdown class="dropdown" halign='right'>
          <core-menu class="menu"  selected="{{selectedCurrency}}">
            <template repeat="{{c in currencies}}">
              <paper-item>{{c}}</paper-item>
            </template>
          </core-menu>
        </paper-dropdown>
      </paper-dropdown-menu>

Dart:
void selectCurrency(CustomEvent e, var detail, PaperDropdownMenu m) {
    var id = m.getAttribute("selected");
    //id = mCurrencyDropdown.selected;
    JsObject detail = new JsObject.fromBrowserObject(e)['detail'];

    if(detail['isSelected']) {
        PaperItem selected =  detail['item'] as PaperItem;

        print( 'source | $selected' );
    }

  print(detail);

}

I can see several properties from which I might get the information I want but I can't access them as the don't seem to be public:
https://drive.google.com/file/d/0B9-4jVIpB0XuTXJ5eVBMZllyanM/view
Any idea? Thank you!
Thanks to Günter I have found the answer:
I have an observable like this:
@observable int selectedCurrency = 20;

Apparently you can simply add a method to your class matching the members name like this and it's called each time the observable is changed:
selectedCurrencyChanged(var oldValue, var newValue) {
    print(newValue);
}

Official Documentation

A: Where is the field selectedCurrency you have bound to ?
I guess you can drop the on-core-select event handler entirely and instead add a method
selectedCurrencyChanged(newValue) {
  // event handler code here
}


text:
Q: How to get Exponent of Scientific Notation in Matlab When the numbers are really small, Matlab automatically shows them formatted in Scientific Notation.
Example:
A = rand(3) / 10000000000000000;

A =

  1.0e-016 *

    0.6340    0.1077    0.6477
    0.3012    0.7984    0.0551
    0.5830    0.8751    0.9386

Is there some in-built function which returns the exponent? Something like: getExponent(A) = -16?
I know this is sort of a stupid question, but I need to check hundreds of matrices and I can't seem to figure it out.
Thank you for your help.

A: You can use log10(A). The exponent used to print out will be the largest magnitude exponent in A. If you only care about small numbers (< 1), you can use
min(floor(log10(A)))

but if it is possible for them to be large too, you'd want something like:
a = log10(A);
[v i] = max(ceil(abs(a)));
exponent = v * sign(a(i));

this finds the maximum absolute exponent, and returns that. So if A = [1e-6 1e20], it will return 20.
I'm actually not sure quite how Matlab decides what exponent to use when printing out. Obviously, if A is close to 1 (e.g. A = [100, 203]) then it won't use an exponent at all but this solution will return 2. You'd have to play around with it a bit to work out exactly what the rules for printing matrices are.

A: Basic math can tell you that:
floor(log10(N))

The log base 10 of a number tells you approximately how many digits before the decimal are in that number.
For instance, 99987123459823754 is 9.998E+016
log10(99987123459823754) is 16.9999441, the floor of which is 16 - which can basically tell you "the exponent in scientific notation is 16, very close to being 17".
Floor always rounds down, so you don't need to worry about small exponents:
0.000000000003754 = 3.754E-012
log10(0.000000000003754) = -11.425
floor(log10(0.000000000003754)) = -12


text:
Q: How to use secure NTP authentication from Windows client to a Linux Server? I have a NTP Server running on a Linux (Ubuntu 16.04) box and I also have to  securely serve a bunch of Windows Server boxes (2012, 2012 R2 and 2008 R2 mainly). For network equipements and Linux servers I'm using MD5 keys but I don't know how to do something similar on Windows.
I tried to google that issue but all I could find is this thread.
How can I securely sync the Windows boxes with the Linux NTP server ?
Thank you.

A: Windows uses a subset of the NTP protocol (SNTP)[https://serverfault.com/questions/740490/ntp-with-authentication-on-windows-system], you won't be able to use the same authentication mechanisms.
Since you can't use Active Directory for authentication, you'll probably have to use a different (third party) NTP client that supports it.


text:
Q: Increasing the cluster size in Google Container Engine How do I add VM instances to my existing Container Engine cluster?
I understand that I can add pods via replication controllers, but it seems there can be multiple pods per VM instance. Adding 50 new pods to my initial 3 VM cluster just distributed those pods evenly and did not start new instances. Not really helpful if I want to scale my app due to increased load.

A: For now, there isn't a way to scale your cluster. We are working on integrating Container Engine with the recently announced Managed Instance Groups and Cloud AutoScaling Service.
Stay tuned!

A: Resizing a cluster is now possible, see the docs

A: This may help you
https://cloud.google.com/container-engine/docs/resize-cluster
$ gcloud container clusters describe CLUSTER_NAME --format yaml | grep -A 1 instanceGroupUrls
$ gcloud compute instance-groups managed resize gke-example-b937f2ba-group --zone us-central1-f --size 4


text:
Q: Radeon 5450 crashes when running streaming video via HDMI So I have a box that's been working fine for months, with a Radeon 5450 video card running a standard small monitor via VGA. Just bought my first-ever HDMI-capable TV, and plugging the HDMI cable into it, it works fine... until I try to stream video on it.
Netflix is fine. Simple animations, like the spectrometer in Foobar, is fine.
But if I try anything else with video streaming -- YouTube, or TV streaming -- after a few seconds I'll get a total freeze with a stuttering sound. Zero keyboard response. If I use the reset button, I get a freeze on the BIOS startup screen. A hard reboot -- full power down, wait 10 seconds -- and everything boots up again normally.
I'm mystified, but I also don't know much at all about HDMI, hardware controllers, etc.
I'm attaching a full system rundown (captured by Speccy) and some screenshots of the Catalyst control center that seem to pertain.
I do have:
- a fully updated BIOS
- all updates for Windows XP, which is what this system is running on
- the latest video drivers for my video card
Again, it seems to be only streaming video that crashes the system. Which, since this is basically what this setup is for, is kind of disheartening. Ideas?
Speccy rundown:
http://pastebin.com/DmmmGjK7
Images from Catalyst Control Center:

A: Your graphics card drivers seem to be outdated, can you update your drivers and then try this out again ?


text:
Q: How to sum values in treeview line using onchange event in odoo 9 I got a parent model and a child model, here is the code :
class parent_model(osv.osv):
    _name = 'parent_model'
    _columns = {
        'line_ids'      : fields.one2many('child_model', 'line_id', 'Line ID', ondelete='cascade'),
        'description'   : fields.text('Description', required=True),
        'grand_total'   : fields.float('Grand Total'),
    }

class child_model(osv.osv):
    _name = 'child_model'
    _columns = {
        'line_id'       : fields.many2one('parent_model', string='Line ID', required=True),
        'item'          : fields.char('Item', required=True),
        'amount'        : fields.float('Amount', required=True),
        'qty'           : fields.integer('Qty', required=True),
        'subtotal'      : fields.float('Total', readonly=True),
    }

    def get_subtotal(self, cr, uid, ids, num1, num2, context=None):
        res = {}
        if num1 and num2:
            res['subtotal'] = num1 * num2
        return {'value': res}

In child_model I successfully multiplying "amount" and "qty" in event onchange get_subtotal, here is the xml :
<tree >
    <field name="item" />
    <field name="amount" on_change="get_subtotal(amount, qty)" />
    <field name="qty" on_change="get_subtotal(amount, qty)" />
    <field name="subtotal" />
</tree>

My question is how to calculate(sum) subtotal in child_model and store the value into grand_total field in parent_model using onchange event.
Need help please, Thanks

A: 1st: move everything to new api.
Add an onchange to the parent model hooked to line_ids, like:

@api.onchange('line_ids')
def _onchange_line_ids(self):


text:
Q: Time-control animations in a SpriteKit SKScene Using CALayer's beginTime we're able to scrub through animations.
Is there any way to achieve the same when using SpriteKit?
Is there anything similar for SKScene or SKView?


text:
Q: Is there any way I can set a number of times somethings loops in batch file Here is my code I want to know if I can set a number of times it loops
@echo off
:IDK
color a
:loop
echo derp
color 1a
echo derp
color 2a
echo derp
color 3a
echo derp
color 4a
echo derp
color 5a
echo derp
color 6a
echo derp
color 7a
echo derp
color 8a
echo derp
goto loop

A: You can do this with a FOR /L loop:
SET NumberOfTimes=10
FOR /L %%A IN (1,1,%NumberOfTimes%) DO (
    REM Enter code to repeat here.
)


text:
Q: javascript to show or hide a class according to a condition In this website : website
when you scroll down to the badge section,
I have  two conditions for badges :(below are the two badges)

Issue :
when the count (which appears on the upper right side of the badge as "10" and "0" here) is greater than "0" then "unlocked with check mark" should be displayed else "locked with cross" should be dispalyed and it should be faded as in hover effect we see normally.
javascript as suggested in the community : (in the fiddle its in the html section with a comment)

$.each($('.Portfolio-box'), function() {
  var count = $(this).children('has-badge').attr('data-count');
  if (data - count > 0) {
    $(this).children('ul.locked').hide();
    $(this).children('ul.unlocked').show();
  } else {
    $(this).children('ul.locked').show();
    $(this).children('ul.unlocked').hide();
  }
});

Fiddle link with the html and css.Please Ignore the images or proper alignment.Changes in the "lock and unlock" section of the code works perfect.
Link :https://jsfiddle.net/dkjz1z4k/
Its quite tricky for me.Kindly help,if anyone can.Thanks a lot.God bless.

A: Almost there, just a little tweak at the conditional if (count > 0) & .has-badge
$.each($('.Portfolio-box'), function() {
  var count = $(this).children('.has-badge').attr('data-count');
  if (count > 0) {
    $(this).children('ul.locked').hide();
    $(this).children('ul.unlocked').show();
  } else {
    $(this).children('ul.locked').show();
    $(this).children('ul.unlocked').hide();
  }
});

Working Fiddle


text:
Q: Php Javascript Google Maps Api Hi i have an web app where the result that php get from mysql db includes coordinates for google maps api. Following are my code on php
$businessMapper = new Application_Model_Mapper_BusinessMapper();
$biz = $businessMapper->searchBusinessByCityAndName($searchtext,$city);
$this->view->biz = $biz;

the result array are as follow:
[0] => Array
                    (
                        [business_name] => Madam Kwan's Restaurant KLCC
                        [business_url] => Madam-Kwan-s-Restaurant-KLCC
                        [reviews_num] => 2
                        [business_id] => 134
                        [rating] => 3
                        [business_phone] => 03-2026 2297
                        [business_add1] => Suria Klcc
                        [business_add2] => Jalan Ampang
                        [x] => 101.74357729999997
                        [y] => 3.1597723
                        [photo_url] => 201302051423582
                        [cat_name] => Restaurants
                    )

                [1] => Array
                    (
                        [business_name] => Spring Garden Restaurant
                        [business_url] => Spring-Garden-Restaurant
                        [reviews_num] => 2
                        [business_id] => 135
                        [rating] => 4
                        [business_phone] => 03-2166 9881
                        [business_add1] => Lot 413-414, Level 4
                        [business_add2] => Kuala Lumpur City Centre
                        [x] => 101.71465799999999
                        [y] => 3.1567893
                        [photo_url] => 201302011217282
                        [cat_name] => Restaurants
                    )

                [2] => Array
                    (
                        [business_name] => Hard Rock's Cafe Kuala Lumpur
                        [business_url] => Hard-Rock-s-Cafe-Kuala-Lumpur
                        [reviews_num] => 1
                        [business_id] => 137
                        [rating] => 2
                        [business_phone] => 03-2715 5555
                        [business_add1] => Ground Floor, Wisma Concorde
                        [business_add2] => Jalan Sultan Ismail
                        [x] => 101.70525199999997
                        [y] => 3.155552
                        [photo_url] => 201302011203172
                        [cat_name] => Restaurants
                    )

                [3] => Array
                    (
                        [business_name] => Sao Nam
                        [business_url] => Sao-Nam
                        [reviews_num] => 1
                        [business_id] => 141
                        [rating] => 4
                        [business_phone] => 03-2144 1225
                        [business_add1] => Anggun Boutique Hotel 7 & 9
                        [business_add2] => Tengkat Tong Shin
                        [x] => 101.70798279999997
                        [y] => 3.1463384
                        [photo_url] => 201302011122322
                        [cat_name] => Restaurants
                    )

                [4] => Array
                    (
                        [business_name] => Palate Palette
                        [business_url] => Palate-Palette
                        [reviews_num] => 1
                        [business_id] => 150
                        [rating] => 3
                        [business_phone] => 03-2142 2148
                        [business_add1] => 21 Jalan Mesui
                        [business_add2] =>
                        [x] => 101.70791299999996
                        [y] => 3.149042
                        [photo_url] => 201302011031132
                        [cat_name] => Restaurants
                    )

x and y value are used to map maps on google map api. In view template the google map api javascripts are as follow:
<script src="http://maps.google.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
 <script type="text/javascript">

    var locations = [
     {business_name1},{x1},{y1}
     {business_name2},{x2},{y2}
     etc...
    ];

    var map = new google.maps.Map(document.getElementById('map-container'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>

Now the issues are, how can i pass array of result from php to javascripts so that it can iterate through the x, y and business name and map out maps ?

A: I suppose the crude way to do it is to just output the variables into the correct place withing your JS script tags.
<script src="http://maps.google.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
 <script type="text/javascript">

    var locations = [
<?php

foreach($results as $biz){
     echo '{' . $biz['business_name'] . '},{ ' . $bix['x'] . '},{ ' . $biz['y'] . '}';
}
?>

    ];

That will replicate what you showed in your example, but you may need to watch out for how JS handles arrays (ie JS does not permit a trailing comma AFAIK)
Get say, 2 hardcoded JS results working on the page first, then use the echo method I showed to replicate what really does work.
If its JSON you want you might just output using the PHP json_encode() function by either selecting a sub-set of the results, or dropping the results you do not want (url, rating etc)
Depending on your situation you could store the results arrays, or json in an external .js file that way you can cache results too.

A: Use this,
    var locations = [
    <?php
    foreach($resultarray as $row){
    echo "{".$row['business_name']."},{".$row['x']."},{".$row['y']."}";
    }
    ?>
    ];


text:
Q: SwiftUI round button deforms when clicked I have created a round button with following code:
struct RoundButton : View {

    var value = "..."

    var body: some View {
        GeometryReader { geometry in
            Button(action: {}) {
                VStack {
                    Text(self.value)
                        .font(.headline)
                        .color(Color("NightlyDark"))
                    Text("MIN")
                        .font(.footnote)
                        .color(.white)
                }
                .frame(width: geometry.size.width, height: geometry.size.height)
            }
            .clipShape(Circle())
        }
    }
}

But when clicking the button, the shape gets deformed. Any idea why this happens ?

Same happens when i use .mask(Circle())
Is this a beta thing or normal behavior ? And does anyone maybe know a better way to create rounded buttons ?

A: what happens here is Button Considers all screen[width + height] as their frame by default.
so you have to set Button also.
I think it's the default behavior in watchOS
Here Your Code :
struct RoundButton: View {

    var value = "..."

    var body: some View {

        GeometryReader { geometry in

            Button(action: {}) {
                VStack {
                    Text(self.value)
                        .font(.headline)
                        .foregroundColor(Color("NightlyDark"))
                    Text("MIN")
                        .font(.footnote)
                        .foregroundColor(.white)
                }
                .frame(width: geometry.size.width, height: geometry.size.height)
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
                .clipShape(Circle())
        }

    }
}

Note: i'm using Xcode 11 Beta 4


text:
Q: Textual order of static variables and initialization order in Java I only spend five minutes to find a duplicate in SO.
My question is simple. Does the following code always work?
public class LexicalOrderStatic {
    private static Integer a1 = initA1();

    private static Integer a2 = initA2();

    private static Integer initA2(){
        return new Integer(5) / a1;
    }

    private static Integer initA1(){
        return new Integer(5);
    }

    public Integer getA1(){
        return new Integer(a2);
    }

    public static void main(String[] args) {
        LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
        System.out.println(lexLuthor.getA1());

    }
}

In java can I be sure that a1 is  always initialized before a2 ?
Thanks. Dw is ok if it is asked or if it is very simple.

A:
In java can I be sure that a1 is always initialized before a2 ?

Yes, because the specification (section 12.4.2) guarantees it (emphasis mine):

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

Note that constants are initialized earlier than non-constants (step 6 compared with step 9 quoted above).

A: Yes.
The chain of elements group ( name of the class, static attributes, instance attributes, static method, inner static block of code, etc) (1) is defined in compile time, not in run time: it has a deterministic behaviour.
When you run main, you have loaded at the first time LexicalOrderStatic and the static elements (attributes, methods) are loaded very quickly if this is the first loading.
If you load a second obejct of LexicalOrderStatic, the attribute are shared between the two instance.
Yu can see this statement in running this modified main
public static void main(String[] args) {
    LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
    System.out.println(lexLuthor.getA1());
    LexicalOrderStatic lexLuthor2 = new LexicalOrderStatic();
    System.out.println(lexLuthor2.getA1());
}

(1) before I referred to inheritance, but it'snt the situation, as pointed by the first comment


text:
Q: F# Script Ends Immediately After Execution (FSI) When I double-click .fsx files the script ends immediately after execution. There is no chance of interacting with the script or see what it does.
I can barely see one of the scripts create a WinForms window, but it quickly closes.
I have tried several default Run actions (including sending to a .cmd file):
"C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0\fsi.exe" "%1" %*
"C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0\fsi.exe" --quiet --exec "%1"

A: Both command lines you tried do indeed run the script and then exit. If you want to keep the REPL open to interact with the script, you need either --load:file.fsx or --use:file.fsx.

*

*--use:file.fsx does roughly the same as just running fsi and then pasting the contents of file.fsx into the REPL. So for example if the file just contains let x = 2 then you can immediately type x;; and it will be recognized. This is the one you want if your file contains a bunch of values, statements, types and/or modules.

*--load:file.fsx does roughly the same as just running fsi and typing #load "file.fsx". This means that values defined in this file will be in a separate namespace. This is the one you want if your file starts with a namespace or module declaration.


text:
Q: What code cost more at performance level Every body knows that today technology is low cost and many of us don't really care about it. So, take a look to this codes:
Approach #1
$Obj = new Obj();

if (!empty($val1)) {
    $Obj->setVal1($val1);
}

if (!empty($val2)) {
    $Obj->setVal2($val2);
}

if (!empty($val3)) {
    $Obj->setVal3($val3);
}

if (!empty($valN)) {
    $Obj->setValN($valN);
}

Approach #2
if (!empty($var1) && !empty($var2) && !empty($var3) && !empty($varN)) {
    $Obj = new Obj();

    if (!empty($val1)) {
        $Obj->setVal1($val1);
    }

    if (!empty($val2)) {
        $Obj->setVal2($val2);
    }

    if (!empty($val3)) {
        $Obj->setVal3($val3);
    }

    if (!empty($valN)) {
        $Obj->setValN($valN);
    }
}

In the first example we're creating and object and leave around if none of the values exists, in the second one we are checking first if the values exists and aren't empty and then create the object and set the values. From your perspective which one would be the best solution in performance levels? Which one would you write on your codes?
Note: N is not infinite

A: Usually it's not operations like empty() or isset() that wastes time. Instead higher memory usage and memory leakage tends to lead to more GC operations, new() performs initialization that takes time, I/O operations causes delay, and that is where you should do your improvement.
It can be very very complex if you want to discuss the time usage in detail: during compilation, runtime, whether the code will run at all etc.

A: that is depend on what you want,
the first code will set value if it's not empty even tho' another value might be empty,
but the second code would check all of the value first, so if one of the value is empty, it will never create the Obj.
that is a clear choice,
if you think all value is important and necessary, then go with the second code, if it's fine to leave another value empty and want to update any value that is not empty there's no point on using the second code


text:
Q: How to comment and uncomment code in a contextmenu I'm working on a contextmenu that shows on right-click using a mousedown event and 2 of my list for contextmenu are comment and uncomment with this code:
private void CommentMenuItemClick(object sender, EventArgs e)
    {
        rtb.SelectedText = "//" + rtb.SelectedText;
        lb.Hide();
    }

    private void UnCommentMenuItemClick(object sender, EventArgs e)
    {
        rtb.SelectedText = rtb.SelectedText.Replace("//", "");
        lb.Hide();
        rtb.SelectionColor = Color.Black;
    }

but for comment when I select all and there's diff rows of text (selectall) the output was:

but I should be like:

(Don't mind the highlighting just I want the // before the text).
How can I add // before diff rows of text? Also for uncomment is my code enough? Or is there more/better code for that?
Edit
void Parse()
    {
        String inputLanguage = "\n";

        // Foreach line in input,
        // identify key words and format them when adding to the rich text box.
        Regex r = new Regex("\\n");
        String[] lines = r.Split(inputLanguage);
        foreach (string l in lines)
        {
            ParseLine(l);
        }
    }

A: Your problem is that you are only adding '//' to the start of the text.
You need to parse the selected text for a new line char and then prepend a '//' to the start of each line.
String Builder is described here, it's in System.Text
something like this:
private void CommentMenuItemClick(object sender, EventArgs e)
{
    StringBuilder sw = new StringBuilder();

    string line;
    StringReader rdr = new StringReader(rtb.SelectedText);
    line = rdr.ReadLine();
    while(line != null)
    {
            sw.AppendLine(String.IsNullOrWhiteSpace(line) ? "//" : "" + line);
            line= rdr.ReadLine();
    }
    rtb.SelectedText = sw.ToString();
    lb.Hide();
}

A: what you need to do is replace the newline with "//"
so try this
rtb.SelectedText = "//" + rtb.SelectedText.Replace(System.Environment.NewLine, System.Environment.NewLine + "//")

A: You need to break it out by line and add "//" to the beginning of each.  Right now you're just adding "//" to be beginning of a single string composed of every line concatenated (hence the single "//").

A: First split each line. Then add // to the start of each line.
string[] lines = selected.Split('/n', '/r');
foreach (string l in lines)
{
    ParseLine(l);
}

Add to these lines and append them. The appended string is to be replaced with the selected text.
EDIT:
Commenting:
using System;

public class Test
{
    public static void Main()
    {
        string source = "comment me" + Environment.NewLine + "line two.";
        string[] lines = source.Split('\r', '\n');
        foreach (string line in lines)
        {
            Console.WriteLine("//" + line);
        }
    }
}

Output:
// comment me
// line two.

Online snippet: http://ideone.com/sGJNzr
Uncommenting:
using System;

public class Test
{
    public static void Main()
    {
        string source = "//uncomment me" + Environment.NewLine + "//line two.";
        string[] lines = source.Split('\r', '\n');
        foreach (string line in lines)
        {
            Console.WriteLine(line.Replace("//", ""));
        }
    }
}

Output:
uncomment me
line two.

Online snippet: http://ideone.com/roY0AK
You need to set source to rtb.SelectedText


text:
Q: VSCode show error with interface extended I have a error with VSCode. It show me an error when I use a new method for "string":

When I run with npx ts-node, there is not error. How fix VsCode?
I look for VSCode not to show those errors.
Here the code:
//types.d.ts
interface String {
    test: () => string
}

//tscongig.json
{
    "compilerOptions": {
        "target": "ESNext",
        "moduleResolution": "NodeNext",
        "baseUrl": ".",
        "paths": {
            "@tools/*": [
                "tools/*"
            ],
            "@core/*": [
                "core/*"
            ]
        }
    },
    "files": [
        "types.d.ts"
    ]
}

//index.ts
String.prototype.test = () => 'hola!'

console.log('prueba'.test())

And a settings file for VSCode:
//settings.json
{
    "typescript.tsdk": "node_modules\\typescript\\lib"
}

I am executing with npx ts-node .

A: First, extending the String prototype is bad practice and you should try to avoid doing that at all costs.
The error is genuine and correct. You can execute the program because it is valid JavaScript code and ts-node does transpilation, but you will not be able to compile your program to JS.
Try compiling with your code with tsc index.ts and you will get the same errors, which you will need to fix:
index.ts:1:18 - error TS2339: Property 'test' does not exist on type 'String'.

1 String.prototype.test = () => 'hola!'
                   ~~~~

index.ts:3:22 - error TS2339: Property 'test' does not exist on type '"prueba"'.

3 console.log('prueba'.test())


text:
Q: Web development with ESN Planet, how does it work? I'm starting a new job soon, in web-app development. While I'm experienced with programming, my background is primarily in game development and desktop/server applications. I have very little experience from modern web app development. Anyway...
Our primary development tool is going to be something called ESN Planet, which I've not heard about before. Their website is not very specific about its features, and it seems unlikely for one to get a trial invitation ("We have been getting lots of applications, so please try to be as detailed as possible when applying for an invite below.").
Is anyone using this tool, and can explain what kinds of skills are involved in development of apps using this tool? Should I learn Python, JavaScript, CSS, or something else? All of the above? What is the workflow like for a developer? Will I need modern HTML skills?
I'd like to prepare for this job, but not sure what to expect and prepare for. My contact with the company is not a developer, so I figured I would ask here.

A: I saw a talk by the boss of the company that developed this stuff, at the Europython conference this year. It was ostensibly about the custom IDE that they created to develop in it, but also touched on the Planet system itself. It seems like a pretty run-of-the-mill MVC framework, as far as I can tell.
As far as what to learn, you will definitely need Python. Normally in web development you also need HTML, CSS and Javascript as well - but some frameworks abstract a lot of that away from you, to a greater or lesser extent. Impossible without knowing more about the framework to tell whether this is one that does. And it also depends on the way the company you're working for is set up - some have separate front-end teams that deal with that side of things, leaving the Python developers to just manage the server-side stuff.

A: For what it's worth, ESN Planet has been used to build Battlelog (http://battlelog.battlefield.com), the web platform for stats tracking and web launching of Battlefield 3.


text:
Q: Input filter/val output escape zf2 correctly? Do I correctly understand, that I need to escape in view smth like this:

        <?php $escaper = new Zend\Escaper\Escaper('utf-8'); ?>
        <input type="text" placeholder="<?php echo $escaper->escapeHtml($this->languageText('TEXT_SEARCH_OUR_SITE',"Search Our Site"));
       ?>" name="query" id="query" />

And how correctly filter, or validate in controller this line:
$this->view->phrase = $this->getRequest()->getParam('phrase','');

A: How to escape something correctly depends on the context. In your example the variable is being output in a HTML attribute, so you should use escapeHtmlAttr:
<input type="text" placeholder="<?php echo $escaper->escapeHtmlAttr($this->languageText('TEXT_SEARCH_OUR_SITE',"Search Our Site"));
   ?>" name="query" id="query" />

There is a list of escape functions in the overview of the component.
As for what you need to do in the controller, the answer is: probably nothing, but it depends what you are going to use "phrase" for.


text:
Q: Nano and Midnight Commander don't work on Docker for Windows beta I use Docker for Windows 10. Arrow controls don't work on nano, vim and midnight commander. Have encoding problems

A: With mc you can press F9 to select top menu. Then navigate to Options->Learn keys using only letter keys. The needed key will be highlighted. So it will be "F9 o k" and then follow the instructions. Worked for me.

A: Try to disable legacy mode in powershell (Powershell > Properties > "Options" tab) if you already have updates installed (enables new features described here).
Works fine without encoding problems and navigation glitches.
Please, view screenshot: Alpine with installed Midnight Commander in Windows Powershell

A: Install and run bash, run it and than run mc from bash.
apk update && apk add bash mc
bash
mc

Encoding problem can be solved in Options->Appearance in mc itself.


text:
Q: Tiny space between image and its container The image fills its container but it has a small red gap around it. Please see a sample code or image below. I would like the image to fill the container without the tiny space. Can it be fixed or is it related to the browser's rendering? Thanks.

div {
  border-radius: 100%;
  height: 64px;
  margin: 0 auto;
  width: 64px;
  background-color: red;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
}

A: Yes, in Chromium on Linux i can see the tiny red space.
I assume it's a clipping error.
Any way to include the image as background-image of the div? The unwanted space disappears on my browser this way.

div {
    border-radius: 100%;
    height: 64px;
    margin: 0 auto;
    width: 64px;
    background-color: red;
    overflow: hidden;
    background-image: url(https://www.postavy.cz/foto/doge-foto.jpg);
    background-size: contain;
}

But, why have the red background of the div anyways if the image fills it out?


text:
Q: PHP - alpha sort lines from several files in one directory and save them to files of "x" lines max in alpha named folders This below goes through files in a directory, reads them and saves them in files of 500 lines max to a new directory.
This works great for me (thanks Daniel) but, I need a modification.
I would like to save to alpha num based files.
First, sort the array alpha numerically (already lowercase) would be the first step I assume.
Grab all of the lines in each $incoming."/.txt" that start with "a" and put them into a folder at $save500."/a" but, a max of 500 lines each.
(I guess it would be best to start with the first at the top of the sort so "0" not "a" right?)
All the lines that start with a number, go into $save500."/num".
None of the lines will start with anything but a-z0-9.
This will allow me to search my files for a match more efficiently using this flatfile method. Narrowing it down to one folder.
$nextfile=0;
    if (glob("" . $incoming . "/*.txt") != false){
     $nextfile = count(glob("" . $save500 . "/*.txt"));
     $nextfile++;
    }
    else{$nextfile = 1;}
    /**/
     $files = glob($incoming."/*.txt");
     $lines = array();
     foreach($files as $file){
     $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
    }
     $lines = array_unique($lines);
    /*this would put them all in one file*/
    /*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
    /*this breaks them into files of 500*/
     foreach (array_chunk($lines, 500) as $chunk){
     file_put_contents($save500 . "/" . $nextfile . ".txt", implode("\n", $chunk));
     $nextfile++;
    }

Each still need to be in a max of 500 lines.
I will graduate to mysql later on. Only been doing this a couple months now.
As if that is not enough. I even thought of taking the first two characters off. Making directories with subs a/0 thru z/z!
Could be the wrong approach above since no responses.
But I want a word like aardvark saved to the 1.txt the a/a folder (appending). Unless 1.txt has 500 lines then save it to a/a 2.txt.
So xenia would be appended to the x/e folder 1.txt file unless there are 500 lines so create 2.txt and save it there.
I will then be able to search for those words more efficiently without loading a ton into memory or looping through files /lines that won't contain a match.
Thanks everyone!

A: I wrote some code here that should do what you're looking for, it's not a perfomance beauty but should do the job. Try it in a safe environment, no guarantee for any data-loss ;)
Comment if there are any errors, it's pretty late here ;) I have to get some sleep ;)
NOTE: This one only works if every line has at least 2 characters! ;)
$nextfile=0;

if (glob("" . $incoming . "/*.txt") != false){
  $nextfile = count(glob("" . $save500 . "/*.txt"));
  $nextfile++;
}
else
{
  $nextfile = 1;
}

$files = glob($incoming."/*.txt");
$lines = array();
foreach($files as $file){
  $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}

$lines = array_unique($lines);

/*this would put them all in one file*/
/*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
/*this breaks them into files of 500*/

// sort array
sort($lines);

// outer grouping
$groups     = groupArray($lines, 0);
$group_keys = array_keys($groups);

foreach($group_keys as $cKey) {
  // inner grouping
  $groups[$cKey] = groupArray($groups[$cKey], 1);

  foreach($groups[$cKey] as $innerKey => $innerArray) {
    $nextfile = 1;
    foreach(array_chunk($innerArray, 500) as $chunk) {
      file_put_contents($save500 . "/" . $cKey . "/" . $innerKey . "/" . $nextfile . ".txt", implode("\n", $chunk));
      $nextfile++;
    }
  }

}

function groupArray($data, $offset) {

  $grouped = array();

  foreach($data as $cLine) {
    $key = substr($cLine, $offset, 1);
    if(!isset($grouped[$key])) {
      $grouped[$key] = array($cLine);
    }
    else
    {
      $grouped[$key][] = $cLine;
    }
  }

  return $grouped;
}


text:
Q: C++ type conversion from a variable to a reference When doing a type conversion from a variable to a reference, like:
float f = 1.0f;
int a = (int&) f;
std::cout << a;

Why do I get the actual bit-representation of the float value (and not the numeric value).

A: Your code is undefined behavior, technically speaking. Your C-style cast does a reinterpret_cast which isn't defined for convering a float lvalue to int&. Maybe you just wanted to cast to an int?

A: Because reference in C++ means "another name for". So when you cast something to a reference you just give it another name, and not perform a value conversion from floats to integers.

A: Why are you converting a variable to a reference and then storing it in a variable?


text:
Q: Simpler definition for kernel, image, and rank of transformation matrix? I'm a beginner at linear algebra and I keep running into such complicated definitions for kernel, image, and rank of a matrix and I would appreciate it if someone could simplify the definitions more into English rather than math symbols. I generally know how to find these qualities but...what am I finding? Thanks in advance!

A: Viewing a matrix as a function (given by multiplying by the matrix), the definitions translate to:

*

*The kernel is everything that is mapped to zero by the function.

*The image is everything that comes out of the function.

*The rank is the dimension of the image.

For the latter, you should first verify that the image of a matrix is a vector space.

A: Without symbols, the definitions become unnecessarily lengthy! But, per request:
(i) The kernel of a linear map is the set of all points of the domain of the linear map such that the linear map assigns the zero of its codomain to each of the points. (cf. The kernel of a linear map $T$ is the set of all points $x$ of the domain of $T$ such that $T(x) = 0$).
(ii) The image (range, more properly, used hereafter) of a linear map is the set of all points of the codomain of the linear map such that the linear map assigns each of the points to at least one point of the domain of the linear map. (cf. The range of a linear map $T$ is the set of all points $y$ of the codomain of $T$ such that $y = T(x)$ for some $x$ in the domain of $T$.)
(iii) The rank of a linear map is the dimension of the range of the linear map.
Of course we can simplify (iii) by assigning a symbol to the range of $T$.
Moreover, using the language of set theory we can further simplify (i) and (ii); for example: let $V, W$ be vector spaces; let $T: V \to W$ be linear. Then the kernel of $T$ is defined as the set
$\{ x \in V \mid T(x) = 0_{W} \}$.


text:
Q: Torsion of elliptic curves and abelian extensions Let $L/K$ be an abelian $p$-extension of number fields and $E$ be an elliptic curve over $\Bbb Q$.
If $E[p](K)=0$, does it follow that $E[p](L)=0$ ? The converse is obviously true, but I don't have any reference for my problem.


text:
Q: in react native's react-native-timeline-flatlist in imageUrl image is not showing Hi I am trying to applying react-native-timeline-flatlist in my screen
so the problem is that when I put any live image url from any website the image are showing up but when I want to show image from my react native directory then image are not showing up , please tell me where is the problem occuring
here is my data
const [data,setData] = useState([
      {
        time: '1st Week',
        title: 'Your baby is still taking shape.',
        description: ' ',
        lineColor:'#009688',
        icon: require('../../assets/icon.png'),
        imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240340/c0f96b3a-0fe3-11e7-8964-fe66e4d9be7a.jpg',
      },
      {
        time: '2nd Week',
        title: 'Your baby is still taking shape.',
        description: ' ',
        icon: require('../../assets/icon.png'),
        imageUrl: '../../assets/43/2.png'
      },
      {
        time: '3rd Week',

        title: 'Your baby is still taking shape.',
        description: ' ',
        icon: require('../../assets/icon.png'),
        imageUrl: '../../assets/43/3.png'
      },
     ]);

in this data only first image is showing while another 2nd and 3rd image is not showing  up

A: try with require
const [data,setData] = useState([
      {
        time: '1st Week',
        title: 'Your baby is still taking shape.',
        description: ' ',
        lineColor:'#009688',
        icon: require('../../assets/icon.png'),
        imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240340/c0f96b3a-0fe3-11e7-8964-fe66e4d9be7a.jpg',
      },
      {
        time: '2nd Week',
        title: 'Your baby is still taking shape.',
        description: ' ',
        icon: require('../../assets/icon.png'),
        imageUrl: require('../../assets/43/2.png')'
      },
      {
        time: '3rd Week',

        title: 'Your baby is still taking shape.',
        description: ' ',
        icon: require('../../assets/icon.png'),
        imageUrl: require('../../assets/43/3.png')
      },
     ]);


text:
Q: Two "where" statements with one table doesn't work without subqueries I've got a table with 3 columns: name, lastname and date.
For example:
Name Lastname Date
Ab   Ab       2008-07-01
Ab   Ab       2006-06-23
Kb   Kb       2008-07-01
Kb   Kb       2007-06-03

I need to find the names of those who are assigned to 2008-07 and not to 2006-06. So for this example the output will be:
Name Lastname Date
Kb   Kb       2008-07-01
Kb   Kb       2007-06-03

My code:
select  Name, Lastname, YEAR(date), MONTH(date) from MyTable
where (YEAR(date) = 2008 AND MONTH(date) = 7) AND (YEAR(date) <> 2006 AND MONTH(date) <> 6)

It doesn't work well, because really nothing happen (it "blocking" for example all names with month = 6). I try to do it with UNION statement, but nothing work well.
Note, I need to do this without using a subquery.

A: I think you want a group by and a having clause, because you are looking for multiple rows:
select  Name, Lastname
from MyTable
group by Name, LastName
having
    sum(case when YEAR(date) = 2008 AND MONTH(date) = 7 then 1 else 0 end) > 0 and
    sum(case when YEAR(date) = 2006 AND MONTH(date) = 6 then 1 else 0 end) = 0;

Each condition in the having clause counts the number of rows that match.  The > 0 means there is at least one.  The = 0 means there are none.  This generalizes easily to more conditions.

A: SELECT
    t.*
FROM (
    SELECT
        Name,
        LastName
    FROM #Temp
    GROUP BY Name, LastName
    HAVING
        SUM(CASE WHEN YEAR([Date]) = 2008 AND MONTH([Date]) = 7 THEN 1 ELSE 0 END) = 1
        AND SUM(CASE WHEN YEAR([Date]) = 2006 AND MONTH([Date]) = 6 THEN 1 ELSE 0 END) = 0
)x
INNER JOIN #Temp t
    ON t.Name = x.Name
    AND t.LastName = x.LastName

RESULT
Name                 LastName             Date
-------------------- -------------------- ----------
Kb                   Kb                   2008-07-01
Kb                   Kb                   2007-06-03

A: You can use a sequence of outer joins to do it with no subquery.
SELECT c1.*
FROM Customers c1
LEFT OUTER JOIN Customers c2 ON
    c1.Name = c2.Name AND c1.LastName = c2.LastName
    AND YEAR(c2.date) = 2006 AND MONTH(c2.date) = 6
LEFT OUTER JOIN Customers c3 ON
    c1.Name = c3.Name AND c1.LastName = c3.LastName
    AND YEAR(c3.date) = 2008 AND MONTH(c3.date) = 7
WHERE
    c2.date IS NULL
    AND c3.date IS NOT NULL

You're asserting that the first join fails, but the second join succeeds.
The results are
Kb Kb 7/1/2008 12:00:00 AM
Kb Kb 6/3/2007 12:00:00 AM


text:
Q: Laravel Queue, Jobs, Redis - falling back to sync connection i'm using Laravel 5.4, i'm trying to set a queued job.
Here is my config:
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

and my config/queue.php
'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'default',
        'retry_after' => 90,
    ],

    'emails' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'emails',
        'retry_after' => 90,
    ],

Here is my code
 public function handle()
 {
    dd($this->job->getConnectionName());
 }

My problem, when i change sync the QUEUE_DRIVER, i get "sync"
But when i change redis , i get any thing.


text:
Q: Cant save configuration in backend When I edit something in system -> configuration, it doesn't matter where, for example i want to edit the store contact address, it doesnt save my edit.
I can change and add products but I cant edit anything in the configuration.
The System log and exception log are empty and no errors are shown.
Is says "The configuration has been saved."
Does someone know how to fix this.
Magento version: 1.9.3.6
EDIT:
I have noticed that this problem has occurred when we applied patch SUPEE 11219 When i revert that patch we can save config in the backend again.
Any idea?

A: You need to check "max_input_vars" in your php configuration. Try to increase "max_input_vars" value and test.
ini_set('max_input_vars','5000' );

You need to set it with php.ini or .htaccess file.

A: navigate to
app/code/core/Mage/Core/etc/config.xml
Find
<log>
    <active>0</active>
    <file>system.log</file>
    <exception_file>exception.log</exception_file>
</log>

Replace
<log>
    <active>1</active>
    <file>system.log</file>
    <exception_file>exception.log</exception_file>
</log>

Note: this is not a solution this will help you in getting the error then once you know the error kindly update the question with the error details

A: In your magento root folder, there is index.php file,
In that file the code like this one
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}

#ini_set('display_errors', 1);

Form that code, remove the # from this line :
ini_set('display_errors', 1);

So your code look like this one:
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
        Mage::setIsDeveloperMode(true);
    }

ini_set('display_errors', 1);

Now open the admin and try to save the config, this will show real error if there anythnig.


text:
Q: Django render individual form field not showing I'm trying to display individual fields of the Django form one by one as I want to change certain properties.
This is my forms.py. I've reduced it to just one field for clarity.
from django import forms

class NameForm(forms.Form):
    name = forms.CharField(max_length=100)

It works perfectly if I render the form completely. My HTML code -
<form style="text-align:center; padding-bottom: 2%" action="/contact/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
</form>

The page source for the above code comes like this -

Name: <input id="id_name" maxlength="100" name="name" type="text" />

The problem comes when I try to render individual field like using {{ form.name }} instead of {{form}}. The page source for this shows empty. No HTML is formed.
I also tried -
{% for field in form %}

        {{ field }}

{% endfor %}

And the HTML rendered for this is like -

                    <

                    p

                    >

                    <

                    l

                    a

                    b

                    e

                    l

                    f

                    o

                    r

I haven't posted the full HTML source but seems like the loop is printing each character of the HTML code rendered from the form as if we combine the first few characters printed it forms HTML like -

and so on...
Please explain why this is happening.

A: Please check what are you returning from your view.
This might happen if your view is returning the form.as_p.
This can be corrected by returning the form only.
It should work! If it still doesnt work, post views and entire template.

A: If you know the name of the field, you can render it individually like that :

    {{ form.myfield.errors }}
    Label for myfield :
    {{ form.myfield }}

(you can also use {{ form.myfield.label_tag }} for the label if you defined it in the Form class)
Else, if you want to have a for you can do it like that :
{% for field in form %}

        {{ field.errors }}
        {{ field.label_tag }} {{ field }}

{% endfor %}

It works well for me. If you still have a issue, it must be in the rest of your code I think. Show the enter template if so :)


text:
Q: SP2-0310: unable to open file "LOGIN.SQL" from Oracle DB 18c in Docker for Windows container In Docker for Windows I installed an Oracle DB 18c XE Linux Docker container by the books:

*

*Downloaded official sources (from https://github.com/oracle/docker-images)

*Created an image from it

*Created a container:
docker run --name $containerName -d -p 15210:1521 -e ORACLE_PWD=$dbPassword -v $dbVolume:/opt/oracle/oradata 'oracle/database:18.4.0-xe'

When I open SQL*Plus within the container, everything works fine:
> docker exec -it DevDB sqlplus sys/pwd@//localhost:1521/xe as sysdba

SQL*Plus: Release 18.0.0.0.0 - Production on Fri May 21 19:47:10 2021
Version 18.4.0.0.0

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

Connected to:
Oracle Database 18c Express Edition Release 18.0.0.0.0 - Production
Version 18.4.0.0.0

SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT
SQL>

In my Windows host I installed SQLPlus Instant Client. When I run SQL*Plus from there, I get a warning message telling me that "LOGIN.SQL" cannot be opened.
However, I seem to be able to run queries:
> sqlplus sys/pwd@//localhost:15210/xe as sysdba

SQL*Plus: Release 18.0.0.0.0 - Production on Fri May 21 21:34:58 2021
Version 18.5.0.0.0

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

Connected to:
Oracle Database 18c Express Edition Release 18.0.0.0.0 - Production
Version 18.4.0.0.0

SP2-0310: unable to open file "LOGIN.SQL"
SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT
SQL>

What is causing this warning message? How can I get rid of it?

A: After some more testing I now found the answer to my issue:
Apparently, the reported error is a glitch in the 18.5.0.0 release of SQL*Plus.
I just updated SQL*Plus to 19.11.0.0, and the warning message is gone:
> sqlplus sys/pwd@//localhost:15210/xe as sysdba

SQL*Plus: Release 19.0.0.0.0 - Production on Fri May 21 21:53:11 2021
Version 19.11.0.0.0

Copyright (c) 1982, 2020, Oracle.  All rights reserved.

Connected to:
Oracle Database 18c Express Edition Release 18.0.0.0.0 - Production
Version 18.4.0.0.0

SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT
SQL>


text:
Q: "GlassFish Server, deploy, null, false" error I'm having problems with Glassfish 4.0 + Netbeans 7.4...
whenever i try to run my project i get this erros:
ant -f D:\\Projetos\\NetBeans\\Sullimar -Dbrowser.context=D:\\Projetos\\NetBeans\\Sullimar\\web\\index.html -DforceRedeploy=false -Dclient.urlPart=/index.html -Ddirectory.deployment.supported=true -Dnb.wait.for.caches=true -Dnb.internal.action.name=run.single run
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
In-place deployment at D:\Projetos\NetBeans\Sullimar\build\web
GlassFish Server, deploy, null, false
D:\Projetos\NetBeans\Sullimar\nbproject\build-impl.xml:1045: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 0 seconds)

and my glassfish server output:
Informations:   visiting unvisited references
Informations:   Created HTTP listener http-listener-1 on host/port 0.0.0.0:2869
Informations:   Created HTTP listener http-listener-2 on host/port 0.0.0.0:8181
Informatios:   Created HTTP listener admin-listener on host/port 0.0.0.0:4848
Grave:   Cannot start container web, exception: A MultiException has 2 exceptions.  They are:
1. java.lang.IllegalArgumentException: virtual server server has an invalid docroot C:\Users\Thaís\GlassFish_Server\glassfish\domains\domain1/docroot
2. java.lang.IllegalStateException: Unable to perform operation: post construct on com.sun.enterprise.web.WebContainer

Grave:   Aborting, Failed to start container com.sun.enterprise.web.WebContainer
Grave:   Exception while deploying the app [Sullimar]
Grave:   Exception during lifecycle processing
java.lang.Exception: Aborting, Failed to start container com.sun.enterprise.web.WebContainer
    at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:736)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:374)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)

Grave:   Exception while deploying the app [Sullimar] : Aborting, Failed to start container com.sun.enterprise.web.WebContainer

What do I do to fix these errors? In my Services tab I can access my databases, and my dabatase connection to my Sullimar database works fine (I can view the data...) so I can't underastand the problem.
Thanks a million!

A: the error is easy, you need delete  in WEB-INF/web.xml

A: Take a look at your server.log file.
It's located under /$YouGlassfishRoot/glassfish/domains/$Domain/logs/server.log
The problem is probably your server's jdk version.

A: Got the S.O.B to work. Turns out Windows firewall was blocking Netbeans (as it should), which for whatever reason requires incoming connections for deployment.
Try create a rule allowing inbound TCP for C:\program files\netbeans 8.0\bin\netbeans64.exe

A: I had similar problem on Windows 7, for you it's to late, but it could help somebody else. First there was no server.log file in GLASSFISH_INSTALATION_DIRECTORY\glassfish\domains\domain1\logs and the reason was that my user didn't have rights to write anywhere in GLASSFISH_INSTALATION_DIRECTORY (glassfish was installed with netbeans )
after fixing that I found "...Invalid resource : jdbc/..." exception and fix for that can be found at this webpage https://netbeans.org/kb/docs/web/jsf20-crud.html under Troubleshooting paragraph


text:
Q: minify code creates syntax problem python I am trying to minify code to save stress on my hard disk computer. This caused syntax error. I am not sure if token or comment is illegal and raising the error.
The original version worked. However, when I have try to unminify the minified original, it raises an error.
CODE (minified)
""" Title:TicTacToeAuthor:GNDate:12Version:1""";player_symbol='X';ai_symbol='O';board=[[' ',' ',' '],[' ',' ',' '],[' ', ' ',' ']];while True: print("{} {} {}\n{} {} {}\n{} {} {}\n".format(board[0][0],board[0][1],board[0][2],board[1][0],board[1][1],board[1][2],board[2][0],board[2][1],board[2][2]));row=input('row? ');

Expected Output: 'row?'
But the actual output is Файл
Syntax Error: invalid syntax: **C:\Users\Administrator\Desktop\gn\GN.py**, line 1, pos 136, строка 1
"""

A: The while keyword has to be at the beginning of the line.


text:
Q: disable autoplay on mobile devices I would like to disable the autoplay of audio streaming from my website, the problem is that mobile devices do not work the autoplay and the button that activates the event is paused (as if you were playing audio). I wish that instead of the pause button play button appears and I think it best to disable the autoplay on mobile devices.
<script type="text/javascript">
   var audio, playbtn, mutebtn, seek_bar;
function initAudioPlayer(){
    audio = new Audio();
    audio.src = "http://listen.streaming";
    audio.loop = true;
    audio.play();
    // Set object references
    playbtn = document.getElementById("playpausebtn");
    // Add Event Handling
    playbtn.addEventListener("click",playPause);
    // Functions
    function playPause(){
        if(audio.paused){
            audio.play();
            playbtn.style.background = "url(pausa-sobre.png) no-repeat";
        } else {
            audio.pause();
            playbtn.style.background = "url(play-sobre.png) no-repeat";
        }
    }

}
window.addEventListener("load", initAudioPlayer);

    </script>

html
<button id="playpausebtn"></button>

CSS
    button{ border:none; cursor:pointer; outline:none; }
button#playpausebtn{
    background:url(pausa-sobre.png) no-repeat;
    width:68px;
    height:68px;
}

A: You can use the RegExp provided by http://detectmobilebrowsers.com/ and do wrap the window.addEventListener("load", initAudioPlayer); into:
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4)))) {
    window.addEventListener("load", initAudioPlayer);
}

Or you can simply use a library that offers more than just checking, like Mobile Detect https://github.com/hgoebl/mobile-detect.js

A: A possible solution would be to check the paused status of the audio after you run the play() method:

*

*If it is false: that means that the audio started.

*If it is true: it means that the audio didn't start (and you'll have to show the play button instead of the pause button)

This would be the code (replace the images for the right ones):
var audio, playbtn, mutebtn, seek_bar;
function initAudioPlayer(){
    audio = new Audio();
    audio.src = "http://www.w3schools.com/html/horse.mp3";
    audio.loop = true;
    audio.play();

    // Set object references
    playbtn = document.getElementById("playpausebtn");

    // if it's not playing after calling play(), show the other icon
    if(audio.paused) {
        playbtn.style.background = "url(http://www.clker.com/cliparts/e/5/a/2/1206570547560908424akiross_Audio_Button_Set_4.svg.thumb.png) no-repeat";
    }

    // Add Event Handling
    playbtn.addEventListener("click",playPause);
    // Functions
    function playPause(){
        if(audio.paused){
            audio.play();
            playbtn.style.background = "url(http://www.clker.com/cliparts/c/e/f/2/1206570536270669982akiross_Audio_Button_Set_1.svg.thumb.png) no-repeat";
        } else {
            audio.pause();
            playbtn.style.background = "url(http://www.clker.com/cliparts/e/5/a/2/1206570547560908424akiross_Audio_Button_Set_4.svg.thumb.png) no-repeat";
        }
    }

}
window.addEventListener("load", initAudioPlayer);

You can see it working on this JSFiddle: http://jsfiddle.net/LbnLu89d/3/


text:
Q: Change the database's table in hive or hcatalog Is there a way to change the database's table in hive or Hcatalog?
For instance, I have the table foo in the database default, and I want to put this table in the database bar. I try this, but it doesn't work:
ALTER TABLE foo RENAME TO bar.foo

Thanks in advance

A: AFAIK there is no way in HiveQL to do this. A ticket was raised long back though. But the issue is still open.
An alternate could be to use the EXPORT/IMPORT feature provided by Hive. With this feature we can export the data of a table to a HDFS file along with the metadata using the EXPORT command. The data is stored in JSON format. Data once exported this way could be imported back to another database (even another hive instance) using the IMPORT command.
More on this can be found on the IMPORT/EXPORT MANUAL.
HTH

A: thanks for your response. I found an other mean to change the database
USE db1; CREATE TABLE db2.foo like foo


text:
Q: $X$ standard normal. $Y=X^2$. Find the pdf of $Y$ and covariance between $X$&$Y$ Let $X$ be standard normal random variable, i.e., $X ∼ N(0, 1)$. Consider transformed random
variable: $Y = X^2$.
(a) Find the probability density function of $Y$.
(b) Find the covariance between $X$ and $Y$.
I'm new to probability and don't really get yet transformation of random variables. If anyone could help me with this one I'd much appreciate.
My work: $F_Y(y)=P(Y\leq y)=P(X^2\leq y)=P(X\leq\sqrt{y})=F_X(\sqrt{y})=\int_{-\infty}^\sqrt{y}\frac{1}{\sqrt{2\pi}}e^{-t^2/2}\,dt$ that's where I'm stuck.
Edit: Is the correlation 0 because of the odd-moments popping in the equation?

A: You are close on the CDF. The only issue is that you need an absolute value: $$ F_Y(y) = P(|X|\le \sqrt{y}) = P(X\le \sqrt{y})-P(X\le -\sqrt{y}) = F_X(\sqrt{y})-F_X(-\sqrt y).$$ This would be an integral $\int_{-\sqrt y}^{\sqrt y}$ instead of $\int_{-\infty}^{\sqrt{y}}.$
In order to get the PDF, you differentiate the CDF. This can either be done from the integral using the fundamental theorem of calculus and the chain rule, or, equivalently, using the chain rule and the fact that $f_X=F_X'.$ So you have $$ f_Y(y) = \frac{d}{dy}(F_X(\sqrt y)-F_X(-\sqrt{y}) = \frac{1}{2\sqrt{y}}(f_X(\sqrt{y})+ f_X(-\sqrt{y})) = \frac{1}{\sqrt{y}}\frac{e^{-y/2}}{\sqrt{2\pi}}$$ for $y>0$.


text:
Q: Criteria API with ODER BY CASE expression throws SQLException: ORA-12704 "character set mismatch" I am using criteria API to create my query. Because of special sorting algorithm I use an "order by case" expression. My Unit-Tests using in memory H2 DB and are working. In the development stage we are using Oracle DB and there I get an "SQLException: ORA-12704" when executing the query.
Assume my root entity 'Foo' has a Set of 'Bar's. Bar has an attribute 'myOrderByColumn'
public class Bar {
    ...

    @NotBlank
    @javax.validation.constraints.Size(max = 255)
    @Column(name = "MYORDERBYCOL")
    private java.lang.String myOrderByColumn;

    ...
}

Here is the code which produces the exception. It creates the Order object later used in CriteriaQuery.orderBy(..)
   private Order buildOrderBy(final CriteriaBuilder cb,
         final Root<Foo> rootEntity,
         final List<String> somehowSpecialOrderedList) {

      final Expression<String> orderByColumn =
            rootEntity.join(Foo_.bars, JoinType.LEFT).get(Bars.myOrderByColumn);

      CriteriaBuilder.SimpleCase<String, Integer> caseRoot = cb.selectCase(orderByColumn);

      IntStream.range(0, somehowSpecialOrderedList.size())
            .forEach(i -> caseRoot.when(somehowSpecialOrderedList.get(i), i));

      final Expression<Integer> selectCase = caseRoot.otherwise(Integer.MAX_VALUE);

      return cb.asc(selectCase);
   }

I took a look into the Oracle DB. The type of the column 'myOrderByColumn' ist NVARCHAR2(255).
I guess the problem here ist that the "when" part in the SQL query must match with the type of the 'MYORDERBYCOL' database column, which is NVARCHAR2. In Java I use Strings. Probably Hibernate is not casting this correctly!?
I can produce the database ORA-12704 error by
SELECT FOO.id
FROM FOO
LEFT OUTER JOIN BAR ON FOO.id = BAR.fk_id
ORDER BY
   CASE FOO.myorderbycol
      WHEN '20' THEN 1
      ELSE           2
   END ASC;

This SQL works
SELECT FOO.id
FROM FOO
LEFT OUTER JOIN BAR ON FOO.id = BAR.fk_id
ORDER BY
   CASE FOO.myorderbycol
      WHEN cast('20' as NVARCHAR2(255))
      THEN 1ELSE           2
   END ASC;

How do I have to adjust my oder by case expression with criteria API so that the query is working with any database? (must later work with at least H2, Oracle, MS SQL, PostgreSQL)

A: Looks like an Oracle issue to me. Which version are you using? You can try a different approach which might work.
  CriteriaBuilder.SearchedCase<Integer> caseRoot = cb.selectCase();

  IntStream.range(0, somehowSpecialOrderedList.size())
        .forEach(i -> caseRoot.when(cb.equal(orderByColumn, somehowSpecialOrderedList.get(i)), i));

  final Expression<Integer> selectCase = caseRoot.otherwise(Integer.MAX_VALUE);


text:
Q: Employees for Merchant in E-commrece? I have an e-commerce project that contains there type of user admins,merchants and normall user in merchant section I need to make employees for merchant, like each merchant will have many employees with him and I'm confused between two structures for database first one:
In the same merchants table add another column named ( merchant_id ) it belongs to the parent of merchant.
id - name - email - password - merchant_id

The second:
Make a separate table like ( employees ) that the merchant has many employees.
id- name- email - password - merchant_id

The problem that I'm confused with is like when I give the employees permissions!
please guy's any suggestions for something like this probelm ?

A: I created a diagram to show my point of view. Please consider the following image:

Explaining the diagram:

*

*A merchand hasMany Employees;

*An employee belongsTo a merchand (foreign key merchand_id to tbl_merchands);

*An employee belongsTo a permission (foreign key permission_id to tbl_permissions);

*A permissions hasMany employees;

Code the relations in the models and you are good to go. To validate if a user has permission to access some Route(), you can use a middleware.
NOTE: I created a tbl_permissions because of your request. Maybe I would rename to tbl_groups (admins, users, etc) and use the table globally.
Hope it guides you. Regards!
COMMENT #1:
To control the page access you may use a middleware. You can create a table for products with foreign keys to merchand_id and employee_id. To get products associated to an employee, you need to create a Model plus the relation to the products. To retrive the data, do Employees::find($employee_id)->products. Hope you know how to code in laravel otherwise you will have an hard time coding this tips.


text:
Q: Should I capture `tableView` in this closure? I have this code sample with a closure that has a capture list of self:
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let dismiss = UITableViewRowAction(style: .destructive, title: "Dismiss") { [weak self] _, indexPath in
            let cell = tableView.cellForRow(at: indexPath)
            self?.dismissIssue(cell)
        }
        return [dismiss]
    }

Should I put the tableView on the capture list? How to reason about it?

A: No, the passed tableView instance is a local instance. It doesn't cause a retain cycle


text:
Q: Replace line with command sed I want to replace a line in a file, but I'm kinda lost with the command line.
Here's the specific line I want to change; line 55 of a PHP file:

$response['data']['responseData']['ballonsftver'] =
  @constant('BALLON_VER');

I want to replace for this:

$response['data']['responseData']['ballonsftver'] = "2.1-0";

How do I use sed to replace that line?
Thanks

A: This will replace  @constant('BALLON_VER') on line 55 with "2.1-0"
sed -i 55s/"@constant('BALLON_VER')"/"\"2.1-0\""/ filename

Careful while using -i switch of sed to perform an in-place editing.


text:
Q: Common emitter amplifier - calculate Q-point? I am currently studying the common emitter amplifier and I am getting some nasty clipping in the output. So what I am trying to do is to figure out how I can calculate the highest and lowest output voltage (U_CE). My goal is to put the Q-point in the middle of it to have a maximum amplitude symmetrical output signal.
This is my circuit. Its very basic. I use an ideal AC-source with a DC-Offset to set the DC-Bias of UBE.
The transistor uses a constant Beta = hFE = 100.

So as far as I understand the transistor cycles between cut-off region, active region and close to saturation.
When the input signal amplitude (sine wave, UBE) has a negative peak, the transistor should be in the cut-off region. Therefore I assume IC = 0A and UCE = 20V.
When the input signal amplitude has positive peak, the transistor is on the edge of saturation. Therefore UBC = 0 and UCE = UBE_max.
So now I put the Q-Point in the middle: UCE_Q = (20V+UBE_max) / 2.
I choose my IC = 100mA. Therefore collector resistor RC=103ohm (approximately using UBE_MAX = 0.7V)
Doing so I get pretty bad clipping on the positive input half waves.
What am I doing wrong? I understand when the input signal amplitude is too big I get clipping. But in this case the output signal is clipped almost for a whole of the positive input half wave. This leads to the conclusion that the Q-point is not in the middle of the active region. But why?

A: The transistor does not have constant beta. The beta reduces as the collector current reduces which causes the severe distortion where the tops of the waveform are squashed and are not clipping.
You need to add negative feedback to reduce the distortion.

A: You can't easily set the bias point in this circuit.
Basically because the gain of the transistor is so high, minor errors in the choice of base voltage (which is around 0.7 V, but not precisely that, the collector current (and therefore V in this circuit) will have wide variations.
The appropriate DC value of base V is usually generated using negative feedback around the transistor. This also has the effect of reducing the gain (which may be unwanted), and also of linearizing it (making it constant which is generally desirable).
If you still want a large gain, it will require more components to get a large and stable gain.
An emitter resistor will generate negative feedback (and effectively reducing the gain) and also simplify setting the Q point. With an emitter R, the overall gain will be about -Rcollector/Remitter.


text:
Q: Use scss with react-frame-component in create-react-app We have a create-react-app that uses the react-frame-component to render one part of the page completely independent of the rest of the page.
We have been using css files within the frame to apply styles to the components.
This can be done by supplying the initialContent-property with -tags for the css files to the Frame-component, like this (taken from https://github.com/ryanseddon/react-frame-component/issues/74#issuecomment-347710246)
import Frame from 'react-frame-component'
import styles from 'public/css/styles.iframe.css'

const initialContent = () => {
  return (
    `<!DOCTYPE html>

        <link href="${styles}" rel="stylesheet" />

    `
  )
}

<Frame initialContent={initialContent()}>
  <FrameContent />
</Frame>

Now we'd like to be able to use scss files as well.
The problem is when importing the scss files in the app they will be applied to the parent frame and not to the inner frame (of course), no matter in which component you import them.
So what we'd need would be a way to trigger the compilation of the scss file and get the path to the compiled css returned which we could then supply as a string to the Frame-component (like we do with css-files already).
We're already using craco to overwrite some of the cra-config.
So I thought about applying a scss compiler plus a file-loader for certain suffixed scss files.
Here is my craco.config.js:
module.exports = {
  webpack: {
    configure: {
      module: {
        rules: [
          {
            test: /\.(s*).theme.scss$/,
            use: [
              "file-loader",
              "sass-loader"
            ]
          }
        ]
      }
    }
  }
};

And the file is in
css/style.theme.scss

It's included like this:
const testScss = require("./css/style.theme.scss");

But I keep getting
Module not found: Can't resolve './css/style.theme.scss' in '.../.../dist'

A: In order to load scss files you will need style-loader, css-loader, sass-loader. Following rule works perfectly for me. You can give it a try.
{
    test: /\.(css|scss)$/,
    use: [
      { loader: "style-loader" },
      { loader: "css-loader" },
      { loader: "sass-loader" },
    ],
  },


text:
Q: $\mathbb{R}[x,y]/(x^2+y^2-1)$ is integrally closed.
I have been thinking about how to prove that the integral domain $\mathbb{R}[x,y]/(x^2+y^2-1)$ is integrally closed and I am writing this post to ask for proof verification.

Attempt.
Let $R=\mathbb{R}[x,y]/(x^2+y^2-1)$. Then $Q(R)=\frac{R}{\{nonzero\:elements\: of\:R\}}$. But {nonzero elements of $R$} is the complement of $(x^2+y^2-1)$ which is the prime ideal of $\mathbb{R}[x,y]$. So letting $p=(x^2+y^2-1)$, $Q(R)=(\mathbb{R}[x,y]/(x^2+y^2-1))_p=R_p.$ Let $\overline{R}$ be the integral closure of $R$ in $Q(R)$. Then since $(\overline{R})_p$ is the integral closure of $R_p(=Q(R))$ in $Q(R)_p(=Q(R))$, $\overline{R}_p=R_p$. And for all other primes $p'$ in $\mathbb{R}[x,y]$, $p'^c\cap p\neq\emptyset$. So $R_{p'}=0={\overline{R}}_{p'}$, which concludes $R=\overline{R}$.


text:
Q: Agregar fila desde un boton - datagridview c# Estoy tratando de agregar 1 fila desde un botón en mi datagridview en c#,la información es cargada mediante diseño de la siguiente manera.

Codigo para cargar informacion de una tabla de sql por datatable.

public void mostrardatos() {

            dt = negCli.DatosContacto(MODULOS.Globales.Base, txtcod.Text.Trim());

            foreach(DataRow data in dt.Rows){

                int aa = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[aa].Cells[0].Value = data["ITEM"].ToString();
                this.dataGridView1.Rows[aa].Cells[1].Value = data["para_cobranza"].ToString();
                this.dataGridView1.Rows[aa].Cells[2].Value = data["NOMBRE_CONTACTO"].ToString();
                this.dataGridView1.Rows[aa].Cells[3].Value = data["DIRECCION_CONTACTO"].ToString();
                this.dataGridView1.Rows[aa].Cells[4].Value = data["TELEFONO_CONTACTO"].ToString();
                this.dataGridView1.Rows[aa].Cells[5].Value = data["DNI"].ToString();

            }

        }

Alguna idea para agregar una fila desde el boton,facil puedo dejar la opcion editar o agregar desde el controlador del datagridview,pero en este caso quiero realizarlo desde el boton.

A: Pensaria en la siguiente adecuacion:
public void mostrardatos() {

        dt = negCli.DatosContacto(MODULOS.Globales.Base, txtcod.Text.Trim());

        foreach(DataRow data in dt.Rows){

            this.dataGridView1.Rows.Add();
          int aa=  this.dataGridView1.RowCount-1;/*Asi escribiras los datos en la ultima fila agregada al datagridview*/
            this.dataGridView1.Rows[aa ].Cells[0].Value = data["ITEM"].ToString();
            this.dataGridView1.Rows[aa].Cells[1].Value = data["para_cobranza"].ToString();
            this.dataGridView1.Rows[aa].Cells[2].Value = data["NOMBRE_CONTACTO"].ToString();
            this.dataGridView1.Rows[aa].Cells[3].Value = data["DIRECCION_CONTACTO"].ToString();
            this.dataGridView1.Rows[aa].Cells[4].Value = data["TELEFONO_CONTACTO"].ToString();
            this.dataGridView1.Rows[aa].Cells[5].Value = data["DNI"].ToString();

        }

    }