text:
Q: How to check migration status? In Rails, I can run:
rake db:migrate:status

But how about Laravel? How would I know which migrations will run when I do:
php artisan migrate

I am on a production server, and I need to make sure that I won't break things.

A: It's the exact same way with artisan, just add :status:
php artisan migrate:status

In the future you can run just php artisan and it will list all available commands with a short description for each one. If you want more details about a command, like usage and what options it accepts, you can run php artisan help [command]. So for your command it would be:
php artisan help migrate:status

A: If you are using PHP 8 as alternate version then use below command to check.

php80 artisan migrate:status

Check list of PHP Migration command:

php80 artisan list

redpajama_set_name: RedPajamaStackExchange


text:
Q: add if statement inside array php I want to add data into db, but the data required on :status suppose to be a condition eg. status value will be 100 if :name, :dob, :barcode equal to 1 (. else the status value will be 0.
How to put it in ':status' => ???
    if ($_POST["action"] == 'Add') {
        $data = array(
            ':visitor_enter_time'   =>  $visitor->get_datetime(),
            ':visitor_name'         => $_POST["visitor_name"],
            ':no_rm'        =>  $_POST["noRm"],
            ':options'  =>  $_POST["options"],
            ':name' =>  $_POST["name"],
            ':dob' =>   $_POST["dob"],
            ':barcode' =>   $_POST["barcode"],
            ':status' => ???,
            ':id_pic'       =>  $_SESSION["admin_id"]

        );

A: You can create an a function to get status with each case.
function get_status.

function get_status($dob) {
  $status = 0;
  if ($dob == '1') {
    $status = 100;
  }
  return $status;
}

if ($_POST["action"] == 'Add') {
        $data = array(
            ':visitor_enter_time'   =>  $visitor->get_datetime(),
            ':visitor_name'         => $_POST["visitor_name"],
            ':no_rm'        =>  $_POST["noRm"],
            ':options'  =>  $_POST["options"],
            ':name' =>  $_POST["name"],
            ':dob' =>   $_POST["dob"],
            ':barcode' =>   $_POST["barcode"],
            ':status' => get_status($_POST["dob"]),
            ':id_pic'       =>  $_SESSION["admin_id"]

        );


text:
Q: Can I use my azure DNS zone in more than one AKS clusters I have DNS zone with my domain name and also I have an AKS cluster. I want to create dev and staging environments with two separate clusters. So I want to use same domain with different subdomains in each cluster and integrate it in ingress.

A: If I understood you correctly, you need something like Exposing Applications on Azure.
So the idea is to use External DNS + nginx ingress controller.
You

*

*Create 2 AKS clusters

*Create 2 DNS zones entries
az group create -n devresourcegroup -l yourlocation
az network dns zone create -g devresourcegroup -n dev.yourdomainname.com

az group create -n stagingresourcegroup -l yourlocation
az network dns zone create -g stagingresourcegroup -n staging.yourdomainname.com

*

*create  dev.yourdomainname.com and staging.yourdomainname.com entries

*add permissions to modify dns zone for external-dns

*deploy externaldns in both clusters
I suppose external-dns-values.yaml should be like
dev-external-dns-values.yaml:
domainFilters:
  - dev.yourdomainname.com          # (optional) Just restrict to this
...
azure:
  secretName: azure-config-file     # Secret name created above for dev
extraArgs:
  azure-resource-group: devresourcegroup  # (Optional) Resource group name created above

staging-external-dns-values.yaml:
domainFilters:
  - staging.yourdomainname.com     # (optional) Just restrict to this domain
...
azure:
  secretName: azure-config-file     # Secret name created above for staging
extraArgs:
  azure-resource-group: stagingresourcegroup  # (Optional) Resource group name created above

*

*Install external-dns'es

helm install stable/external-dns --name external-dns -f dev-external-dns-values.yaml
helm install stable/external-dns --name external-dns -f staging-external-dns-values.yaml

*

*Install Ingress controllers

*deploy apps with proper ingress objects in each cluster. I mean this part
spec:
  rules:
  - host:
    http:
      paths:
      - backend:
          serviceName:
          servicePort:
        path:


text:
Q: android spinner.setSelection(position, false); is not executed I have a MediaPlayer object and a spinner with all the songs located on the sd card.
I'm trying to create the codes of each Play, Pause, Stop, Previous and Next buttons.
When an item from the spinner is being selected, i'm getting the MediaPlayer from it, and set its data source and calling prepare method. Here's the code:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

            Context context = getApplicationContext();
            CharSequence text = "onItemSelected";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();

            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(sdcard_playlist.get(arg2));
                applyValuesToEqualizer();
                mediaPlayer.prepare();
                index = arg2;

            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            } catch (SecurityException e1) {
                e1.printStackTrace();
            } catch (IllegalStateException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

And here's the code for each Stop and Next buttons:
public void stopSong(View view) {
    if (isPlaying) {
    mediaPlayer.reset();

    isPlaying = false;
    spinner.setSelection(index, false);  // index is the index of the chosen item from spinner
    seekbar.setProgress(0);
    }
}

public void nextSong(View view) {
    if (isPlaying) {
        mediaPlayer.reset();
        isPlaying = false;
        spinner.setSelection(index + 1, false);
        seekbar.setProgress(0);
        playPauseSong(findViewById(R.id.pause_music_button));
    } else {
        spinner.setSelection(index + 1, false);
        seekbar.setProgress(0);
    }
}

What's is happening is that when nextSong() is called, everything is working fine and the toast in onItemSelected() is shown, but when stopSong() is called, onItemSelected() is not being executed and the toast is not shown, the song is being stopped but when I click play button again, i get an exception: start called in state 1, error (-38, 0), it's because the mediaPlayer is reset and not prepared again.
Thanks in advance :)

A: I have solved the issue: If I'm selecting an item from the spinner that is already selected, spinner.setSelection(index, false); won't call onItemSelected again, it's only called if the index is changed. So i did the following:
I created a string variable and set its value to dataSource:
private String dataSource;

in onItemSelected, I added this:
mediaPlayer.reset();
dataSource = sdcard_playlist.get(arg2);
mediaPlayer.setDataSource(dataSource);
applyValuesToEqualizer();
mediaPlayer.prepare();
index = arg2;

So stopSong() method became:
public void stopSong(View view) {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(dataSource);
            applyValuesToEqualizer();
            mediaPlayer.prepare();
        } catch (IOException e) {
            Log.e(TAG, "Error in stopSong() method");
        }
        isPlaying = false;

        seekbar.setProgress(0);
    }
}

A: new Handler().postDelayed(new Runnable() {
                public void run() {
                    spinner.setSelection(index, false);
                }
              }, 100);

try this


text:
Q: GAE Javascript Client : Failed to load resource: net::ERR_CONNECTION_TIMED_OUT Failed to load resource: net::ERR_CONNECTION_TIMED_OUT https://apis.google.com/js/client.js
Has anyone experiencing it right now?
Suddenly, the google cloud endpoint - javascript client stopped working. Is it replaced or being maintained?
If so, why is it I haven't receive an email or any means of notification?
EDIT
Anyway, what are the ways to catch this error?
UPDATE 1:
For unknown reason, GAE - Javascript Client is working again. I am now trying to catch the error so that we can notify the users; and hope this would not happen again.
UPDATE 2:
Doesn't work again. I suspect maintenance is going on(If this is true), What disappoint me is that they failed to provide prior notice.
UPDATE 3:
It is now working as expected. Few updates were made that has nothing to do with the error.


text:
Q: How to add site navigation (ascx) to MVC _Layout.cshtml page I am migrating a WebForm asp.net project to MVC. I copied and pasted the masterpage content to the _Layout.cshtml page. Now I got the side panel for the site Navigation. In the Webform, as shown in the code below, the  put the site navigation to the far left.  I tried both the enf and ~/Views/SiteNavigation.ascx, but the site navigation control is  not appearing  when I load up the page. Just a blank left panel. Any help is appreciated.

                <enf:SiteNavigation  ID="ISRNavigation" />
                @*~/Views/SiteNavigation.ascx*@

                    <asp:ContentPlaceHolder ID="ISRContent" >
                    </asp:ContentPlaceHolder>

        </asp:Panel>

A: I gess you're looking for Html.RenderPartial helper.
In Razor syntax it will be:
@{ Html.RenderPartial("~/Views/SiteNavigation.ascx"); }

A: First of all,

A view in MVC is basic HTML code in which you can add razor syntax. The "Razor code" will be parsed server side and will generate html output to bind models, generate valid url etc.
Here is an example of what your _Layout.cshtml view might look like:

            @Html.Partial("~/Views/YourPartialNavigationView") //Your navigation bar will be rendered here

                @RenderBody() //Body html code will be rendered here

MVC Projet don't support the asp:htmltags syntax

A: in MVC instead of web forms user control, you should use partial views and by using of Helper functions like RenderPartial and Partial you could render it througth your view !!
and also instead of using PlaceHolder you should use Section !
you can Google for both topics : partialView , Section


text:
Q: Couldn't read row 0, col -1 from CursorWindow I am having trouble trying get a graph working in my app but I don't know where i'm going wrong with this code. The code builds but crashes selecting the activity. I think I may have structured it incorrectly as I may be trying create a graph before I obtain data from the database. If anyone can point out my mistake, I would be grateful.
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_graph);
    myDB = new DatabaseCode(this);
    SQLiteDatabase db = myDB.getWritableDatabase();
    Cursor cursor=db.rawQuery("select * from "+TABLE_NAME,null);
        if(cursor.getCount()==0){
            return;
        }
        else {
            ArrayList<Integer> ListArray = new ArrayList<Integer>();
            //
            while (cursor.moveToNext()) {
                ListArray.add(cursor.getInt(cursor.getColumnIndex("COL_2")));
            }
            GraphView graph = (GraphView) findViewById(R.id.graph);
            LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {

                    new DataPoint(0,ListArray.get(0)),
                    new DataPoint(1,ListArray.get(1)),
                    new DataPoint(2,ListArray.get(2))
            });
            graph.addSeries(series);
        }

}

}

Here is the error log.
04-30 16:34:18.912 20125-20125/com.example.fitmess.project E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.example.fitmess.project, PID: 20125
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fitmess.project/com.example.fitmess.project.GraphActivity}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                             at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                          Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                             at android.database.CursorWindow.nativeGetLong(Native Method)
                                                                             at android.database.CursorWindow.getLong(CursorWindow.java:524)
                                                                             at android.database.CursorWindow.getInt(CursorWindow.java:591)
                                                                             at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:69)
                                                                             at com.example.fitmess.project.GraphActivity.onCreate(GraphActivity.java:36)
                                                                             at android.app.Activity.performCreate(Activity.java:6904)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                             at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: while accessing data from cursor you have to check data in cursor and move cursor to first location and the looping will be done like below example
if(cursor.moveToFirst()) //this will move cursor to first position
{
   do{
//your code to fetch data from cursor
  ListArray.add(cursor.getInt(cursor.getColumnIndex("COL_2")));
    }while(cursor.moveToNext());
}

also check the "COL_2" column name is right one as per schema.


text:
Q: testing unexpected user behaviour? I'm discovering that I'm REALLY horrible at testing, and I think to write good tests, you have to know what the user is going to do.
As an example, I've recently taken over an ajax app. It is really well written (I think) and I made some changes to implement a new feature.
When I go through the flow as we expect a user will use the app, everything works fine, but somebody else came along and just started clicking around and broke a feature. It didn't fail catastrophically, but it is definitely a bug. I can't imagine a user ever doing this, but, there is a bug in the app and I missed it in my testing.
How do you manage these sorts of cases? How do you envision anything and everything that a user could possibly do with the app and then test for it?
I understand that every app has bugs, so I'm not looking for support in how to deal with accepting that I'm not perfect.
How do you make sure you're testing as many possibilities as possible, and not just the expected behaviours?

A: Obviously having a team of dedicated testers will help, and performing things like hallway testing or Bug Hunts with your development peers will provide you with some nice bugs.
But the truth is that you are simply suffering from the same thing most developers do when testing out their apps.  I wrote about it in my blog here, and then I wrote about some techniques you can use to improve the tests that you do here.
Testing is not rocket science, but it requires some knowledge and the correct mind-set.
Good luck!
-joel
(BTW, not the same joel that Matty mentioned :-) )

A: You can't anticipate what the user will do with your app. The only thing you can do is to let as many people use your app as possible and as you've already seen that'll help flush out your bugs.
Try doing some hallway testing. Do you have dedicated testers? If not, Joel'll tell you why you should.


text:
Q: How to protect login form from being proxied and used in phishing attack? asking here because I can't find exactly what I am looking for. I looked at several OWASP pages, searched using terms like "login proxy phishing", "login csrf attack" and the likes and found no useful information how to protect this kind of scenario.
Let's say you have your trusted site (T), a malicious site (M), and the user who has an account at trusted site (U).
M sends a malicious email to the user, pretending to be T. User clicks the link and is redirected to M. Now, M is acting as a proxy to your trusted site and scrapes the login page -- the form, the CSRF token if any, is there. But the form's action has been manipulated to POST to M instead of T -- allowing the malicious actor to capture the credentials, before forwarding the login request, and giving to the user T's response (redirect).
Here's the sequence diagram of the attack i'm trying to prevent:
  USER                  MALCIOUS                  TRUSTED
   |                        |                        |
   |  access site >         |                        |
   +----------------------->| scrape login form >    |
   |                        +----------------------->|
   |                        |            < give form |
   |   < give modified form |<-----------------------+
   |<-----------------------+                        |
   | login >                |                        |
   +----------------------->| capture credentials    |
   |                        | and forward login >    |
   |                        +----------------------->|
   |                        |                        |
   |                        |        < login success |
   |                        |         < 301 to /home |
   |                        |<-----------------------|
   |          < redirect to |                        |
   |     < trusted.com/home |                        |
   |<-----------------------+                        |
   |                        |                        |
   |                   (phished!)                    |
   |                                                 |
   |                                                 |
   | access site normally >                          |
   +------------------------------------------------>|
   |                                                 |

Is this actually preventable? I have a gut feeling that CSRF will not help here because the token can be easily scraped and passed back to T and it will pass. Let me know if I'm wrong.
I also think that POSTing the login using ajax will not work because the attacker can proxy everything, including assets, and modify them before serving to the victim -- and make the browser post the ajax form to the malicious site (bypassing XSS). M can then fake an XHR call using curl to forward the request to T.
I am sure this has already been thought of and solved by the experts, but english not being my first language is giving me difficulty in finding the right resources.
What are the keywords that I need to know in order to prevent this?

A: Assume I send you a link to https://grnail.com (gmail where I try to fake m with rn which in some fonts look almost alike). Are you going to log in and put your own credentials? You are going to check the domain name if it is something you really expect.
Unfortunately most of the security at this point relies on the user and his ability to read. On the other hand sometimes reading does not help at all. There are e.g. unicode attacks that were quite popular some years ago:

*

*https://en.wikipedia.org/wiki/IDN_homograph_attack

*https://thehackernews.com/2017/04/unicode-Punycode-phishing-attack.html
Well, try it yourself in different browsers: https://www.аррӏе.com/
How to prevent this kinds of attack. You can't. Well, almost. If your site is using authentication and your users authenticate using U2F, then even if their credentials leek, the attacker will not be able to take over the account.


text:
Q: To determine file owner, size and date/time modified based on last modify date I would like to determine the ownership, size and date/time modified of files from a number of disk systems.
Is there a way to search for these files and directories recursively as the only solution I know is using find's -mtime option and that only returns a list of file names/paths based on a specified date range. I will need the ownership, size and date/time modified as well.
I knew stat will give the detail info with some post-processing, but is there any other option to find these files efficiently with the information I need on each file, as I have to deal with a huge files/directories across many file systems?

A: With GNU find, you can use the -ls option to have find print the results in a format similar to ls -isl or use the -printf option to select exactly the fields you want. Examples:
find . -type f -mtime -3 -ls

find . -type f -mtime -3 -printf 'owner=%u (uid %U) size=%s bytes modified=%t name=%p\n'

A: The GNU version of find has -user (for owner), -size (for file size), -mtime (for modified time).
Don't these options give you exactly what you need?

A: I edited your OP for readability and clarity.
Based on what I believe you are asking, you can combine find with ls to give you what you are looking for:
find . -type f -mtime -3d -print0 | xargs -0 ls -la

The above command-line statement will identify all files less than three days since modified and pipe the output to the ls command with the -la switch to give you full file information, as you indicated you needed. You can fiddle around with the find portion of the statement to identify the actual file set, but the back portion will always give you the details on the files.


text:
Q: Postgres function slower than same ad hoc query I have had several cases where a Postgres function that returns a table result from a query is much slower than running the actual query. Why is that?
This is one example, but I've found that function is slower than just the query in many cases.
create function trending_names(date_start timestamp with time zone, date_end timestamp with time zone, gender_filter character, country_filter text)
    returns TABLE(name_id integer, gender character, country text, score bigint, rank bigint)
    language sql
as
$$
select u.name_id,
       n.gender,
       u.country,
       count(u.rank)                                   as score,
       row_number() over (order by count(u.rank) desc) as rank
from babynames.user_scores u
         inner join babynames.names n on u.name_id = n.id
where u.created_at between date_start and date_end
  and u.rank > 0
  and n.gender = gender_filter
  and u.country = country_filter
group by u.name_id, n.gender, u.country
$$;

This is the query plan for a select from the function:
Function Scan on trending_names  (cost=0.25..10.25 rows=1000 width=84) (actual time=1118.673..1118.861 rows=2238 loops=1)
  Buffers: shared hit=216509 read=29837
Planning Time: 0.078 ms
Execution Time: 1119.083 ms

Query plan from just running the query. This takes less than half the time.
WindowAgg  (cost=44834.98..45593.32 rows=43334 width=25) (actual time=383.387..385.223 rows=2238 loops=1)
Planning Time: 2.512 ms
Execution Time: 387.403 ms
  Buffers: shared hit=100446 read=50220
  ->  Sort  (cost=44834.98..44943.31 rows=43334 width=17) (actual time=383.375..383.546 rows=2238 loops=1)
        Sort Method: quicksort  Memory: 271kB
        Sort Key: (count(u.rank)) DESC
        Buffers: shared hit=100446 read=50220
        ->  HashAggregate  (cost=41064.22..41497.56 rows=43334 width=17) (actual time=381.088..381.906 rows=2238 loops=1)
"              Group Key: u.name_id, u.country, n.gender"
              Buffers: shared hit=100446 read=50220
              ->  Hash Join  (cost=5352.15..40630.88 rows=43334 width=13) (actual time=60.710..352.646 rows=36271 loops=1)
                    Hash Cond: (u.name_id = n.id)
                    Buffers: shared hit=100446 read=50220
                    ->  Index Scan using user_scores_rank_ix on user_scores u  (cost=0.43..35077.55 rows=76796 width=11) (actual time=24.193..287.393 rows=69770 loops=1)
                    ->  Hash  (cost=5005.89..5005.89 rows=27667 width=6) (actual time=36.420..36.420 rows=27472 loops=1)
                          Rows Removed by Filter: 106521
                          Index Cond: (rank > 0)
                          Filter: ((created_at >= '2021-01-01 00:00:00+00'::timestamp with time zone) AND (country = 'sv'::text) AND (created_at <= now()))
                          Buffers: shared hit=99417 read=46856
                          Buffers: shared hit=1029 read=3364
                          Buckets: 32768  Batches: 1  Memory Usage: 1330kB
                          ->  Seq Scan on names n  (cost=0.00..5005.89 rows=27667 width=6) (actual time=0.022..24.447 rows=27472 loops=1)
                                Rows Removed by Filter: 21559
                                Filter: (gender = 'f'::bpchar)
                                Buffers: shared hit=1029 read=3364

I'm also confused on why it does a Seq scan on names n in the last step since names.id is the primary key and gender is indexed.


text:
Q: iPhone WebKit CSS animations cause flicker This is the iphone site:
http://www.thevisionairegroup.com/projects/accessorizer/site/
After you click "play now" you'll get to a game. The guns will scroll in. You can scroll the purse and accessories up and down. You can see that when you let go they snap into place. Just as that snap happens, there's a flicker that occurs. The only webkit animations I'm using are:
'-webkit-transition': 'none'

'-webkit-transition': 'all 0.2s ease-out'

'-webkit-transform': 'translate(XXpx, XXpx)'

I choose either the first or second transition based on whether or not I want it to animate, and the transform is the only way I move things around.
The biggest issue though is when you click "Match items", then click "Play again". You'll see as the guns animate in, the entire background of the accessories/purses goes white. Can someone please radiate me with some insight asto why this is happening??

A: Michael's answer -webkit-backface-visibility: hidden; worked when we hit this problem. We had translateZ(0px) on our  tag to prevent an iOS 3.1.3 and earlier IFRAME boundary bug and it caused anims to flicker. Adding -webkit-backface-visibility: hidden; to each element we animated fixed the flicker! Life saver.

A: Try this, and hopefully it will help:
#game {
  -webkit-backface-visibility: hidden;
}

A: div { -webkit-tap-highlight-color: rgba(255, 255, 255, 0); }

i noticed when i had a hover state on a div the page would flicker, even if i did not have any css or js attached to it. maybe this helps someone else.

A: If anyone finds that backface-visibility is not working, you might look at the properties already on your animated element. For us, we found that overflow-y: scroll on an absolute or fixed positioned element was causing major flickering on iOS.
Simply removing overflow-y: scroll fixed it.

A: body {-webkit-transform:translate3d(0,0,0);}

A: The actual answer for my case is here. Someone was close with: -webkit-backface-visibility: hidden; But the real answer is -webkit-backface-visibility: hidden; needs to be added to the parent div.

A: I added -webkit-backface-visiblity and that mostly helped, but I still had an initial flicker after reloading the page. When I added -webkit-perspective: 1000, there was no flicker whatsoever.
-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;

A: I had a problem with a "flickering" CSS transition as well. The animation in question was a menu sliding in from off screen, and just when the animation finished, the entire menu flashed/flickered.
As it turned out, this was caused by an actual iOS feature, the "tap highlight", which for some reason kicked in after the CSS animation finished (i.e. way after the actual tap), and highlighted the entire menu instead of only the element that was tapped. I "fixed" the issue by entirely disabling tap-highlight, as described here:
-webkit-tap-highlight-color: rgba(0,0,0,0);

A: Even though I had -webkit-transform-style: preserve-3d; and -webkit-backface-visibility: hidden the flicker was still happening.
In my case the cause was the z-index. Increasing it on active element did help.

A: I tried all the above and still had major flickering problems on Firefox and Chrome. I fixed it, or at least greatly reduced it to an acceptable issue by removing the box-shadow transform that was causing many repaints during the animation. I followed this and modified for my needs:
http://tobiasahlin.com/blog/how-to-animate-box-shadow/

A: I had to use an actual value (rather than 0):
.no-flick{
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-transform:translateZ(0.1px);
    transform: translateZ(0.1px); /* needs an actual value */
}

Example:

From what I've read, the flicker is caused by the browser switching between hardware and software rendering. And I think browser manufacturers are aware of yea olde "translate3d(0,0,0)" to force hardware rendering -- so they may now be ignoring these fake values.
=> Using an actual value may cause things to "stick".
Anyway, worked for me.

A: So I found a fix for this issue where none others worked properly.
CSS:
.ios-animation-fixer {
  position: fixed;
  width: 100%;
  height: 10px;
  top: -10px;
  background-color: green;
  z-index: 1;
  pointer-events: none;
  visibility: hidden;
}

HTML:

Then set the z-index for your animated element to be > 1. This somehow tricks iOS devices into rendering the animation differently, and avoids the flicker in my scenario. Adjusting z-index values may be helpful if this solution doesn't work out of the gate.

A: I've been trying to fix a similar problem for ages, and a comment in this thread was the key for me, so I'm highlighting it for others:

I actually needed to add -webkit-backface-visibility: hidden; to the parent div, the animated div, AND the children of the animated div. Once I did that, it worked flawlessly. –
mattstuehler
Mar 12, 2013 at 13:36

I has a horrible white flash when using transform: translate3d to reposition a div: if I added transition-duration to the transform and moved the div too far, the screen would flash white on iOS webkit browsers (only!).  It drove me crazy, and I combed threads like these looking for a solution, while trying everything else I could to stop it.  Here's what finally worked:

#board_container * { /* asterisk(*) => board container and all its descendants */
    /*
       attempt to stop iOS webkit flash when board is panned
       to its edge... is it finally working?!?
    */
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
}

I had previously tried applying things to my #board div and its wrapper #board_container, but there were a couple more levels of elements contained within, and apparently they all needed the treatment for the white flash to disappear.  What I has missing was a simple asterisk in the CSS:
#board_container * {
Never did figure out why it only happened on iOS webkit browsers, and only when the board div was translated beyond a certain extent...

A: Here's a new solution. I was setting the background-image with jQuery, and none of the 3d-rendering tricks worked. So I tried using classes to define the properties instead. Voilà! Smooth as butter.
This causes flicker:
$('#banner').css('backgroundImage', 'url("slide_1.jpg")';

Instead do:
$('#banner').attr('class', '.slide-1');

with classes defined:
#banner { -webkit-transition: background-image .25s; }
.slide-1 { background-image: url("slide_1.jpg"); }
.slide-2 { background-image: url("slide_2.jpg"); }

A: Try this solution. It works for me in Phonegap + jQM 1.4.0:
Change this <meta name="viewport" content="width=device-width, initial-scale=1">
To this instead:
<meta name="viewport" content="width=device-width, user-scalable=no" />
Read more here: http://www.fishycode.com/post/40863390300/fixing-jquery-mobiles-none-transition-flicker-in

A: I had spent a lot of time trying to figure out this issue for Ember Animated Outlets, Phonegap, and iOS setup.
Though simple, I had to add a background to each top-level parent element that was included in the css animations. In other words, make sure that at no point in your views there is an element that doesn't have a background.
My setup was this for each template and all three elements had a background color assigned to them:

A: Instead of applying the transition to "all" just specify the one you really need. It removed the flickering on my case.

A: for me, flickering issue on safari solved by removing will-change: transform; to the animated element.
also I could solve this issue by adding overflow: hidden; to the parent, but with this, all elements with transform: translateZ() got ineffective

A: I've experienced flickering when performing a slide transition when using a default Android web browser.
I've used the following transition css:
-webkit-transition: all 2s;
-webkit-transform: translate(100%,0);

None of the workarounds mentioned in this thread have helped to solve the issue.
Finally I've found the solution. The source of flickering is the all keyword which means to perform all possible transitions. I've changed it to perform only transformation and the issue has been solved:
-webkit-transition: -webkit-transform 2s;
-webkit-transform: translate(100%,0);

A: What fixed it for me was to delay the assignment of the transform-translate CSS rule. Something like this:
HTML:

CSS:
.animate-this {
  &:not(.loading) {
    transform: -webkit-translate(50px);
    transform: translate(50px);
    transition: -webkit-transform 0.3s, transform 0.3s;
  }
}

JavaScript (jQuery):
$(document).ready(function(){
  window.setTimeout(function(){
    $('.animate-this').removeClass('loading');
  }, 250);
});

… Because -webkit-backface-visibility: hidden; didn't do anything for me.

A: UPDATE 2019
You can turn on flickering by simply add these rules to your element that is transition used on.
-webkit-transform: translate3d(0, 0, 0);

Worked for me on Safarai


text:
Q: How to check if a user inputted value is valid? I'm working on an app in which the user has the option to input a set of coordinates in two EditText views for Latitude and Longitude. The inputted coordinate/location will then be displayed on a map, which works great. However if the user inputs an invalid value the app crashes, and I need to prevent that.
The Latitudes/Longitudes value has to be for example 35.27, and the thing that makes the app crash is when there's more then one dot "." e.g. 33.23.43. How can i check if the inputted value only has ONE dot?
I don't really have a lot of experience in this area, and I'm still new to android, so any help will be much appreciated.

A: I was going to suggest that you checked the length of the string that you get, but because 1.5 and 153.163 are both valid that doesn't work. I advise you to use a `try/catch statement. For example
try{
    //do what ever you do with the numbers here
catch(Exception e){
//the user has inputted an invalid number deal with it here
}

A: Check out
Android EditText : setFilters Example : Numeric Text field Patterns and Length Restriction.
It may be what you want.

A: bool badInput = countChar(s, '.')  > 1;

where countChar is
int countChar(string s, char c)
{
    int counter = 0;
    for( int i=0; i<s.length(); i++ ) {
        if( s.charAt(i) == c ) {
            counter++;
        }
    }
    return counter;
}

A: Simply use a regexp to check the validity of the input.
Pattern p = Pattern.compile("^(-)?\d*(\.\d*)?$");
Matcher m = p.matcher(inputString);
if (m.find()) {
    ////Found
}
else {
  //Not found
}

Now Implement a focus listener on the field to run this validity test.
OR : you can do this from xml also.
In XML add attribute to editText :
android:inputType="number|numberSigned|numberDecimal"

for signed floating point number.
Thanks.


text:
Q: How to update a control in MDI parent form from child forms? I looked to some similar questions but I didn't really get my answer, so I ask again hopefuly someone can explain it.
The situation:
I have a MDI form that has some menues and a status bar and stuff like that. Is the only way of altering text for status bar and doing other things to the parent form is to call it as static? Or if not, can you please give an example for updating (for example) status bar that exist in parent form within the child forms?
Thanks!

A: You need to make the child forms take a parent form instance as a constructor parameter.
The children can save this parameter to a private field, then interact with the parent at will later.
For optimal design, you should abstract the parent from the child through an interface implemented by the parent, containing methods and properties that do what the children need.  The children should then only interact with this interface.
public interface IChildHost {
    void UpdateStatusBar(string status);
    //Other methods & properties
}

public partial class ParentForm : IChildHost {
    public void UpdateStatusBar(string status) {
        ...
    }
    //Implement other methods & properties
}

public partial class ChildForm {
    readonly IChildHost host;
    public ChildForm(IChildHost parent) {
        this.host = parent;
    }

}

A: The Form class already exposes a property MdiParent ensure the parent forms IsMdiContainer property is set accordingly.

A: Another option is to use events (you can build these events into a base class and let all your child forms inherit from it):
// Code from Form 1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2();
        objForm2.ChangeStatus += new ChangeStatusHandler(objForm2_ChangeStatus);
        objForm2.Show();
    }
    public void objForm2_ChangeStatus(string strValue)
    {
        statusbar.Text = strValue;
    }
}

// Code From Form 2
public delegate void ChangeStatusHandler(string strValue);
public partial class Form2 : Form
{
    public event ChangeStatusHandler ChangeStatus;

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (PassValue != null)
        {
            PassValue(textBox1.Text);
        }
    }
}


text:
Q: Создание списка из словаря по списку со значениями ключей этого словаря Есть список с ID и словарь с ключами со значениями этих ID.
Нужно сравнить их, и если есть такие ID, то вывести их в новый список.
Что есть:
items = {1: 'Русский язык', 2: 'Математика', 3: 'Физика', 4: 'Химия', 5: 'Информатика и ИКТ'}

values = [2, 2, 5, 5, 3, 3, 5, 5]

Что нужно получить:
['Математика', 'Математика', 'Информатика и ИКТ', 'Информатика и ИКТ', 'Физика', 'Физика', 'Информатика и ИКТ', 'Информатика и ИКТ']

A: res = [items.get(x, "не найдено") for x in values]

результат:
In [55]: res
Out[55]:
['Математика',
 'Математика',
 'Информатика и ИКТ',
 'Информатика и ИКТ',
 'Физика',
 'Физика',
 'Информатика и ИКТ',
 'Информатика и ИКТ']

A: items = {1: 'Русский язык', 2: 'Математика', 3: 'Физика', 4: 'Химия', 5: 'Информатика и ИКТ'}

values = [2, 2, 5, 5, 3, 3, 5, 5]

result = []
# result = [items[id] for id in values if id in items]

for id in values:
  if id in items:
    result.append(items[id])

print(result)


text:
Q: Explicit Formula Given a Recursion Suppose we have a function $f$ such that for positive integers $n \ge1$ and $f(0)=0$ and $f(1)=1$ we have:
i)  $f(2n + 1) = 2f(n) + 2$
ii) $f(2n) = f(n) + f(n − 1) + 2$
What is the generating function for $f$, and what is the explicit formula for $f(n)$?
Challenge
Moreover, what would be the value of $\lim_{k \to \infty} \frac{f(2^kx)}{2^kx}$, in terms of $x$

A: LAST UPDATE - promised :-) (Explicit Formula)
Let's start by subtracting both equations :
$$f(2n+1)-f(2n)=f(n)-f(n-1)$$
we have too $\ f(2(n+1))=f(n+1)+f(n)+2$ so that :
$$f(2n+2)-f(2n+1)=f(n+1)-f(n)$$
Setting $\ g(n):=f(n+1)-f(n)\ $ will return the simpler :
$$g(2n)=g(n-1),\quad g(2n+1)=g(n)$$
and the even simpler for $n>0$ ( with $g(0)=1,\ g(1)=2$ ) :
$$\boxed{g(n)=g(2n+1)=g(2n+2)}$$
The initial values of $1$ and $2$ will 'propagate' all the way long alternating a power of $2$ number of ones with the same number of twos getting (starting with $n=0$) :
$$1, 2, 1, 2, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1$$
A simpler rule to retain this is to consider $n+1$ : if the two most significant bits of $(n+1)$ are $10_2$ then $g(n)=2$ else (for $11_2$) we get $g(n)=1$ or more formally :
$$
g(n)=\begin{cases}
&1\quad \text{if}\quad n=0\quad \text{or}\quad 2^m+2^{m-1}\le n+1<2^{m+1}\ \text{with}\ m\in\mathbb{N}\ \ \\
&2\quad \text{if}\quad 2^m\le n+1<2^m+2^{m-1}\ \text{with}\ m\in\mathbb{N}\\
\end{cases}
$$
Let's try to get a generating function for the $g(n)$ terms :
\begin{align}
G(x)&=\sum_{n=0}^\infty g(n)\,x^n\\
&=1+2x^1+x^2+2(x^3+x^4)+x^5+x^6+2(x^7+x^8+x^9+x^{10})+x^{11}+\cdots\\
&=\frac 1{1-x} +x^1+(x^3+x^4)+(x^7+x^8+x^9+x^{10})+(x^{15}+\cdots+x^{22})+\cdots\\
&=\frac {1+x(1-x)+x^3(1-x^2)+x^7(1-x^4)+x^{15}(1-x^8)+\cdots}{1-x}\\
&=\frac {1+\sum_{k=0}^\infty x^{2\cdot 2^k}(1-x^{2^k})/x}{1-x}\\
&=\frac {1+\left(S(x^2)-S(x^3)\right)/x}{1-x}\\
\end{align}
Using the $S$ series (convergent for $|x|<1$) defined by : $\ \displaystyle S(x):=\sum_{n=0}^\infty x^{2^n}$
(the continued fraction of $S\left(\frac12\right)$ was studied by Shallit here and given at OEIS)
Let's observe that (of course!) $G\left(\frac 1{10}\right)=1.212211222211112222222211\cdots$

Concerning $f(n)$ it will be obtained using $\ f(n+1)=f(n)+g(n)\ $ with $f(0)=0$ getting :
$$0, 1, 3, 4, 6, 8, 9, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 28, 30, 32$$
You may obtain this result using following generating function (remembering that the effect of the division by $1-x$ is to obtain the partial sums) :
\begin{align}
F(x)&=\frac{1x+2x^2+1x^3+2x^4+2x^5+1x^6+1x^7+2x^8+2x^9+2x^{10}+2x^{11}+1 x^{12}+\cdots}{1-x}\\
&=0+1x + 3x^2 + 4x^3 + 6x^4 + 8x^5 + 9x^6 + 10x^7 + 12x^8 +14x^9+16x^{10}+\cdots\\
\end{align}
or formally :
$$F(x)=\frac{x\,G(x)}{1-x}=\frac {x+S(x^2)-S(x^3)}{(1-x)^2}$$
An explicit formula for $f(n)$ should be (for $n>1$ and  $m:=\lfloor\log_2(n)\rfloor$) :
$$
f(n)=\begin{cases}
&2\;n-2^{m-1}\quad &\text{if}\quad 2^m\le n<2^m+2^{m-1}\ \text{with}\ m\in\mathbb{N}\\
&\ n+2^m-1\quad &\text{if}\quad 2^m+2^{m-1}\le n<2^{m+1}\ \text{with}\ m\in\mathbb{N}\ \ \\
\end{cases}
$$

Challenge (updated)
I don't have a proof of this but I'll conjecture that for $x\in \mathbb{N}^*$ (with $m:=\lfloor\log_2(x)\rfloor$) :
$$
\lim_{k \to \infty} \frac{f(2^kx)}{2^k}=\begin{cases}
&2\;x-2^{m-1}\quad &\text{if}\quad 2^m\le x<2^m+2^{m-1}\ \text{with}\ m\in\mathbb{N}\\
&\ x+2^m\quad &\text{if}\quad 2^m+2^{m-1}\le x<2^{m+1}\ \text{with}\ m\in\mathbb{N}\ \ \\
\end{cases}
$$
Interesting problem. Hoping this helped a little,


text:
Q: SP 2013 - Audit Report - Custom Report - Filters not working We have setup up SP 2013 and enabled auditing. The issue is when I try to run a custom report on a sub site I get the error...It does not allow me to select using browse buttons in either the "Save location" or the "Restrict the report to:" browse.

Sorry, something went wrong
Report contains no data.

I have included screenshot of what I am running. When I return to the screen after the error the "Restrict the report to" checkbox is unticked and the text field greyed out.

As a foot note I have also tried this directly from a custom list item (custom lists I need to get this working on).
I click on Compliance details > Generate audit log report with the following errors:
When I attempt to change the save location

Sorry, something went wrong   Reports cannot be stored at
  '/Documents'. Reports can only be stored in a document library in the
  current site.

When I do not change the list save location

Sorry, something went wrong  Report contains no data.

A: You must be a site collection administrator, then you can do:
Site Actions
Site Settings
Modify All Site Settings
Site Collection Administration
Site collection audit settings
Cofigure Audit Settings - and check the boxes that are appropriate for your case.
This article help you to configure audit setting and view audit log reports from Site settings: https://community.spiceworks.com/how_to/126012-how-to-track-changes-on-sharepoint-server-2013
Thanks,


text:
Q: datetimepicker works in every web browser except Firefox? here is my HTML piece of code :
meta:
<link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.min.css">

body:

    Date:
    <input type='text' class="form-control" id='datetimepicker4' placeholder="Sélectionnez une date" />

My script :
$(function () {
    $('#datetimepicker4').datetimepicker({
        isRTL: false,
        format: 'dd.mm.yyyy hh:ii',
        autoclose:true,
        language: 'fr'
     });
});

This works in every web browser except Firefox on Microsoft only (works on Mac)
Here it how it looks like :

But in Firefox, it doesn't pop up.
Here is the error message i get from the console log :

Any ideas ?


text:
Q: Identify a linear feature on a raster map and return a linear shape object using R I would like to identify linear features, such as roads and rivers, on raster maps and convert them to a linear spatial object (SpatialLines class) using R.
The raster and sp packages can be used to convert features from rasters to polygon vector objects (SpatialPolygons class).  rasterToPolygons() will extract cells of a certain value from a raster and return a polygon object.  The product  can be simplified using the dissolve=TRUE option, which calls routines in the rgeos package to do this.
This all works just fine, but I would prefer it to be a SpatialLines object.  How can I do this?
Consider this example:
## Produce a sinuous linear feature on a raster as an example
library(raster)
r <- raster(nrow=400, ncol=400, xmn=0, ymn=0, xmx=400, ymx=400)
r[] <- NA
x <-seq(1, 100, by=0.01)
r[cellFromRowCol(r, round((sin(0.2*x) + cos(0.06*x)+2)*100), round(x*4))] <- 1

## Quick trick to make it three cells wide
r[edge(r, type="outer")] <- 1

## Plot
plot(r, legend=FALSE, axes=FALSE)

## Convert linear feature to a SpatialPolygons object
library(rgeos)
rPoly <- rasterToPolygons(r, fun=function(x) x==1, dissolve=TRUE)
plot(rPoly)

Would the best approach be to find a centre line through the polygon?
Or is there existing code available to do this?
EDIT:  Thanks to @mdsumner for pointing out that this is called skeletonization.

A: Thanks to @klewis at gis.stackexchange.com for linking to this elegant algorithm for finding the centre line (in response to a related question I asked there).
The process requires finding the coordinates on the edge of a polygon describing the linear feature and performing a Voronoi tessellation of those points.  The coordinates of the Voronoi tiles that fall within the polygon of the linear feature fall on the centre line.  Turn these points into a line.
Voronoi tessellation is done really efficiently in R using the deldir package, and intersections of polygons and points with the rgeos package.
## Find points on boundary of rPoly (see question)
rPolyPts <-  coordinates(as(as(rPoly, "SpatialLinesDataFrame"),
                "SpatialPointsDataFrame"))

## Perform Voronoi tessellation of those points and extract coordinates of tiles
library(deldir)
rVoronoi <- tile.list(deldir(rPolyPts[, 1], rPolyPts[,2]))
rVoronoiPts <- SpatialPoints(do.call(rbind,
                 lapply(rVoronoi, function(x) cbind(x$x, x$y))))

## Find the points on the Voronoi tiles that fall inside
## the linear feature polygon
## N.B. That the width parameter may need to be adjusted if coordinate
## system is fractional (i.e. if longlat), but must be negative, and less
## than the dimension of a cell on the original raster.
library(rgeos)
rLinePts <- gIntersection(gBuffer(rPoly, width=-1), rVoronoiPts)

## Create SpatialLines object
rLine <- SpatialLines(list(Lines(Line(rLinePts), ID="1")))

The resulting SpatialLines object:

A: You can get the boundary of that polygon as SpatialLines by direct coercion:
rLines <- as(rPoly, "SpatialLinesDataFrame")

Summarizing the coordinates down to a single "centre line" would be possible, but nothing immediate that I know of. I think that process is generally called "skeletonization":
http://en.wikipedia.org/wiki/Topological_skeleton

A: Here's my effort. The plan is:

*

*densify the lines

*compute a delaunay triangulation

*take the midpoints, and take those points that are in the polygon

*build a distance-weighted minimum spanning tree

*find its graph diameter path

The densifying code for starters:
densify <- function(xy,n=5){
  ## densify a 2-col matrix
  cbind(dens(xy[,1],n=n),dens(xy[,2],n=n))
}

dens <- function(x,n=5){
  ## densify a vector
  out = rep(NA,1+(length(x)-1)*(n+1))
  ss = seq(1,length(out),by=(n+1))
  out[ss]=x
  for(s in 1:(length(x)-1)){
    out[(1+ss[s]):(ss[s+1]-1)]=seq(x[s],x[s+1],len=(n+2))[-c(1,n+2)]
  }
  out
}

And now the main course:
simplecentre <- function(xyP,dense){
require(deldir)
require(splancs)
require(igraph)
require(rgeos)

### optionally add extra points
if(!missing(dense)){
  xy = densify(xyP,dense)
} else {
  xy = xyP
}

### compute triangulation
d=deldir(xy[,1],xy[,2])

### find midpoints of triangle sides
mids=cbind((d$delsgs[,'x1']+d$delsgs[,'x2'])/2,
  (d$delsgs[,'y1']+d$delsgs[,'y2'])/2)

### get points that are inside the polygon
sr = SpatialPolygons(list(Polygons(list(Polygon(xyP)),ID=1)))
ins = over(SpatialPoints(mids),sr)

### select the points
pts = mids[!is.na(ins),]

dPoly = gDistance(as(sr,"SpatialLines"),SpatialPoints(pts),byid=TRUE)
pts = pts[dPoly > max(dPoly/1.5),]

### now build a minimum spanning tree weighted on the distance
G = graph.adjacency(as.matrix(dist(pts)),weighted=TRUE,mode="upper")
T = minimum.spanning.tree(G,weighted=TRUE)

### get a diameter
path = get.diameter(T)

if(length(path)!=vcount(T)){
  stop("Path not linear - try increasing dens parameter")
}

### path should be the sequence of points in order
list(pts=pts[path+1,],tree=T)

}

Instead of the buffering of the earlier version I compute the distance from each midpoint to the line of the polygon, and only take points that are a) inside, and b) further from the edge than 1.5 of the distance of the inside point that is furthest from the edge.
Problems can arise if the polygon kinks back on itself, with long segments, and no densification. In this case the graph is a tree and the code reports it.
As a test, I digitized a line (s, SpatialLines object), buffered it (p), then computed the centreline and superimposed them:
 s = capture()
 p = gBuffer(s,width=0.2)
 plot(p,col="#cdeaff")
 plot(s,add=TRUE,lwd=3,col="red")
 scp = simplecentre(onering(p))
 lines(scp$pts,col="white")

The 'onering' function just gets the coordinates of one ring from a SpatialPolygons thing that should only be one ring:
onering=function(p){p@polygons[[1]]@Polygons[[1]]@coords}

Capture spatial lines features with the 'capture' function:
capture = function(){p=locator(type="l")
            SpatialLines(list(Lines(list(Line(cbind(p$x,p$y))),ID=1)))}

A: I think ideal solution would be to build such negative buffer which dynamically reach the minimum width and doesn't break when value is too large; keeps continued object and eventually, draws a line if the value is reached. But unfortunately, this may be very compute demanding because this would be done probably in steps and checks if the value for particular point is enough to have a point (of our middle line). Possible it's ne need to have infinitive number of steps, or at least, some parametrized value.
I don't know how to implement this for now.


text:
Q: apache-cxf client works with exec-maven-plugin, but not from outside I am having problems triying to create a WS client in java.
The libraries I'm using is apache-cxf 2.12. This is an old version but I want the web service to be added to a JBoss application that is already running and uses Spring 2.5.6, so this org.apache.cxf version uses same spring  version.
But the question is (I know is quite generic, is related to maven, netbeans and apache-cxf)
When I execute my client project (maven proyect) from netbeans, it works sort of Ok.
When I try to  run this class with a script (bot windows an linux) it  gives me this error:
"Invocation failed with the following: org.apache.cxf.ws.policy.PolicyException: None of the policy alternatives can be satisfied."
Java versions are the same, I've copied all the dependency jar into lib dir and added then to %classpath%
So, what can be different that when I execute my sample program with maven org.codehaus.mojo:exec-maven-plugin:1.2.1:exec it works and it doesn't when I run it with a srcipt? (I have checked all dependencies, java version, ... )
I guess it has to be related to JAX-WS o JCE (Java Cryptography Architecture) initialization.
¿Is there a way to see what %classpath  maven is creating when in runs java.exe?
Maven script that works:
JAVA_HOME=D:\\LOCAL\\Java\\jdk1.5.0_15
D:\\LOCAL\\apache-maven-2.0.9\\bin\\mvn.bat
-Dexec.classpathScope=runtime
-DskipTests=true
"-Dexec.args=-Djavax.net.debug=all -classpath %classpath es.webservice.aaTest TESTFILE"
-Dexec.executable=D:\\LOCAL\\Java\\jdk1.5.0_15\\bin\\java.exe
-Dmaven.repo.local=D:\\bsrepo\\.m2 process-classes
org.codehaus.mojo:exec-maven-plugin:1.2:exec

Thanks


text:
Q: Homogeneous Structures Let $M$ be a countable structure that is homogeneous, i.e. every isomorphism between finitely generated substructures of $M$ extends to an automorphism of $M$. Let $\phi_M$ be the Scott sentence of $M$.
If $N$ is an uncountable model of $\phi_M$, then $N$ is not necessarily homogeneous, but is the existence of an uncountable model sufficient for the existence of an uncountable homogeneous model? If so, can we further conclude that given $N\models\phi_M$, $N$ uncountable, there is a homogenous model of $\phi_M$ of the same cardinality as $N$?
Any help?


text:
Q: ServletException in:/layouts/menu.jsp null' in one portion of jsp page where redirect link is there There is a java struts 1.1 web application developed using java 4 and which is now being upgraded to openjdk 8. While running the application I am getting this servlet exception in the UI screen in one portion which consists of a link to different jsp page. How to fix this issue?
[ServletException in:/layouts/menu.jsp] null'

A: I had the same issue. I think it's getting hung up somewhere in your Action class, as soon as you enter the entry point of your Action class. Place some system outs to the console and check how far you can get with it. Then if you don't see your next system  out, then that's where the issue may be hanging around.


text:
Q: java standard lib produce wrong xml 1.1 I found this interesting problem last week. Run the program below. It's very simple, first create a dummy xml file, and read it with standard lib and write it back to a file.
Look through the generated gtest2.xml, you will see that it has some content that were come out of nowhere.
In my case, this is the sample of wrong section (the place vary on different machine).
<test>1924</test>
<test>1925</test>
<test>t>24</test>
<test>1927</test>
<test>1928</test>
<test>1929</test>

This does not happen if I changed my xml version to 1.0. So something wrong with my code or jdk?
Here is the test code:
import java.io.File;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class DocumentBuilderCheck {

    public static void main(String[] args) throws Exception {
        String filename = "/tmp/gtest.xml";
        generateXmlFile(filename, 2500);
        Document doc = readXmlFile(filename);

        String filename2 = "/tmp/gtest2.xml";
        writeDocument(doc, filename2);
    }

    private static void writeDocument(Document document, String filename) throws Exception {
        StreamResult streamResult = new StreamResult(filename);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(new DOMSource(document), streamResult);
    }

    private static Document readXmlFile(String filename) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File(filename));
        return doc;
    }

    private static void generateXmlFile(String filename, int total)
            throws Exception {
        File f = new File(filename);

        PrintWriter pw = new PrintWriter(f);
        pw.write("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
        pw.write("<main_tag>");
        for (int i = 0; i < total; i++) {
            pw.write("<test>" + String.format("%04d", i) + "</test>");
        }
        pw.write("</main_tag>");
        pw.close();
    }
}

A: I don't know what gives, but one well-known (?) problem with JDK is that it often includes old version of libraries such as Xerces (XML parser) and Xalan (XSLT processor). Worse, sometimes these are custom versions using old version as baseline, and some set of patches, so it is hard to even verify what to expect.
As a result, recommendation is not to rely on whatever is bundled but instead explicitly use official Xerces/Xalas versions to ensure that version used is known and you can at least check what known issues exist.
So maybe you can use latest Xerces and Xalan versions to ensure it's not something that has been fixed earlier.


text:
Q: Terminal not beeping on bell character I'm running a nearly vanilla installation of OS X Yosemite 10.10.1 with the usual Homebrew, MacPorts, and Fink.  I have barely anything installed with these utilities.  For some reason, my Terminal.app is not producing an audible bell, even with the preference enabled.  I have since enabled the visual bell, and at first it didn't produce a result either until I disabled the "Only when sound is muted" option.  I do not have my system's default audio device muted; it is in fact at 100% volume and fully functional.  It seems like Terminal.app is under the impression that my system audio is muted for some reason.  How can I get my Terminal.app to beep like it did in past versions of OS X?

A: There are several ways to do this on Terminal, but first make sure that in Terminal preferences > Advanced you have ticked the Audible bell option, otherwise you won't hear anything.  Now you can do any of the following to get the bell:

*

*$ echo ^G (hold down the ctrl key followed by V and then G to get ^G)

*$ printf "\a" or $ printf \\a

*$ echo -e "\a" or $ echo -e \\a

*$ tput bel
FYI: the way you installed Yosemite, whether via Homebrew, Macports etc., shouldn't affect this issue.

A: I came here via a search as I was experiencing exactly the same issue and tried all the steps suggested to Clay Freeman with the same results.
What worked for me was going into Systems Preferences / Sound, where I noticed that the slider for Alert Volume was at its leftmost setting. Sliding that to the right resolved the problem.

A: *

*On your Terminal what are the Bell options you have set in Preferences > Advanced?  As I said before, Audible bell and Visual bell should be ticked, otherwise that's the problem.

*Did you check that you can play other system sounds?  The standard system sound files for alerts are located in /System/Library/Sounds, and can be played from Terminal using afplay.  Try doing the following
$ afplay /System/Library/Sounds/Funk.aiff
You should be able to hear the sound.

*If not, then it could be a problem with value for the bell setting in the terminfo for terminal - terminfo is an internal database of terminal settings files that Terminal.app uses to perform actions for different terminal types - a collection of different settings files for different terminals.  The standard one is xterm-256color - you can find out which one by doing
$ echo $TERM
you should see xterm-256color.  The settings file for this terminal is a binary file located in a numbered subfolder of /usr/share/terminfo, to find out which one do
$ mdfind xterm-256color

You should see several lines, the first which should be something like /usr/share/terminfo/78, in which case that's where the settings file for xterm-256color is located.  Since it is a binary file you won't be able to read it out literally, but must do the following
$ infocmp

to print it out in human-readable form.  This is a long string of key-value pairs for different settings - to find out the bell settings for your terminal you can either manually scan the output for bel=^G or do
$ infocmp | grep bell

and you will see something like bel=^G, blink=\E[5m, bold=\E[1m, cbt=\E[Z, civis=\E[?25l.  The bel=^G key-pair is saying that using echo or printf followed by ^G (the key combination ctrl+V+G) from your terminal will produce the audible bell (using whatever standard system sound you are using, e.g. the Funk sound /System/Library/Sounds/Funk.aiff.  Using tput you can use the capability name bel to sound the bell also by doing $ tput bel.
OK, so tell me what you see when you have done this.  If the file is corrupted or damaged or the value is missing, or there is something you should be able to identify it.


text:
Q: Put function in parallel and wait for it to finish I need a gaussian blur function, which with big parameter takes a lot of time (1.8 s) to do. I want to make this function to work on its own, without stopping my entire code. This is a solution that I made. I was wondering - is there a proper way to do this?
is_done = False
done_blur = []
def get_blur(imag):
    global is_done, done_blur
    done_blur = cv2.GaussianBlur(imag, (333, 333), 0)
    is_done = True

_thread.start_new_thread(get_blur, (an_image,))
while True:## big loop, which has to keep working without waiting for blur function
    time.sleep(0.01)
    if is_done == True:
        back_blurred = done_blur
        is_done = False


text:
Q: Self Biased Current Reference I'm studying this circuit:

The author of my book says that the purpose of this circuit, called "Self Biased Current Reference", is to generate a current almost independently of the supply voltage. He also says that, if M3 and M4 are perfectly equal, than I1=Iref. Then it follows that:

from which I can find VGS1 and I1.
Question 1: When the author says that the current mirror is perfectly matched and then I1=Iref, isn't it too much simplified? He neglects channel lenght modulation, but in reality the source-to-drain voltages of M3 and M4 will not be equal (because we have just M1 under M3, instead we have M2 and a resistor under M4)
Question 2: Why is this current almost independent of VDD? The author says:
"The value of the generated current weakly depends on the supply voltage
because there is a high impedance element per branch capable of absorbing
possible supply variations. These two elements are the transistors M2 and M3.
The drain to source voltage of M1 and M4 can not change freely: the former is
two VGS above ground the latter is one VGS below VDD. Any supply fluctuation
is then "absorbed" by the high resistance that we have between drain and
source of M2 and M3"
I don't understand the strong part of the text: why is any fluctuation "absorbed" by the high resistance that we have between drain and source of M2 and M3?
Thank you

A: 1) Yes, channel length modulation must be ignored to get the \$I_1 = I_{Ref}\$ relationship. Otherwise, as you correctly point out, the currents will depend on the voltage dropped across the remainder of the two branches of the circuit.
Channel length modulation can only be ignored if the transistors stay in saturation. If not, the drain current will depend on the drain-source voltage. But as long as \$V_{dd}\$ is high enough and \$I_{Ref}\$ is low enough, the drain-source voltage and consequently the gate source voltage (due to the gate-drain tie) will be high enough to keep the transistors in saturation and the mirror function intact.
2) While the mirror function is due to M3 and M4, the constant current source function is due to M1 and M2. As the equations indicate, the current is dictated by the relatively constant \$V_{Th}\$ and \$R\$. So how is the current kept constant, even as \$V_{DD}\$ varies?
As \$V_{DD}\$ rises, something must "take up" the excess voltage. The author uses "absorb" instead of "take up", which is fair because as well as providing the additional voltage drop, the extra power must also be absorbed, but it's the increase in voltage drop that is important here. M1 and M2 cannot perform this function, because as stated their drain to source voltage is relatively fixed, so it is up to M2 and M3.
Since the current mirror is enforcing \$I_1 = I_{Ref}\$, and the current source is enforcing constant \$I_{Ref}\$, additional voltage due to \$V_{DD}\$ is dropped over the drain to source of M2 and M3. This will remain intact while ever M2 and M3 can continue to produce large enough drain to source voltages. MOSFETs are capable of producing high drain to source "resistance", so the circuit can be made stable.

A: The current mirror, as configured, is not highly compliant to power supply variation. A cascode mirror would greatly improve performance, but would add another DS voltage drop.
I ran a simulation, and it is well worth while.

A: Note this circuit (like many self-biased circuits) also has a possible state with all currents (nearly) zero. If the V on the gate of M2 is 0, then it will be off. There V across R is then 0, and so M1 is also off. When M2 is off, its drain current is 0, so M4's current is also 0 and it is off. M3 is therefore off. This leaves the gate of M2 'floating' (undefined), and it can settle at any V between 0 and VDD. If it settles at a low value, M2 will remain off, and the circuit won't have started.


text:
Q: Assistance with the creation of site offering lists based challenges I want to develop a website that offers lists based challenges. The idea is based upon the website http://listchallenges.com where users can look at different types of lists and select the options that they have personally done (watched a movie, went to a place, etc.
Here is a part of my code :
function ($) {
$('#ig-thumbs').delegate('img','click', function()
{
if(record.indexOf($(this).parent().attr('id'))  > -1 )
{
$(this).removeClass("counted");

if(a < 1)
{}
else
{
a=a-1;

document.getElementById("result").value=a;
record.pop($(this).parent().attr('id'),record);
}
}
else
{

record.push($(this).parent().attr('id') ) ;

$(this).addClass("counted")

a=a+1;
document.getElementById("text").value=a;

}

});

This code basically uses the variable a as the counter and displays its value in a text box called "result". "this" refers to a individual image that is being clicked which gets a class "counted" when it is clicked and the class is removed when it is clicked again. All of this is working fine but the problem arises in the dynamic updation of the variable a. Once a image is clicked the value of a increments by 1 but sometimes I have to click on the image twice to decrement the value.
For eg - If their are 8 items and I click on them once the value of a becomes 8 and gets displayed correctly. But when I click on all the images again the value does not become 0 but rather comes down to 1 or 2 and I have to click on the first or second image again to decrement the value to 0.
Can anybody help me in optimizing the code as I have tried many different things but I am unable to get it right.

A:
0

i hope this code help you :)


text:
Q: SSO with Spring Security 3.x.x I need to implement SSO with Spring Security 3.2.9 / Java 1.7 / Spring MVC, and upgrading to Spring Security 4 and Java 1.8 isn't an option. I was able to integrate CAS 4, except it fails after login redirect because  of the version of Spring Security we are using (we don't want to use any versions of CAS earlier than 4).  I have also looked at Gluu and Keycloak, but it looks like both require Java 1.8 on the client side and Spring Security 4.
The only SSO platform that I have been able to find that meets my requirements is MITREid Connect, but the downside of that is it doesn't look like there is any React library if we want to use that in the future.
Does anyone have experience integrating SSO on older versions of Spring Security? This is my first time implementing SSO.

A: Spring Security 3.x with Spring Security SAML extension works well to achieve standards based SSO.


text:
Q: jquery .live('click') vs .click() I am wondering whether there are any circumstances where it would be better to use .click(function {...}); rather than .live('click', function {...});?
From what I gather the live option seems to be a better option and I am hence using it in almost all circumstances instead of the plain .click(), especially given a lot of my code is loaded asynchronously.
EDIT:
Another part to this question. If I'm asynchoronously loading all the javascript in, .click will still pickup all elements already in the dom. Right?

A: "live" is needed when you dynamically generate code.
Just look the below example :

$("#div1").find('button').click(function() {
    $('<button />')
     .text('BUTTON')
     .appendTo('#div1')
})
$("#div2").find('button').live("click", function() {
    $('<button />')
     .text('BUTTON')
     .appendTo('#div2')
})
button {
  margin: 5px;
}

  <button>Click</button>

  <button>Live</button>

without "live" the click-event occurs only when you click the first button, with "live" the click-event occurs also for the dynamically generated buttons

A: Always use click if you not dynamically add elements.
live works by adding an event listener to the document root and listens for bubbled up events. An alternative is delegate, which works the same, but binds the event handler to the specified element.
This way, the event has not to bubble up the whole DOM and is caught earlier.

A: .live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')

A: There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:
$(this).children().live('click',doSomething);

It needs a selector to work properly because of the way events bubble up the DOM tree.
Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:
$(selector).on('click', function () {
    ...
});

and to replace live:
$(document).on('click', selector, function () {
    ...
});

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.

A: (Note 29/08/2017: live was deprecated many versions ago and removed in v1.9. delegate was deprecated in v3.0. In both cases, use the delegating signature of on instead [also covered below].)

live happens by capturing the event when it's bubbled all the way up the DOM to the document root, and then looking at the source element. click happens by capturing the event on the element itself. So if you're using live, and one of the ancestor elements is hooking the event directly (and preventing it continuing to bubble), you'll never see the event on your element. Whereas normally, the element nearest the event (click or whatever) gets first grab at it, the mix of live and non-live events can change that in subtle ways.
For example:

jQuery(function($) {

  $('span').live('click', function() {
    display("<tt>live</tt> caught a click!");
  });

  $('#catcher').click(function() {
    display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");
    return false;
  });

  function display(msg) {
    $("
").html(msg).appendTo(document.body);
  }

});

  Click me
  or me
  or me

    I'm two levels in
    so am I

    I'm two levels in AND my parent interferes with <tt>live</tt>
    me too

I'd recommend using delegate over live when you can, so you can more thoroughly control the scope; with delegate, you control the root element that captures the bubbling event (e.g., live is basically delegate using the document root as the root). Also, recommend avoiding (where possible) having delegate or live interacting with non-delegated, non-live event handling.

Here several years later, you wouldn't use either live or delegate; you'd use the delegating signature of on, but the concept is still the same: The event is hooked on the element you call on on, but then fired only when descendants match the selector given after the event name:

jQuery(function($) {

  $(document).on('click', 'span', function() {
    display("<tt>live</tt> caught a click!");
  });

  $('#catcher').click(function() {
    display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");
    return false;
  });

  function display(msg) {
    $("
").html(msg).appendTo(document.body);
  }

});

  Click me
  or me
  or me

    I'm two levels in
    so am I

    I'm two levels in AND my parent interferes with <tt>live</tt>
    me too

A: All objects that would be associated with the .click must exist when you set the event.
Example: (in pseudo code) the append can be $("body").append() for example
append('
...
');
$("div.something").click(function(){...});
append('
...
');

Click works for foo but doesn't work for bar
Example2:
append('
...
');
$("div.something").live("click",function(){...});
append('
...
');

click works for both foo and bar
With .live('click'... you can dynamicaly add more objects after you created the event and the clicking event will still work.

A: As 'live' will handle events for future elements that match the current selector, you may choose click as you don't want that to happen - you only want to handle the current selected elements.
Also, I suspect (though have no evidence) that there is a slight efficiency using 'click' over 'live'.
Lee

A: From what I understand the key difference is that live() keeps an eye open for new DOM elements that match the selector you are working on, whereas click() (or bind('click')) attach the event hook and are finished.
Given that alot of your code is loaded asynchronously, using live() will make your life alot easier. If you don't know exactly the code you are loading but you do know what kind of elements you will be listening to, then using this function makes perfect sense.
In terms of performance gains, one alternative to using live() would be to implement an AJAX callback function to re-bind the event hooks.
var ajaxCallback = function(){
 $('*').unbind('click');
 $('.something').bind('click', someFunction);
 $('.somethingElse').bind('click', someOtherFunction);
}

You will need to keep proper track of your event hooks and make sure this function is rebinding the proper events.
p.s. Ajax methods .get(), .post(), .load() and .ajax() all let you specify a callback function.

A: If you need simplify code then live is better in the most cases.
If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).

A: remember that the use of "live" is for "jQuery 1.3" or higher
in version "jQuery 1.4.3" or higher is used "delegate"
and version "jQuery 1.7 +" or higher is used "on"
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

As of jQuery 1.7, the .live() method is deprecated.
check http://api.jquery.com/live/
Regards,
Fernando

A: In addition to T.J. Crowders answer, I have added some more handlers - including the newer .on(...) handler to the snippet so you can see which events are being hidden and which ones not.
What I also found is that .live() is not only deprecated, but was deleted since jQuery 1.9.x. But the other ones, i.e. .click, .delegate/.undelegate and .on/.off
are still there.
Also note there is more discussion about this topic here on Stackoverflow.
If you need to fix legacy code that is relying on .live, but you require to use a new version of jQuery (> 1.8.3), you can fix it with this snippet:
// fix if legacy code uses .live, but you want to user newer jQuery library
if (!$.fn.live) {
    // in this case .live does not exist, emulate .live by calling .on
    $.fn.live = function(events, handler) {
      $(this).on(events, null, {}, handler);
    };
}

The intention of the snippet below, which is an extension of T.J.'s script, is that you can try out by yourself instantly what happens if you bind multiple handlers - so please run the snippet and click on the texts below:

jQuery(function($) {

  // .live connects function with all spans
  $('span').live('click', function() {
    display("<tt>live</tt> caught a click!");
  });

  // --- catcher1 events ---

  // .click connects function with id='catcher1'
  $('#catcher1').click(function() {
    display("Click Catcher1 caught a click and prevented <tt>live</tt> from seeing it.");
    return false;
  });

  // --- catcher2 events ---

  // .click connects function with id='catcher2'
  $('#catcher2').click(function() {
    display("Click Catcher2 caught a click and prevented <tt>live</tt>, <tt>delegate</tt> and <tt>on</tt> from seeing it.");
    return false;
  });

  // .delegate connects function with id='catcher2'
  $(document).delegate('#catcher2', 'click', function() {
    display("Delegate Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");
    return false;
  });

  // .on connects function with id='catcher2'
  $(document).on('click', '#catcher2', {}, function() {
    display("On Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");
    return false;
  });

  // --- catcher3 events ---

  // .delegate connects function with id='catcher3'
  $(document).delegate('#catcher3', 'click', function() {
    display("Delegate Catcher3 caught a click and <tt>live</tt> and <tt>on</tt> can see it.");
    return false;
  });

  // .on connects function with id='catcher3'
  $(document).on('click', '#catcher3', {}, function() {
    display("On Catcher3 caught a click and and <tt>live</tt> and <tt>delegate</tt> can see it.");
    return false;
  });

  function display(msg) {
    $("
").html(msg).appendTo(document.body);
  }

});

  Click me
  or me
  or me

    I'm two levels in
    so am I

    #1 - I'm two levels in AND my parent interferes with <tt>live</tt>
    me too

    #2 - I'm two levels in AND my parent interferes with <tt>live</tt>
    me too

    #3 - I'm two levels in AND my parent interferes with <tt>live</tt>
    me too


text:
Q: How to fix a cyrillic character/utf encoding issue in php I'm trying to access a table which is named, say, "Вильгельм_Телль". So I do the following:
$group = "Вильгельм_Телль";
$msql = "SELECT result FROM $group";
What I get is:

check the manual that corresponds to your MySQL server version for the right syntax to use near '�ильгельм_Телль' at line 1

Extra information:

*

*The issue only seems to affect only the first character of the string

*My meta charset is set to UTF8

*My PHP charset is set to UTF8 using mysqli_set_charset, I get the same result using 'header (...)'

*My file is saved as UTF8 without BOM

*I'm using WAMP to serve my page

*EDIT: it doesn't work as one-word either

A: You must use `` (quote identifier) for sql queries.
SELECT * FROM `Вильгельм Телль`

Recommendation: do not use anything other ansi characters for table names, columns etc. You may face problems in other apps, cli etc.


text:
Q: best way to check element combination exist in array in typescript I have array with some element that I want to check if some element combination exist in array that target element is following by any element of checkingSet, if yes, then return true otherwise, return false. For example,
if inputArray is ['a', 'b', 'c', 'd'] and looking for combination is ['a', 'd'] then it should return true because inputArray has both in the right sequence.
if inputArray is ['d', 'b', 'c', 'd', 'a'] and the combination is ['a', 'd'], then it should be false because inputArray includes both elements but in wrong order
or
isExist(['a', 'd']) => true
isExist(['a', 'a', 'd']) => true
isExist(['e', 'd']) => false

I can use Set and while loop
but I am wondering if any more elegant or modern way to do?
export function isExist(checkArray): boolean {
  let hasA = false;
  let hasB = false;
  checkingSet = new Set(['b', 'c', 'd'])
  const target = 'a'
  inputArray = [...checkArray]
  while (inputArray && !!inputArray.length) {
    const lastOne = inputArray.pop();
    if (!hasA && !!lastOne) {
      hasA = chekcingSet.has(lastOne);
    }
    if (!hasB && !!lastOne) {
      hasB = lastOne === target;
    }
    if (hasA && hasB) {
      return true;
    }
  }
  return false;
}

A: To check that the array contains 'a', and after this 'a' at least one of ['b', 'c', 'd'] is in the array you can do this. First, get the index of the first 'a' in the array, then check if some value of ['b', 'c', 'd'] is included in that array after this start index.

function doesExist(arr) {
  const startPos = arr.indexOf('a')
  if (startPos < 0)
    return false
  return ['b', 'c', 'd'].some(char => arr.includes(char, startPos + 1))
}

console.log(doesExist(['a', 'd']))
console.log(doesExist(['a', 'a', 'd']))
console.log(doesExist(['e', 'd']))
console.log(doesExist(['d', 'a']))

A: This is the general version, it's O(n).
function doesDupleExistInOrder([el1, el2], arr) {
    let index = arr.indexOf(el1)
    if (index == -1) return false;
    return arr.includes(el2, index + 1)
}

console.log(doesDupleExistInOrder(["a", "d"], ["a", "b", "c", "d", "e"])); // true
console.log(doesDupleExistInOrder(["a", "b"], ["a", "b", "c", "d", "e"])); // true
console.log(doesDupleExistInOrder(["d", "e"], ["a", "b", "c", "d", "e"])); // true

console.log(doesDupleExistInOrder(["d", "a"], ["a", "b", "c", "d", "e"])); // false
console.log(doesDupleExistInOrder(["d", "a"], ["a"]));                     // false
console.log(doesDupleExistInOrder(["d", "a"], []));                        // false

If you want a specific version then just curry the general function AKA:
let doesADExist = arr => doesDupleExistInOrder(["a", "d"], arr);
console.log(doesADExist(["a", "b", "c", "d", "e"]));  // true


text:
Q: Plot a group box or violin plot from two data frames in python I have two dataframes of equal size. I would like to plot the distribution of the data on a boxplot or violin plot as a pair. Thus far I was able to plot them, however, the distributions are top of each other. How can I plot them next to each other?
fig, ax = plt.subplots(figsize=(15, 6))
ax = sns.violinplot(data=dfInside, color="blue")
ax = sns.violinplot(data=dfOutside, color="red")
plt.show()

My current result:

A: I solved it by merging the two data frames. Creating a key, which I provided hue="key" in the seaborn plot. This solved the issue. Ps I also had to restructure the data.


text:
Q: What´s the most efficient way to store date based availibilites i´m new here and have a project where i have a performance problem that seems hard to fix. I have created a search for objects that have availibilities means a very simple structure:
ObjectID | Date | Number of available objects
---------------------------------------------
Object1  | 01.01.2019 | 1
Object1  | 02.01.2019 | 1
Object1  | 03.01.2019 | 0
Object1  | 04.01.2019 | 1
Object1  | 05.01.2019 | 1
Object2  | 01.01.2019 | 1
Object2  | 02.01.2019 | 1
Object2  | 03.01.2019 | 0
Object2  | 04.01.2019 | 1
Object2  | 05.01.2019 | 1

I´m working with mysql and php
A typical query would be:
Which objects are available between 01.01.2019 - 28.02.2019 10 days available in a row.
It´s not really hard to make it working with mysql but once you have more then 10 users using the searchfunction the server load becomes extremly high eventough the table is optimised (indexes etc.) The server has 2 cores with 4 GB of RAM.
I also tried to store the dates comma separated per object in a table and let the application search but that creates extrem high traffic between application and database which is also not a real solution.
In total we have around 20.000 Objects and availabilities stored for max. 500 days so we have around 10.000.000 datasets in my first solution.
Does anybody have and idea what´s the most efficient way toDo this ?
(How to store it to make search fast ?)
For this project i sadly can not cache the searches.
Thanks for you help and Kind Regards, Christoph

A: *

*Don't store dates in 28.02.2019 format.  Flip it over, then use a DATE datatype in the table.  Please provide SHOW CREATE TABLE.

*What is your algorithm for searching?

*The header says "number of objects", yet the values seem to be only 0 or 1, as if it is a boolean flag??

*What is the maximum timespan?  (If under 64, there are bit-oriented tricks we could play.)

By looking at adjacent rows (cf LAG(), if using MySQL 8.0), decide when an object changes state.  Save those dates.
From that, it is one more hop to get "how many consecutive days" starting at one of those dates.  This will be a simple query, and very fast if you have a suitable composite index.


text:
Q: I am making a stop watch for one part of my app using kivy.clock but it's giving Attribute Error There are multiple windows in my app and a "Tracker" is one of them. The tracker will have a stop watch on display and will keep track of the time spent by entering the total time at the end into a database. (I have not coded the database part yet. I am simply printing the total time into the console for now).
For some reason, I keep running into an Attribute Error.
Code for Tracker Class:
class Tracker(Screen):
    time = 0
    start = False

    def start_stop(self):
        self.root.ids.start_stop_btn.text = ('Start'
                                         if self.start else 'Stop')
        self.start = not self.start
        Clock.schedule_interval(self.add_time, 1)

    def add_time(self, *args):
        while self.start:
            self.root.ids.sec_ones.text = str(int(self.root.ids.sec_ones.text) + 1)
            if self.root.ids.sec_ones.text == '10':
                self.root.ids.sec_tens.text = str(int(self.root.ids.sec_tens.text) + 1)
                self.root.ids.sec_ones.text = '0'
                if self.root.ids.sec_tens.text == '6':
                    self.root.ids.minute_ones.text = str(int(self.root.ids.minute_ones.text) + 1)
                    self.root.ids.sec_tens.text = '0'
                    if self.root.ids.minute_ones.text == '10':
                        self.root.ids.minute_ones.text = '0'
                        self.root.ids.minute_tens.text = str(int(self.root.ids.minute_tens.text) + 1)
            self.time += 1
        print(self.time)

And the Tracker Class in kv file:
<Tracker>:

    name: "Tracker"
    Label:
        text: "Timer: "
        font_size: 50
        pos_hint: {'x': 0.1, 'top': 1}
        size_hint: 0.2, 0.2

    Label:
        id: minute_tens
        text: '0'
        pos_hint: {'x': 0.36, 'top': 0.99}
        font_size: 40
        size_hint: 0.1, 0.2
        canvas.before:
            Color:
                rgba: (0.349, 0.349, 0.349, 1)
            Rectangle:
                pos: self.pos
                size: self.size

    Label:
        id: minute_ones
        text: '0'
        pos_hint: {'x': 0.47, 'top': 0.99}
        font_size: 40
        size_hint: 0.1, 0.2
        canvas.before:
            Color:
                rgba: (0.349, 0.349, 0.349, 1)
            Rectangle:
                pos: self.pos
                size: self.size

    Label:
        text: ':'
        pos_hint: {'x': 0.59, 'top': 0.99}
        font_size: 40
        size_hint: 0.05, 0.2

    Label:
        id: sec_tens
        text: '0'
        pos_hint: {'x': 0.65, 'top': 0.99}
        font_size: 40
        size_hint: 0.1, 0.2
        canvas.before:
            Color:
                rgba: (0.349, 0.349, 0.349, 1)
            Rectangle:
                pos: self.pos
                size: self.size

    Label:
        id: sec_ones
        text: '0'
        pos_hint: {'x': 0.76, 'top': 0.99}
        font_size: 40
        size_hint: 0.1, 0.2
        canvas.before:
            Color:
                rgba: (0.349, 0.349, 0.349, 1)
            Rectangle:
                pos: self.pos
                size: self.size

    Button:
        id: start_stop_btn
        text: 'Start'
        pos_hint: {'x': 0.6, 'top': 0.77}
        size_hint: 0.1, 0.06
        on_release: root.start_stop()

    SmoothButton:
        text: "Back"
        pos_hint: {'x': 0.8, 'top': 0.15}
        size_hint: 0.15, 0.05
        on_release:
            app.root.current = "HomePage"
            root.manager.transition.direction = "right"

The error looks like this:

The app itself runs. The error only comes after clicking the start button.

A: the only class has root is the App class so the Tracker has no root attribute there
in the start_stop method remove the "root" like the follwing
def start_stop(self):
        self.ids.start_stop_btn.text = ('Start'
                                         if self.start else 'Stop')