text:
Q: What is the technology for adding a text loader? I want to know if there's a technology for text loader. I saw this effect on some sites. When the DOM is not fully load there's an effect of loading in the certain text. I want to know if that's a picture, but eventually that will cause the site not to load fast. Or is that a design borders that will be remove on fully loaded DOM.
This is the picture of example:

Since I can't find the correct way to do it. Just a little bit of idea or insights how to achieve it would be helpful.

A: I  applied that effect using css and css transitions property with javascript. So i think that effect is created with css because some byte of code need to create that effect. so document do not need to load a image file which contains a lot of kb.
Here is my example code for you:

function getPost(){
setTimeout(function(){
document.getElementById("demo").innerHTML="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo,";
}, 900)}
getPost();
#demo .text-plbar1 {
    height: 20px;
    width: 80%;
    display: block;
    margin-bottom: 10px;
}
#demo .text-plbar2 {
    height: 20px;
    width: 60%;
    display: block;
    margin-bottom: 10px;
}
#demo .text-plbar3 {
    height: 20px;
    width: 40%;
    display: block;
    margin-bottom: 10px;
}
#demo .text-plbar4 {
    height: 20px;
    width: 80%;
    display: block;
    margin-bottom: 10px;
}
@keyframes placeHolderShimmer {
            0% {
                background-position: -468px 0
            }
            100% {
                background-position: 468px 0
            }
        }

        .animated-background {
            animation-duration: 1s;
            animation-fill-mode: forwards;
            animation-iteration-count: infinite;
            animation-name: placeHolderShimmer;
            animation-timing-function: linear;
            background: #f6f7f8;
            background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
            background-size: 800px 104px;
            height: 96px;
            position: relative;
        }

You can apply this effect using php, ajax, javascript when you fetch data from database;


text:
Q: Duplicate symbol error using AFNetworking framework I am using Paynimo Payment Gateway in my iOS app.
This framework contains AFNetworking, SBjson files in it.
My Project also contains these files for other usage. So it gives duplicate symbols errors for those file. When I try to remove any one of those files, it gives error of file not found.
How can I solve this?

A: You must have to remove any one. Next job is select files from project & include in target membership see attached
.

A: Consider dependency manager like CocoaPods(https://github.com/CocoaPods/CocoaPods) or Carthage (https://github.com/Carthage/Carthage)

A: Remove afnetworking files in your app and use Paynimolib afnetworking and do the following.
1.#import
2.AFHttpoperationmanager replace to AFHttpsessionmanager

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why was Starways Congress fooled in the beginning of Xenocide? Near the beginning of Xenocide,

 Jane cuts off the Invasion Fleet.

Later, it is implied that

 She did it right after Starways Congress sent the order to use the Little Doctor.

So, if you send an order, and right after your communication gets cut off, don't you realize something's tracking your ansibles? If I'm wrong about them being simultaneous, then tell me. I figure the order had to come either at the same time, or later, and Starways Congress wouldn't send it after they were cut off.

A: I believe you are right in the timing.
Starways Congress sent the order to the fleet, and Jane blocked ansible communication with the fleet in order to stop them from receiving the order.
It's important to note that Jane was fully aware that cutting off communication with the fleet would eventually result in her existence being revealed.
Starways Congress was fooled because, at the time, it simply was nearly inconceivable that anything would have the power to selectively interfere with ansible activity between multiple ships.  Ansible communication was thought of as infallible, and the computer security used to protect and regulate it was regarded as equally infallible.  As a result, other scenarios such as complete, simultaneous destruction of the fleet were likely considered first.
Eventually they did realize that the loss of communication with the fleet had to have been because of direct intervention by someone or something with the ability to track, monitor, and control all ansible communications.  However, reaching this conclusion took the diligent and methodical analysis of one of the most brilliant minds in all of humanity: Han Qing-jao of the planet Path.
Without the artificially-enhanced intelligence of Han Qing-jao, it might have taken months, or even years, before anyone started speculating on direct access to the ansible signals, and even then they probably would have started with the idea of a computer virus, rather than a sentient artificial intelligence (in fact, I believe even Han Qing-jao assumed it was a virus at first), but they would probably have reached the correct conclusion eventually.


text:
Q: PDF/html/epub downloads doesn't update for either latest or (manually triggered) stable build In my project, http://lacinia.readthedocs.io/en/latest/, the downloads (PDF, epub, single-page HTML) doesn't update on a build.  It looks like it builds, but the download link keeps downloading a version from Oct 03.  I've done some significant work since then.
The latest link works correctly, showing changes within minutes of my pushing changes.
It's not clear to me whether the build works, but the latest files are simply not put in the correct folder for download, or if the build is broken in some way.
I'd appreciate any clues on how to fix or at least properly diagnose this.

A: Digging around, I found the "wipe build" functionality; that plus, perhaps, a Cmd-Shift-R, to ensure I was downloading fresh and not from local cache, got me the latest versions.


text:
Q: How to writing logs to STDERR base on log level using Serilog I'm using Serilog for my .netcore application and write logs to console.
And all logs come to STDOUT streams, but the requirement is Error and Fatal level should come to STDERR streams. I already added "standardErrorFromLevel": "Error" to arg of Writeto Console setting in appsetting.json but not working and my STDERR still empty.
How do I redirect the logs for error and fatal level to STDERR? Please help!!!

A: I tried to achieve the same thing as you and I got it to work with VS.Net 2020 and Serilog.
My appSettings.json looks like this:
{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "standardErrorFromLevel": "Error"
        }
      }
    ],
  }
}

I tried this with setting command line arguments in my web projects properties, Debug, General, Launch Profiles to:
>c:\temp\stdout.log 2>c:\temp\stderr.log. And the logging gets nicely separated into these two files.
My .Net6 program.cs contains this for SeriLog:
builder.Host.UseSerilog((context, configuration) => configuration
    .Enrich.FromLogContext()
    .ReadFrom.Configuration(context.Configuration)
    })
);

To make SeriLog the default ILogger<T> for dependency injection in controllers, I have added:
builder.Services.AddLogging(x =>
{
    x.ClearProviders();
    x.AddSerilog(dispose: true);
});

Might it be you are using DI and not actually be using SeriLog at all?
If you want to try and set the propeties in code, just add
    .WriteTo.Async(x =>
    {
         x.Console(standardErrorFromLevel: LogEventLevel.Error);
    }

inside UseSerilog().
I have to following SeriLog packages installed:

*

*Serilog.AspNetCore 4.1.0

*Serilog.Extensions.Logging 3.1.0

*SeriLog.Settings.Configuration 3.3.0

*SeriLog.Extensions.Logging.File 2.0.0

The latter should not be relevant there.


text:
Q: Finding records that are not contianed in another query I have two table that are related to each other: QUOTERun and QUOTERunResults.  QUOTERun contains all of the items that are needed for a particular quote.  QUOTERunResults contains records for all of the vendor responses.  I have a program that analyzes those responses and selects the vendor that is the best fit and set a field called Preffered to true.  Some times none of the vendors will work.  I need to create a list of all the records in QUOTERun that don't have a matching record in QUOTERunResults that is marked as preffered.
Here is what I have so far:
Set rs1 = CurrentDb.OpenRecordset("SELECT ReferenceNumber FROM [QUOTERun] WHERE RunID = " & TempRunID, dbOpenDynaset)
Set rs2 = CurrentDb.OpenRecordset("SELECT ReferenceNumber, Preffered FROM [QUOTERunResults] " & _
                                  "WHERE RunID = " & TempRunID & " AND Preffered = True", dbOpenDynaset)
If (rs2.RecordCount = 0) Then
   TempListNotComplete = "NONE OF THE VENDOR RESPONSES HAD ENOUGH STOCK. NO RECORDS HAVE BEEN MARKED AS PREFFERED."
ElseIf (rs1.RecordCount <> 0) Then
   rs1.MoveFirst
   Do While rs1.EOF <> True
      rs2.FindFirst "ReferenceNumber = " & rs1.Fields("[ReferenceNumber]").value
      If (rs2.Fields("[ReferenceNumber]").value <> rs1.Fields("[ReferenceNumber]").value) Then
         If (TempListNotComplete = "") Then
            TempListNotComplete = rs1.Fields("[ReferenceNumber]").value
     Else
            TempListNotComplete = TempListNotComplete & ", " & rs1.Fields("[ReferenceNumber]").value
     End If
      End If
      rs1.MoveNext
   Loop
End If

is there a more efficient way of doing the above?

A: You can create a query in SQL view of the query design window:
SELECT a.ReferenceNumber
FROM
    (SELECT ReferenceNumber
     FROM [QUOTERun]
     WHERE RunID = [Enter TempRunID]) a
LEFT JOIN
    (SELECT ReferenceNumber, Preffered
     FROM QUOTERunResults
     WHERE RunID = [Enter TempRunID] AND Preffered = True) b
On a.ReferenceNumber=b.ReferenceNumber
WHERE b.ReferenceNumber Is Null

The above should show all records in the first derived table that are not in the second derived table.


text:
Q: Faster way to concatenate millions of dataframes without using pd.concat I have about 12 million dataframes stored in a one pickle file as list of dataframes. I want to concatenate these dataframes to have just one dataframe.
I have tried the following:

*

*pd.concat this is quite slow.

*suggestion from https://gist.github.com/TariqAHassan/fc77c00efef4897241f49e61ddbede9e , this takes about 24hrs.
Python code for 1:
'''
from src.utils import load_pickle
data = load_pickle('the file path')
result = pd.concat(data)

'''
Python code for 2:
'''
def fast_flatten(input_list):
    return list(chain.from_iterable(input_list))
COLUMN_NAMES = data[0].columns
df_dict = dict.fromkeys(COLUMN_NAMES, [])
for col in tqdm(COLUMN_NAMES):
    extracted = (frame[col] for frame in data) # Use a generator to save memory
    df_dict[col] = fast_flatten(extracted)  # Flatten and save to df_dict
result = pd.DataFrame.from_dict(df_dict)[COLUMN_NAMES]

'''
The final result should be of size 20000042 by 47.
I will appreciate any efficient way to reduce the time from 24 hours.
Thanks


text:
Q: Не отображается slider slick в wordpress Такая проблема. Я натягиваю страницу на wordpress. По каким то причинам у меня ВООБЩЕ не отображается слайдер slick. При этом код есть и даже показывает значок якобы есть, но сам слайдер как будто стал невидимым. Буду очень рада за помощь!
P.s теги php я не добавила, но ни есть.
Файл index.php

   <?php get_header(); ?>

    <content class = "background_content">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_1.png" alt="">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_2.png" alt="">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_3.png" alt="">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_1.png" alt="">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_2.png" alt="">

<img src="<?php bloginfo('template_url'); ?>/assets/img/slide_man_3.png" alt="">

    </content>
    <?php get_footer(); ?>

Файл functions.php

// правильный способ подключить стили и скрипты
add_action( 'wp_enqueue_scripts', 'clothing_store_scripts' );
// add_action('wp_print_styles', 'theme_name_scripts'); // можно использовать этот хук он более поздний
function clothing_store_scripts() {
    wp_enqueue_style( 'style-clothing_store', get_stylesheet_uri() );
    wp_enqueue_script( 'script-clothing_store', get_template_directory_uri() . 'slider.js', array(), '1.0.0', true );

    wp_enqueue_script( 'script-bootstrap.js', get_template_directory_uri() . 'bootstrap/bootstrap.js', array(), '1.0.0', true );
    wp_enqueue_script( 'script-bootstrap.min.js', get_template_directory_uri() . 'bootstrap/bootstrap.min.js', array(), '1.0.0', true );
    wp_enqueue_script( 'script-jquery.min.js', get_template_directory_uri() . 'bootstrap/jquery.min.js', array(), '1.0.0', true );
    wp_enqueue_script( 'script-slick.min.js', get_template_directory_uri() . 'bootstrap/slick.min.js', array(), '1.0.0', true );
    wp_enqueue_script( 'script-html5.js', get_template_directory_uri() . 'bootstrap/html5shiv.js', array(), '1.0.0', true );
    wp_enqueue_script( 'script-resp.js', get_template_directory_uri() . 'bootstrap/respond.min.js', array(), '1.0.0', true );

    wp_enqueue_style( 'style-fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:300,400,700');
    wp_enqueue_style( 'style-boot_min_css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' );
    wp_enqueue_style( 'style-font-awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' );

    wp_enqueue_script( 'script-jquery', 'https://code.jquery.com/jquery-3.5.1.min.js' );
    wp_enqueue_script( 'script-popper_min_js', 'https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js' );
    wp_enqueue_script( 'script-boot_min_js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' );
    wp_enqueue_script( 'script-jquery_min_js', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' );
    wp_enqueue_script( 'script-slick_min_js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js' );

}

Файл style.css

    /* carousel of men's goods */
    .osnovaniye {
    padding: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    }
    .slick-slider {
    min-width: 0;
    }
    .slick-list {
    overflow: hidden;
    }
    .slick-track {
    display: flex;
    align-items: flex-start;
    }
    .slider {
    position: relative;
    padding: 0px 60px;
    left: 45px;
    top: 205px;
    }
    .slider .slick-arrow {
    position: absolute;
    top: 50%;
    margin: -20px 0px 0px 0px;
    font-size: 0;
    width: 30px;
    height: 30px;
    }
    .slider .slick-arrow.slick-prev {
    position: absolute;
    background-image: url("assets/img/strelka_prev.png");
    position: absolute;
    left: -35px;
    top: 215px;
    width: 54px;
    height: 85px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: none;
    }
    .slider .slick-arrow.slick-next {
    position: absolute;
    background-image: url("assets/img/strelka_next.png");
    position: absolute;
    left: 1570px;
    top: 215px;
    width: 54px;
    height: 85px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: none;
    }
    .slider .slick-arrow.slick-disabled {
    opacity: 1;
    }
    .moving_slayda {
    padding: 0px 20px;
    }
    .moving_slayda img {
    width: 391px;
    height: 477px;
    }

    /* carousel of women's goods */
    .osnovaniye_1 {
    padding: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    }
    @media (max-width: 767px) {
    .osnovaniye_1 {
    padding: 50px 10px;
    }
    }
    .slick-slider {
    min-width: 0;
    }
    .slick-list {
    overflow: hidden;
    }
    .slick-track {
    display: flex;
    align-items: flex-start;
    }
    .slider_1 {
    position: relative;
    padding: 0px 60px;
    left: 45px;
    top: 475px;
    }
    @media (max-width: 767px) {
    .slider_1 {
    padding: 0px 40px;
    }
    }
    .slider_1 .slick-arrow {
    position: absolute;
    top: 50%;
    margin: -20px 0px 0px 0px;
    font-size: 0;
    width: 30px;
    height: 30px;
    }
    .slider_1 .slick-arrow.slick-prev {
    position: absolute;
    background-image: url("assets/img/strelka_prev.png");
    position: absolute;
    left: -35px;
    top: 215px;
    width: 54px;
    height: 85px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: none;
    }
    .slider_1 .slick-arrow.slick-next {
    position: absolute;
    background-image: url("assets/img/strelka_next.png");
    position: absolute;
    left: 1570px;
    top: 215px;
    width: 54px;
    height: 85px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: none;
    }
    .slider_1 .slick-arrow.slick-disabled {
    opacity: 1;
    }
    .moving_slayda_1 {
    padding: 0px 20px;
    }
    .moving_slayda_1 img {
    width: 391px;
    height: 477px;
    }
    .sub{
    position: absolute;
    font-size: 20px;
    left: 740px;
    top: 670px;
    color: #7a7a7a;
    }
    .scroll-slider{
    display:none;
    }
    .moving_slayda{
    display: none;
    }
    .scroll-slider_1{
    display: none;
    }
    .moving_slayda_1{
    display: none;
    }


text:
Q: Not Loading Indexed Sources for nuget packages from Azure Devpos during debugging Trying to use azure yml for build pipleline to publish symbols to allow nuget pkg to be debuggable usin azure devops. I see PDB files are donwloaded to the symbols cache folder but stepping thru is asking for source file location in visual studio, even when i have indexed the source code during publish symbol.
I have tried to enable different options in visual studio debugging but nothing seems to help
Here is my yml

# ASP.NET Core
# Build and test ASP.NET Core projects targeting .NET Core.
# Add steps that run tests, create a NuGet package, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/dotnet-core

name: $(BuildDefinitionName)_$(Year:yyyy).$(Month).$(DayOfMonth)$(Rev:.r) # need this for byBuildNumber verisonScheme nuget pack
# the build will trigger on any changes to the master branch
trigger:
- master

# the build will run on a Microsoft hosted agent, using the lastest Windows VM Image
pool:
  vmImage: 'windows-latest'

# these variables are available throughout the build file
# just the build configuration is defined, in this case we are building Release packages
variables:
  buildConfiguration: 'Release'

#The build has 3 seperate tasks run under 1 step
steps:

# The first task is the dotnet command build, pointing to our csproj file
- task: DotNetCoreCLI@2
  displayName: 'dotnet build'
  inputs:
    command: 'build'
    arguments: '--configuration $(buildConfiguration)'
    projects: 'src/Common.Core/Common.Core.csproj'

- task: PublishSymbols@2
  inputs:
    symbolsFolder: '$(Build.SourcesDirectory)'
    searchPattern: '**/bin/**/*.pdb'
    indexSources: true
    publishSymbols: true
    symbolServerType: 'teamServices'
    treatNotIndexedAsWarning: true
    symbolsProduct: '$(Build.DefinitionName)'
    symbolsVersion: '$(Build.BuildNumber)'
    symbolsArtifactName: '$(name).Symbols_$(BuildConfiguration)'

# The second task is dotnet pack command again pointing to the csproj file
# The nobuild means the project will not be compiled before running pack, because its already built in above step
- task: DotNetCoreCLI@2
  displayName: "dotnet pack"
  inputs:
    command: 'pack'
    arguments: '--configuration $(buildConfiguration)'
    packagesToPack: 'src/Common.Core/Common.Core.csproj'
    nobuild: true
    includeSymbols: true
    versioningScheme: 'byBuildNumber'

# The last task is a nuget command, nuget push
# This will push any .nupkg files to the 'Nuget' artifact feed
# allowPackageConflicts allows us to build the same version and not throw an error when trying to push
# instead it just ingores the latest package unless the version changes
- task: NuGetCommand@2
  displayName: 'nuget push'
  inputs:
    command: 'push'
    feedsToUse: 'select'
    packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg'
    nuGetFeedType: 'internal'
    publishVstsFeed: 'myNuget'
    allowPackageConflicts: true

I would expect that when i am debugging nuget packages with symbols enabled with idnexed soruce code, it automatically downloads the pdf file and the source code.
Visual Studio Settings for debugger

A:
I see PDB files are donwloaded to the symbols cache folder but
  stepping thru is asking for source file location in visual studio,
  even when i have indexed the source code during publish symbol.

You should let the debugger know where to find your source files. First, please rename your xx.nupkg to xx.zip and check if it contains necessary source files.
After that you can right-click Solution in Solution Explorer=>Properties=>Debug Source Files,click the New Line option to add the path of your nuget source files to the debug source files setting.

I would expect that when i am debugging nuget packages with symbols
  enabled with idnexed soruce code, it automatically downloads the pdf
  file and the source code.

Maybe you can get some help from this issue. You can try setting the build action of the source files as C# compiler when you create the nuget package for .net core.


text:
Q: error: hd0 write error Appears it
BusyBox v1.18.5 (Ubuntu 1:1.18.5-1ubuntu4.1) built-in shell (ash)
Enter 'help' for a list of built-in commands
(initramfs)

Can you help me with it?

A: To check the file system on your Ubuntu partition...

*

*boot to the GRUB menu

*choose Advanced Options

*choose Recovery mode

*choose Root access

*at the # prompt, type sudo fsck -f /

*repeat the fsck command if there were errors

*type reboot
If for some reason you can't do the above...

*

*boot to a Ubuntu Live DVD/USB

*start gparted and determine which /dev/sdaX is your Ubuntu EXT4 partition

*quit gparted

*open a terminal window

*type sudo fsck -f /dev/sdaX # replacing X with the number you found earlier

*repeat the fsck command if there were errors

*type reboot
Update #1:
Now, to check the SMART information in your hard drive...

*

*boot to a Ubuntu Live DVD/USB

*start Disks application

*select the correct disk in the left pane

*go to the "hamburger" icon and select SMART Data & Tests

*review the data, note if it indicates that your drive is good/bad

*run the tests


text:
Q: How to render data into a jquery mobile page dynamically I am really new to jQuery Mobile. I am trying to make a simple app with two pages. Page1 is where user will enter search data and Page2 will be where the results are shown. Any help is greatly appreciated.
<!DOCTYPE HTML>

<title>Example</title>

Example

       <input name="searchfor" type="text" id="searchfor"/>

       <input type="button" id="search" data-theme="b" value="search"/>

Page Footer

Page Three

Your search returned this: {data.value}

Page Footer

A: You might as well make your second page an external page and do the search logic right on it:
$(document).on('click', '#search', function () {
    $.mobile.changePage('/path/to/my-script.php?search=' + encodeURIComponent($('#searchfor').val(), { reloadPage : true });

    //prevent the default behavior of the click event
    return false;
});

Then in your second page you can just receive the $_GET variable, do the search, and output the results.
Otherwise you're looking at using $.ajax() to request a similar response via AJAX:
$(document).on('click', '#search', function () {
    $.ajax({
        url      : '/path/to/my-script.php'
        data     : { search : $('#searchfor').val() },
        dataType : 'json',
        success  : function (data) {

            //assuming that the response in an array of objects (JSON)
            var output = [];
            for (var i = 0, len = data.length; i < len; i++) {
                output.push('

' + data[i].name + '

' + data[i].description + '

');
            }

            var $page =  $('#page2').children('.ui-content').append('
' + output.join('') + '
');

            $.mobile.changePage($page);
        },
        error    : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle errors*/ }
    });

});


text:
Q: Greedy, Non-Greedy, All-Greedy Matching in C# Regex How can I get all the matches in the following example:
// Only "abcd" is matched
MatchCollection greedyMatches = Regex.Matches("abcd", @"ab.*");

// Only "ab" is matched
MatchCollection lazyMatches   = Regex.Matches("abcd", @"ab.*?");

// How can I get all matches: "ab", "abc", "abcd"

P.S.: I want to have the all matches in a generic manner.  The example above is just an example.

A: If a solution exists, it probably involves a capturing group and the RightToLeft option:
string s = @"abcd";
Regex r = new Regex(@"(?<=^(ab.*)).*?", RegexOptions.RightToLeft);
foreach (Match m in r.Matches(s))
{
  Console.WriteLine(m.Groups[1].Value);
}

output:
abcd
abc
ab

I say "if" because, while it works for your simple test case, I can't guarantee this trick will help with your real-world problem.  RightToLeft mode is one of .NET's more innovative features--offhand, I can't think of another flavor that has anything equivalent to it.  The official documentation on it is sparse (to put it mildly), and so far there don't seem to be a lot developers using it and sharing their experiences online.  So try it and see what happens.

A: You could use something like:
MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"(((ab)c)d)");

Then you should have three backreferences with ab, abc and abcd.
But, to be honest, this kind of regex doesn't makes too much sense, especially when it gets bigger it becomes unreadable.
Edit:
MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"ab.?");

And you got an error there btw. This can only match ab and abc (read: ab + any (optional) character
Lazy version of:
MatchCollection greedyMatches    = Regex.Matches("abcd", @"ab.*");

is:
MatchCollection nonGreedyMatches    = Regex.Matches("abcd", @"ab.*?");

A: You can't get three different results from only one match.
If you want to match only "ab" you can use ab.? or a.{1} (or a lot of other options)
If you want to match only "abc" you can use ab. or a.{2} (or a lot of other options)
If you want to match only "abcd" you can use ab.* or a.{3} (or a lot of other options)


text:
Q: Fastest way to read binary into int[] in java? In java, what is the fastest way to read a huge binary file into int[]. I saw this solution
Fastest way to read huge number of int from binary file
But there is two solutions, and I don't know which is better. Also they seem to give a fixed maximum size for the int[], but how can I do it with a variable size? Like how can I set it to fit the amount of data in the binary exactly. Is there a way to know how many ints are there in the file?
Thanks

A: You could have some variables to calculate the time in both solutions, then compare the two.
while (bytesRead != -1) {
  double start = System.currentTimeMillis();
   while(doingstuff){}
  double timeTaken = System.currentTimeMillis() - start;
}

As for the array, you could use a arraylist which is expandable.
ArrayList<int> binary = new ArrayList<int>();
binary.add(stuff);


text:
Q: Change the highlighted color of angular material input text box Hi I am using angular material, I like to change the material input focus color on click
Right now by default it is showing in purple color, I like to change white color

I tried with lot of css. But nothing is working for me
Below is the example of stackblitz URL
https://stackblitz.com/edit/material-input-sample?file=src/app/app.component.ts

A: You can modify the css of the mat-input elements by using ::ng-deep.
::ng-deep {
  .mat-form-field-label {
    color: white !important;
  }

  .mat-form-field.mat-focused .mat-form-field-ripple {
    background-color: white !important;
  }
}

Example in stackblitz


text:
Q: Interpolate text getting NULL in java I've been trying to use the code given in a class, but it didn't seem to work. The idea is that, when I put a name, it goes on when called, but i keep getting "null". Even, I saw the teacher using "%1$s" and ""%1$s" in two different lines to make the work done, but none seems to work in my code.
Here it goes the 2 pages of code and an image of the null
The activity:
private void loadPage(int i) {
        mPaginaActiva = mContenidos.getPage(i);
        Drawable drawable = getResources().getDrawable(mPaginaActiva.getImageId());
        mImageView.setImageDrawable(drawable);

        String pageText=mPaginaActiva.getText();
        //acá interpolamos el nombre
        pageText=String.format(pageText, mNombre);

        mTextView.setText(pageText);

The content:
private Pagina[] mPaginas;

    public Contenidos(){
        mPaginas = new Pagina[8];

        mPaginas[0] = new Pagina(
                R.drawable.img0,
                "Saludos \"%1$s, acá empieza tu viaje.",
                new Opcion("Entrenarme", 1),
                new Opcion("Luchar", 2)
        );
        mPaginas[1] = new Pagina(
                R.drawable.img1,
                "Hazte experto en el manejo de una de estas armas.",
                new Opcion("Elijo el palo", 3),
                new Opcion("Elijo la espada", 4)
        );
        mPaginas[4] = new Pagina(
                R.drawable.img4,
                "Bien %1$s, has elegido aprender a usar la espada. Ahora Suzuki está despistado. ¿Deseas atacar por sorpresa?",
                new Opcion("Quiero luchar con honor", 5),
                new Opcion("Atacar por la espalda", 2)
        );

:
Also, if possible, I would like to know if there is a chance to get GIFs instead of images, since the img0 - img7 are GIFs, but they aint getting the animation done in the app. This part of the code is in the content and I'm using drawable:
mPaginas[4] = new Pagina(
                    R.drawable.img4,


text:
Q: Jquery Mobile multi page Link works on second click only Hi i am newbie in jquery mobile development. I have a index.html page (normal page) which has link to inner page i.e. page2.html (which is multi page template). The problem is links present in this page works on second click only. Can you please help me on this?
rel="external" href="#Ans1" style="text-decoration:none">Link 1

&&
data-ajax="false" href="#Ans1" style="text-decoration:none">Link 2

i tried the above two methods.


text:
Q: Load GUI from separate file I have been making an gui for my work, and everything is working perfect with Windows form.
The problem is now that i want to save all the Design and form region into another file. and just load it. Reason: so we can change the design of the GUI if needed and just edit the GUI.ps1 file.
I had the idea that it is just the Main.ps1 that need to be executed. when we need to use the Program.
Any help would be nice.
Main.ps1
 |_GUI.ps1
 |_Functions-files.ps1

Gui.ps1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$FMmain = New-Object System.Windows.Forms.Form
$TCmain = New-Object System.Windows.Forms.TabControl
.....
$FMmain.showdialog()


text:
Q: Assigning values to arrays I am trying to put values into an array, but when I compile the code, it tells me that both arrays have never been assigned to and have their values set to null. Can somebody take a look at the code and tell me what I did wrong?
class SinusoidalWaveform
{
    double[] angleArray;
    double[] resultArray;

    public SinusoidalWaveform(double minAngle, double maxAngle, int size)
    {
        int c = 0;

        for(double temp = minAngle; temp <= maxAngle; temp+=maxAngle/(size - 1d))
        {
          this.angleArray[c] = temp;
          this.resultArray[c] = Math.Sin(temp);
          c++;
        }
    }
}

The minAngle and maxAngle in radians given by the user, and size is how long we want the array to be, which is also specified by the user.

A: You need to allocate memory to both arrays:
double[] angleArray = new double[5];
double[] resultArray = new double[5];

Do that either in the constructor or on declaration. 5 in this case represents the amount of elements allocated in memory for that array.
for(double temp = minAngle; temp <= maxAngle; temp+=maxAngle/(size - 1d))
{
          this.angleArray[c] = temp;
          this.resultArray[c] = Math.Sin(temp);
          c++;
}

That is bad, you are not checking if c++ is greater than the length of the array.
So you have two options.
Crap option:
for(double temp = minAngle; temp <= maxAngle; temp+=maxAngle/(size - 1d))
{
          this.angleArray[c] = temp;
          this.resultArray[c] = Math.Sin(temp);
          if(c+1 > angleArray.Length) break; //exit or risk out of bound exception
          c++;
}

Better option, use a re-sizable array: List<double>.

A: Looks like you don't know the array size before running the loop, so most simple solution is to use a generic List then assign the arrays after the loop:
List<double> angleList = new List<double>();
List<double> resultList= new List<double>();
for(double temp = minAngle; temp <= maxAngle; temp+=maxAngle/(size - 1d))
{
   angleList.Add(temp);
   resultList.Add(Math.Sin(temp));
}
this.angleArray = angleList.ToArray();
this.resultArray= resultList.ToArray();

A: Both arrays really haven't been assigned.
Try this:
class SinusoidalWaveform
{

    double[] angleArray = new double[MAX_SIZE];
    double[] resultArray  = new double[MAX_SIZE];
    .....

Where MAX_SIZE is the size of the array.
If you're not sure what the max size is going to be, think about using a List<double>, for instance.

A: Before starting the loop, instantiate your array using the size specified by the user as shown below:
angleArray = new double[size];
resultArray = new double[size];

Arrays are objects in C#. They must be instantiated before being used.

A: It actually tells you this because you have left your arrays unassigned
double[] angleArray;
double[] resultArray;

If you would like to assign values to these TWO arrays, then you may try ONE of the following
1|| If you would like to assign the values in ONE step, then you may try this
double[] angleArray = { 1, 2, 3 };
double[] resultArray = { 4, 5, 6 };

Then, you may access its values using the following code for example
int n = 1;
angleArray[n] = 1; //Set (2) to (1)

Where n is the index of the item in the array. Generally, in arrays, the first items takes the index 0 but not 1. So, if you say angleArray[1] it will output 2
2|| If you would like to set the array maximum values to a specific value / assign the values in two step
double[] angleArray = new double[3];
double[] resultArrau = new double[3];

Although this will assign the values, the values will still be unknown because when you say
double[] angleArray = new double[3];

you are telling the program that you'd like to assign 3 values but you won't indicate the values right now.
In this case, you may indicate the values using the following code for example
double[] angleArray = new double[3];
int o = 0;
for (int i = 0; i < angleArray.Length; i++)
{
     angleArray[i] = o;
     o++;
}

This will assign a value of o which will be incremented by 1 each for loop. As you may notice, I did not say i < angleArray.Length + 1 because the index in arrays starts with 0 but not 1
Important Notice: If you have an array set of maximum 6 values double[] _Array = new double[6];, you may NOT set a value of index 7 (_Array[7] = 1;) because you only have 6 indices. Otherwise, you'll get IndexOutOfRangeException was unhandled
Thanks,
I hope you find this helpful :)


text:
Q: Migrating Apollo Server from v3 to v4 in next.js In v3 you could write "createHandler" like that:
export default async (req, res) => {
  await startServer;

  await apolloServer.createHandler({
    path: "/api/graphql",
  })(req, res);
};

This is not possible in v4. The error is:

Property 'createHandler' does not exist on type 'ApolloServer<BaseContext>'.

I read the documentation but can't grasp how I could do the equivalent
I tried using this https://github.com/apollo-server-integrations/apollo-server-integration-next but I don't understand how I would import something when I can't install it through npm. I don't even know if this is the equivalent but it seems like that.
import { startServerAndCreateNextHandler } from '@as-integrations/next';'

A: Nevermind me. When I tried to install "@as-integrations/next", I somehow typed "apollo-server-integration-next"


text:
Q: Boost::asio: data get received only after other connection appeared I'm trying to use code examples in my application. At a connection client sends "hello!" to the server. Server receives it and answers on it somehow (and ends message with "Hi, client! I'm server!") - but that's what i have: server doesn't receive anything until I connect to it by telnet and send something. After that it receives (prints) both clients and telnet messages.
Client:
socket.connect(tcp::endpoint(tcp::v4(), 21), error);
if (error)
  throw boost::system::system_error(error);
boost::asio::write(socket, boost::asio::buffer("Hello!\n"), boost::asio::transfer_all(), ignored_error);
for (;;)
{
  boost::array<char, 128> buf;
  boost::system::error_code error;

  size_t len = socket.read_some(boost::asio::buffer(buf), error);

  if (error == boost::asio::error::eof)
    break; // Connection closed cleanly by peer.
  else if (error)
    throw boost::system::system_error(error); // Some other error.

  std::cout.write(buf.data(), len);
}

server:
for (;;)
{
    tcp::socket socket(io_service);
    acceptor.accept(socket);
    for (;;)
    {
        boost::array<char, 128> buf;
        boost::system::error_code error;
        size_t len = socket.read_some(boost::asio::buffer(buf), error);

        if (buf[len-1] == '/n')
            break; // Connection closed cleanly by peer.
        else if (error)
            throw boost::system::system_error(error); // Some other error.
        std::string a(buf.data());
    }

    std::string message = make_daytime_string();
    boost::system::error_code ignored_error;
    boost::asio::write(socket, boost::asio::buffer("Hi, client! I'm server!"),
    boost::asio::transfer_all(), ignored_error);
}

I'm afraid I forgot something to close (like socket). But anyway - and ideas?

A: size_t len = socket.read_some(boost::asio::buffer(buf), error);

if (buf[len-1] == '/n')

you've made some assumptions about tcp::ip::socket::read_some() that are not true.

Remarks
The read_some operation may not read all of the requested number of
  bytes. Consider using the read function if you need to ensure that the
  requested amount of data is read before the blocking operation
  completes.

I suggest you use the read() free function as the documentation suggests.


text:
Q: What is the use of the #error directive in C? What is the #error directive in C? What is the use of it?

A: It's a preprocessor directive that is used (for example) when you expect one of several possible -D symbols to be defined, but none is.
#if defined(BUILD_TYPE_NORMAL)
# define DEBUG(x) do {;} while (0) /* paranoid-style null code */
#elif defined(BUILD_TYPE_DEBUG)
# define DEBUG(x) _debug_trace x /* e.g. DEBUG((_debug_trace args)) */
#else
# error "Please specify build type in the Makefile"
#endif

When the preprocessor hits the #error directive, it will report the string as an error message and halt compilation; what exactly the error message looks like depends on the compiler.

A: If compiler compiles this line then it shows a compiler fatal error: and stop further compilation of program:
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
int main(){
    float a,b=25;
    a=sqrt(b);
    printf("%f",a);
    return 0;
}
#endif

Output:compiler error --> Error directive :First include then compile

A: I may have invalid code but its something like...
#if defined USING_SQLITE && defined USING_MYSQL
#error You cannot use both sqlite and mysql at the same time
#endif

#if !(defined USING_SQLITE && defined USING_MYSQL)
#error You must use either sqlite or mysql
#endif

#ifdef USING_SQLITE
//...
#endif

#ifdef USING_MYSQL
//...
#endif


text:
Q: Making one of the column dividers thicker than the others in a browse I have a browse with 5 columns. I want the dividing line between columns 3 and 4 to be a little thicker.
Is there a way to do this?

A: Short answer is no, you can't change the line between columns.
But you could add an empty dummy column with blank values between column 3 and 4, that you could get to look it like a thicker separator.
Regards,


text:
Q: Помогите решить задачу по js, нужно найти поврежденные файлы и сложить их в массив для дальнейшего анализа Поврежденные файлы. Раньше в папке хранились разные файлы и поддиректории. Файлы назывались file и использовалась собственная асинхронная файловая система, которая базировалась на объекте Folder c двумя методами:
type File = string | Folder | {} | null | undefined;

type Folder = {
  // Получить по индексу файл или папку
  read(index: number, callback: (file: File) => void): void;

  // Получить количество элементов в директории
  size(callback: (size: number) => void): void;
}

Часть файлов осталась без повреждений, часть — потеряна навсегда, потому что превратилась в null или {}, а еще часть повреждена и, кажется, может быть восстановлена. Понять, что файл поврежден очень просто — часть букв в названии продублировались. Помогите найти все такие файлы и сложить их в массив для дальнейшего анализа. Массив надо отсортировать лексиграфически.
Формат ввода
Объект с определенной структурой:
Folder([
    'file',
    'ffffile',
    Folder([
        'file',
    ]),
    Folder([
        'fiiile',
    ]),
    Folder([
        {},
        null,
        'file',
        'ffiillee',
        'ffiillee',
    ]),
    Folder([
        Folder([
            'filllle',
            'file',
            null,
        ]),
        {},
        Folder([]),
    ]),
]);

Формат вывода
Массив строк, отсортированный в лексикографическом порядке:
[
    'ffffile',
    'ffiillee',
    'ffiillee',
    'fiiile',
    'filllle',
]

Примечания
Задачу требуется решить на JavaScript (ES2017) и оформить решение по шаблону:
module.exports = async function(input) {

    return result;
}

условия задачи:
((global) => {
    const timeout = 20;

    const _async = (fn, cb) => {
        setTimeout(() => {
            cb(fn());
        }, Math.random() * timeout);
    };

    const Folder = function (a = []) {
        if (!new.target) {
            return new Folder(a);
        }

        this.read = (index, cb) => _async(() => a[index], cb);
        this.size = (cb) => _async(() => a.length, cb);
    };

    Object.freeze(Folder);
    global.Folder = Folder;
})(typeof window === 'undefined' ? global : window);

const input = Folder([
    'file',
    'ffffile',
    Folder([
        'file',
    ]),
    Folder([
        'fiiile',
    ]),
    Folder([
        {},
        null,
        'file',
        'ffiillee',
        'ffiillee',
    ]),
    Folder([
        Folder([
            'filllle',
            'file',
            null,
        ]),
        {},
        Folder([])
    ]),
]);

console.log(input)

// проверка решения
solution(input).then(result => {
    const answer = ['ffffile', 'ffiillee', 'ffiillee', 'fiiile', 'filllle'];
    const isEqual = String(answer) === String(result);

    if (isEqual) {
        console.log('OK');
    } else {
        console.log('WRONG');
    }
});

async function solution(input) {
    // ... решение задачи

    // пример вызова read
    input.read(1, (file) => console.log(file));

    // пример вызова size
    input.size((size) => console.log(size));
}

A: Оформлением займетесь сами. Я помогу решить простую задачу.

//тупо мок объект для проверки
let Folder = function(optionsArray) {
   return optionsArray;
}

const input = Folder([
    'file',
    'ffffile',
    Folder([
        'file',
    ]),
    Folder([
        'fiiile',
    ]),
    Folder([
        {},
        null,
        'file',
        'ffiillee',
        'ffiillee',
    ]),
    Folder([
        Folder([
            'filllle',
            'file',
            null,
        ]),
        {},
        Folder([])
    ]),
]);

//воспользуемся примером https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
function flatten(array) {
  var flattend = [];
  (function flat(array) {
    array.forEach(function(el) {
      if (Array.isArray(el)) flat(el);
      else flattend.push(el);
    });
  })(array);
  return flattend;
}

// проверка удовлетворяет ли имя файла нашим условиям
function isRecoverable(fileName) {
    for(var key in fileName) {
        // проверка существует ли собственное свойство key у объекта
        // по существу просто проверка не пустой ли объект {}
        if(fileName.hasOwnProperty(key))
        {
          // объект не пустой нужно проверить на дубликаты букв
          // тут возможно и другое решение, но я выбрал это
          return fileName.length != [...new Set(...fileName.split())].length;
        }
    }
    return false;
}

// также отсортировать
let result = flatten(input).filter(file => isRecoverable(file)).sort();

console.log(result);


text:
Q: Palette Library not picking color on linear layout I am using Palette Library for picking dominant color. My swatch is giving right TitleTextColor but not giving RGB color. I am using rgb color to apply background of linear layout
Bitmap bitmap = BitmapCompress.decodeBitmapFromResource(getResources(), R.drawable.mihawk, 360, 360);
Palette p = Palette.from(bitmap).generate();
Palette.Swatch vibrantSwatch = p.getDominantSwatch();
LinearLayout top;
top = findViewById(R.id.wallpaperLinearLayoutTop);
top.setBackgroundColor(vibrantSwatch.getRgb());

Here is Xml
    <LinearLayout
        android:id="@+id/wallpaperLinearLayoutTop"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:alpha="0.85"
        android:orientation="horizontal">


text:
Q: WPF Combo Box Visible Items Not Updating I have a combo box defined in WPF that is bound to an observable collection of options as shown below.
private ObservableCollection<SeriesOption> _SeriesOptions;
        public ObservableCollection<SeriesOption> SeriesOptions
        {
            get { return _SeriesOptions; }
            set { Set<ObservableCollection<SeriesOption>>(() => SeriesOptions, ref _SeriesOptions, value); }
        }

This is defined in a custom object of which I have a list of (called ModulePlots), and a "selected" item (called SelectedModulePlot) in my view model. So the items in my combo box should be updated based on which ModulePlot is selected on the UI.
It works as expected when nothing is selected in the combo box. Once I select an option in the combo box for one of the ModulePlots, the number of items in the combo box sticks to the number that was in the combo box when I selected one.
So if I select something when the combo box had 8 items, then select a different ModulePlot that only has 1 item, it has 7 blank items in the combo box.
I have already checked that the number of options is correct when the second ModulePlot is selected, and the items in the combo box do change. It just seems that the number of visible items is not being updated.
Has anyone else seen this issue or something similar? What can I do to fix this?


text:
Q: Python / web scrape / aspx -- is it humanly possible when there are no forms? Total noob, obviously.  Teaching self Python for web scraping in the interest of open records/government transparency/reporting/etc.
There's an .aspx page I want to scrape, a week-by-week calendar for January - March 2012
But it has no forms ...
Perhaps you fine people can tell me if a solution is even possible before I spend days fighting with it.
http://webmail.legis.ga.gov/Calendar/default.aspx?chamber=house
The only way to see the appointments on the calendar is by choosing a day on a picture of a calendar.  But, at least, if you click on Monday, it shows all the week's appointments.  (I would like to gather all those appointments in order to count how often each committee meets, a bit of a proxy for counting what kind of legislation gets attention and what kind is ignored.)
But so, what strategy to use? It appears that each month at least down in its bowels is assigned to a sequential four-digit number prepended with a "V", like V4414, and days with a non-prepended number.
I'm only hunting Jan - Mar 2012; other months are non-germane and mostly empty.
a clue?
    ...February	March 2012	April

a pattern?
    ...26	27	28	...

Cheers and thanks!!

A: The form contains four inputs with names of:

*

*__EVENTTARGET

*__EVENTARGUMENT

*__VIEWSTATE

*__EVENTVALIDATION
The latter two have initial values. You need to scrape those. The former two are set by those links. For example, you have a link:
1

Look at the href:
javascript:__doPostBack('calMain','4504')

Somehow, parse those two strings out of it. The former is __EVENTTARGET. The latter is __EVENTARGUMENT.
Once you have all four pieces of data, you can issue a POST request to get the next page.

A: You could replicate the POST request in Python using something like urllib.parse.urlencode to build the query strings.
For this you will have to find out what the query string looks like, obviously. Or, you could use another tool like Selenium RC.


text:
Q: How to insert data in database using checkboxes? I'm trying to insert data into the database using check boxes, but I'm not sure how to go about doing it.If the User selects a check box and click the update button, it will be inserted into the database.
Here's my code.
CXATest1Activity
public class CXATest1Activity extends Activity {
/** Called when the activity is first created. */
DBCXAAdapter db = new DBCXAAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //set up main content view
    setContentView(R.layout.main);

    Button button1main = (Button) findViewById(R.id.Button01main);

    button1main.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

         db.open();

            EditText editTextName = (EditText)findViewById(R.id.EditTextName);
            String NameValue = editTextName.getText().toString();

            EditText editTextAge = (EditText)findViewById(R.id.EditTextAge);
            String AgeValue = editTextAge.getText().toString();

            EditText editTextMedicalBackgroundBody = (EditText)findViewById(R.id.EditTextMedicalBackgroundBody);
            String MedicalBackgroundBodyValue = editTextMedicalBackgroundBody.getText().toString();

            Spinner editTextSpinnerGenderType = (Spinner)findViewById(R.id.SpinnerGenderType);
            String GenderTypeValue = editTextSpinnerGenderType.getSelectedItem().toString();

            Spinner editTextSpinnerMedicalBackgroundSelectType = (Spinner)findViewById(R.id.SpinnerMedicalBackgroundSelectType);
            String MedicalBackgroundSelectTypeValue = editTextSpinnerMedicalBackgroundSelectType.getSelectedItem().toString();

            CheckBox editTextCheckboxMedicalBackgroundCancer = (CheckBox)findViewById(R.id.checkBoxCancer);
            String MedicalBackgroundCancerValue = editTextCheckboxMedicalBackgroundCancer.getText().toString();

            editTextCheckboxMedicalBackgroundCancer.setOnCheckedChangeListener(new OnCheckedChangeListener(){
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            long id;
            id = db.insertUserprofile(NameValue, AgeValue, MedicalBackgroundBodyValue, GenderTypeValue, MedicalBackgroundSelectTypeValue, MedicalBackgroundCancerValue);

            db.close();

                //set up dialog
                final Dialog dialog = new Dialog(CXATest1Activity.this);
                dialog.setContentView(R.layout.maindialog);
                dialog.setTitle("Congrats");
                dialog.setCancelable(true);
                //there are a lot of settings, for dialog, check them all out!

                //set up text
                TextView text = (TextView) dialog.findViewById(R.id.TextView01);
                text.setText(R.string.lots_of_text);

                //set up image view
                ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01);
                img.setImageResource(R.drawable.updated_icon_new1);

                //set up button
                Button button = (Button) dialog.findViewById(R.id.Button01);
                button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                        dialog.dismiss();
                    }
                });
                //now that the dialog is set up, it's time to show it
                dialog.show();
            }

DBCXAAdapter
//---insert a userprofile into the database---
public long insertUserprofile(String name, String age, String medicalbackground, String spinnergender, String spinnermedicalbackground, String checkboxmedicalbackgroundcancer)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_AGE, age);
    initialValues.put(KEY_MEDICALBACKGROUND, medicalbackground);
    initialValues.put(KEY_SPINNERGENDER, spinnergender);
    initialValues.put(KEY_SPINNERMEDICALBACKGROUND, spinnermedicalbackground);
    initialValues.put(KEY_CHECKBOXMEDICALBACKGROUNDCANCER, checkboxmedicalbackgroundcancer);
  return db.insert(DATABASE_TABLE, null, initialValues);
}

Thank in advance.

A:         id = db.insertUserprofile(NameValue, AgeValue, MedicalBackgroundBodyValue, GenderTypeValue, MedicalBackgroundSelectTypeValue, MedicalBackgroundCancerValue); all you have to do is add listener to your checkbox which listens of checkbox activity

editTextCheckboxMedicalBackgroundCancer.setOnCheckedChangeListener(new OnCheckedChangeListener(){
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
         }
    });

UPDATE
Well you are not doing inside checkbox listener, you are calling insertUserprofile function outside the listener which will always execute.
editTextCheckboxMedicalBackgroundCancer.setOnCheckedChangeListener(new OnCheckedChangeListener(){
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
long id;
id = db.insertUserprofile(NameValue, AgeValue, MedicalBackgroundBodyValue, GenderTypeValue, MedicalBackgroundSelectTypeValue, MedicalBackgroundCancerValue);

         }
    });


text:
Q: Windows Security Center Service can't be started Win 7 Home Prem 32-bit
I recently had a trojan detection by MS Security Essentials which it caught and quarantined.
I now get the following in the action center - The Windows Security Center Service can't be started.
MS Security Essentials doesn't seem to be present either despite me uninstalling and reinstalling.
I can set the security center service to start automatically but upon reboot it says the same thing? i.e. disabled   i can't get it to start and i can't seem to run MSSE - it just seems to open and close immediately?
Nothing obvious appears in the event viewer.
Any ideas?

A: It seems like your system is still infected and Security Essentials wasn't able to stop all of the trojan's elements.
You might want to try and run an online virus scanner or attempt to install AVG Antivirus to see if the initial scan before install is able to catch the trojan.
Also, if you still remember the trojans name, try and find a clean-up tool from one of the various antivirus providers online.

A: Make a boot AV disc then boot from the disc and scan the hard drive, remove any infections it finds, I prefer the Kaspersky disc myself.
http://www.techmixer.com/free-bootable-antivirus-rescue-cds-download-list/
Then:
Install free MBAM, run the program and go to the Update tab and update it, then go to the Scanner Tab and do a quick scan, select and remove anything it finds.
http://download.cnet.com/Malwarebytes-Anti-Malware/3000-8022_4-10804572.html
When MBAM is done install SAS free version, run a quick scan, remove what it automatically selects.
http://www.superantispyware.com/download.html
These last 2 are not AV softwares like Norton, they are on demand scanners that only scan for nasties when you run the program and will not interfere with your installed AV software, these can be run once a week to ensure you are not infected. Be sure you update them before each weekly scan.
.
after you are sure the system is clean and MSE is still broken, try this MSE repair tool
http://www.itknowledge24.com/MSERT.zip
PDF on what the tool does
http://www.itknowledge24.com/MSE_Restore_Tool.pdf
.

A: Your system is either still infected, or it has suffered serious damage because of the virus.
You might try to repair the Windows system files. See this article:
How to Repair Windows 7 System Files with System File Checker.
If this doesn't help, you might consider reformatting the hard disk and reinstalling Windows.
It is dangerous to use a computer that might still be infected.


text:
Q: Problem with float and IE6 I have problem with floating in IE6. The HTML code:

        STRAN <?php dobiStran(); ?>

CSS:
#prejsnja {
float: left;
}

#naslednja {
float: right;
}

#stran {
position: relative;
width: 400px;
border: 2px black solid;
margin: 0 auto;
font-family: "Comic Sans MS";   /*Izberemo drugo pisavo, kot pa tista ki je definirana v body.*/
color: #599cd4;
text-align: center; /*Postavimo na center.*/
font-size: 30px;    /*Vecja pisava, ker gre za naslov.*/
}

The left image floats to the left, as it should, the text is centered, the right image also floats to the right as it should, but has for some reason some kind of margin-top, that only appears in IE6. Here is example in other browsers:

And in IE6:

A: Try moving your HTML elements around a bit, like this:

        STRAN <?php dobiStran(); ?>

And then your styles become:
#prejsnja {
  float: left;
  width: 100px;
}

#naslednja {
  float: right;
  width: 100px;
}

#stran {
position: relative;
width: auto;
border: 2px black solid;
margin: 0 auto;
font-family: "Comic Sans MS";   /*Izberemo drugo pisavo, kot pa tista ki je definirana v body.*/
color: #599cd4;
text-align: center; /*Postavimo na center.*/
font-size: 30px;    /*Vecja pisava, ker gre za naslov.*/
}

I've assumed your arrow images are 100px, but just change these to whatever it is they actually are.


text:
Q: /index.php persists in 2 Laravel application despite .htaccess Apache Virtual Host and Subdomain Hosting VPS   Please, I have been having issues with eliminating index.php file in the
routes for my Laravel applications.
   I have not had success rectifying it. When I use the server's IP address everything works fine but when I     use the sub-domain names it works for / but for other routes or URL like /login, I must add /index.php/login before it works otherwise it doesn't.
  Below is a sample of my server current settings or configurations.

Site Works when index.php is used in the URL

 Site doesn't work when index.php is removed from the Url

 But it works well when i use the IP address directly.
 but in this case it serves the laravel application hosted in the second subdomain. I just don't know why

MAJOR SITE
domain.com
  Apache CONF FILE (This Works Great Already)
   <VirtualHost *:80>
    ServerAdmin admin@domain.com
    ServerName domain.com
    ServerAlias www.domain.com
    DocumentRoot /var/www/domain.com/public_html

    <Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>

     RewriteEngine on
     RewriteCond %{SERVER_NAME} =www.domain.com [OR]
     RewriteCond %{SERVER_NAME} =domain.com
     RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
  </VirtualHost>

FIRST SUBDOMAIN SITE APACHE CONF:
test1.domain.com
/var/www/test1.domain.com/public_html
// APACHE CONF FILE

/etc/apache2/sites-available/test1.domain.com.conf

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName test1.domain.com
    ServerAlias www.test1.domain.com
    DocumentRoot /var/www/test1.domain.com/public_html

    <Directory /var/www/test1.domain.com/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>

   RewriteEngine on
   RewriteCond %{SERVER_NAME} =test1.domain.com
   RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
  </VirtualHost>

//.htaccess for test1.domain.com

IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
    Options -MultiViews
 </IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

SECOND SUB-DOMAIN SITE APACHE CONF:

test2.domain.com
    /var/www/test2.domain.com/public_html
/APACHE CONF FILE
    /etc/apache2/sites-available/test2.domain.com.conf

  <VirtualHost *:80>
    ServerAdmin admin@test2.domain.com
    ServerName test2.domain.com
    ServerAlias test2.domain.com
    DocumentRoot /var/www/test2.domain.com/public_html

    <Directory /var/www/test2.domain.com/public_html/>
       Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =test2.domain.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
   </VirtualHost>

.htaccess
test2.domain.com htacess file config

          Options -MultiViews -Indexes

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Environment
Ubuntu 16.04
Server PHP 7.2
Laravel Version 5.4.30

OUTCOME OF ALL THESE
 domain.com //WORKS

 test1.domain.com // WORKS
but test1.domain.com/login  // Does'nt work
instead test1.domain.com/index.php/login // works

test2.domain.com // WORKS
but test2.domain.com/login  // Does'nt work
instead test2.domain.com/index.php/login // works

but I realized that
the Ip address works well without the need for index.php
http://server-ip-address // works but serves the app in test2.domain.com
http://server-ip-address/login  // also Works well which is what I expect in the two subdomain test1.domain.com and test2.com

REQUEST PLEASE

I need TO GET RID OF THE NEED TO USE index.php in the route.
       Please, Any Idea is welcome.
      Perhaps fresh Eyes would help me identify ways to fix this out.

RESEARCH I HAVE made
    I Have tried the following links already. still having a hard time finding out what is wrong so that it is rectified.
htaccess for domain and subdomain with laravel
htaccess for domain and subdomain with laravel
apache virtual host and "Dynamic" Domains
Setting document root for Laravel project on Apache virtual host
apache virtual host and "Dynamic" Domains
ONCE AGAIN. FIX To Eliminate the need to include index.php in the Web APPLICATION ROUTE. THANKS IN ADVANCE

A: I was able to fix the issue.
First: The .htaccess files were not being read.
 despite all that I did above, this was confirmed after I followed the
 instructions in the link below by placing gibberish in the .htaccess files and there
 was no 500 status error display
.htaccess file not being read ("Options -Indexes" in .htaccess file not working)
But still it wasn't working.
I began to check all the files in the /etc/apache2/site-enabled directory
and discovered that because I installed SSL Encrypt On My Server Prior To Setting up the Laravel apps, the config files being used are the ones generated by  Encrypt for the domains found at

/etc/apache2/sites-enabled/test1.domain.com-le-ssl.conf (ssl - generated config)
/etc/apache2/sites-enabled/test1.domain.com.conf  (normal config)

and

/etc/apache2/sites-enabled/test2.domain.com-le-ssl.conf ( ssl -generated config)
/etc/apache2/sites-enabled/test1.domain.com.conf (normal config)

and also

/etc/apache2/sites-enabled/domain.com-le-ssl.conf
/etc/apache2/sites-enabled/domain.com.conf

So I viewed the files and discovered that Document Root pointed to a different
  path from the Directory that was why the htaccess files were not being read but
  were being read when I used the IP address that pointed to the second subdomain
NOTE THIS IS IN THE SSL APACHE CONFIG FILES NOT THE NORMAL APACHE CONFIG FILES
    DocumentRoot /var/www/test1.domain.com/public_html
<Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

In Summary this is the final update sample that fixed it
<IfModule mod_ssl.c>
   <VirtualHost *:443>
     ServerAdmin admin@test1.domain.com
     ServerName test1.domain.com
     ServerAlias www.test1.domain.com
     DocumentRoot /var/www/test1.domain.com/public_html

    <Directory /var/www/test1.domain.com/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>

  Include /etc/letsencrypt/options-ssl-apache.conf
  SSLCertificateFile /etc/letsencrypt/live/test1.domain.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/test1.domain.com/privkey.pem
  </VirtualHost>
 </IfModule>

OUTCOME
My Routes and URL Worked As I Expected. as the .htaccess files were now properly being read by apache within appropriate directories
LESSONS LEARNT

*

*Get Your Apache Files Configured Before installing Encrypt as it would duplicate the files and add the necessary configurations to make it secured.

*Or Cross Check/Double check the normal and the SSL Configuration files as well because you definitely want your site to be secured and working as expected.

*Double check the DocumentRoot and the Directory and ensure that they point to the same destination or as expected.

Those are my lessons from all These. Hope Someone else benefits from this. Thanks.


text:
Q: J2EE app needs .java to run, .class not enough? I'm trying to run a j2ee application and eclipse gives me an error saying "the jar file  has no source attachments". This is a jar this application depends on. I extracted the jar and see only class files, but that should be enough to run this application, no?

A: Most likely you are using a JRE and not a JDK to run Eclipse. One way to fix this is to add a JDK to the list of JREs (Window / Preferences / Java / Installed JREs).


text:
Q: Cannot refer to in class function from facebook sdk api function I am having a problem in calling/accessing a in-class function AND a service function from a function which calls a external js lib/code... But I am able to access class variable using the 'this' keyword in angular 2 component
FB <- is the facebook sdk function to get the facebook communicated values of the logged user
Here's the code
statusChangeCallback(resp: any) {
        if (resp.status === 'connected') {
            this.access_token = resp.authResponse.accessToken; // this variable gets the correct value in it

            FB.api('/me?fields=name,email', function (resp: any) {
                this.email = resp.email; // this variable gets the correct value in it

                if (this.email !== '' && this.access_token !== '') {
                    console.log('under if statement');
                    var auth = {};
                    auth['accesstoken'] = this.access_token;
                    auth['emailid'] = this.email;

                    console.log(auth);

                    this.send_registeration(auth); // this function throws ERROR
                    // this.http.fb_register(this.email, this.access_token);
                }
            }, { scope: 'email,public_profile' });
        } else if (resp.status === 'not_authorized') {

        } else {

        }
    }

Here's Error Description shown in chrome
zone.js:260 Uncaught TypeError: this.send_registeration is not a function

here's the full component code to checkout
import {Component, OnInit, Output} from '@angular/core';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import { HttpService } from '../../Service/http.service';

declare const FB: any;

@Component({
    selector: 'facebook-login',
    template: `

        <button class="btn btn-facebook" (click)="onFacebookLoginClick()">
            Sign in with Facebook
        </button>

    `,
    providers: [HttpService],
    directives: [ROUTER_DIRECTIVES]
})

export class FacebookLoginComponent implements OnInit {

    access_token: string = '';
    email: string = '';

    constructor(private http: HttpService) {
        FB.init({
            appId: '****APP ID **********',
            cookie: false,  // enable cookies to allow the server to access
            // the session
            xfbml: true,  // parse social plugins on this page
            version: 'v2.5' // use graph api version 2.5
        });
    }

    onFacebookLoginClick() {
        FB.login(this.statusChangeCallback);
    }

    statusChangeCallback(resp: any) {
        if (resp.status === 'connected') {
            this.access_token = resp.authResponse.accessToken;
            // var self = this;
            FB.api('/me?fields=name,email', (resp: any) => {
                this.email = resp.email;

                if (this.email !== '' && this.access_token !== '') {

                    var auth = {};
                    auth['accesstoken'] = this.access_token;
                    auth['emailid'] = this.email;

                    console.log(auth);

                    this.send_registeration(auth); //throws Error
                    // this.http.fb_register(this.email, this.access_token); // this Service function also throws Error just the same way
                }
            }, { scope: 'email,public_profile' });

        } else if (resp.status === 'not_authorized') {

        } else {

        }
    }

    send_registeration(auth: any) {
        this.http.postRequest(auth, 'fbinvestors')
            .subscribe(
            data => {
                console.log('Server respond is ');
                console.log(data);
            }
            );
    }
}

Here's the updated function ... Facebook sdk callback doesnt seems to be earlier as stated earlier ... but the problem still exits
statusChangeCallback(resp: any) {

        if (resp.status === 'connected') {
            this.access_token = resp.authResponse.accessToken;

        FB.api('/me?fields=name,email,first_name,last_name,age_range,gender,picture', (resp: any) => {
                this.email = resp.email;
        }, { scope: 'email,public_profile' });

        }

        var self = this;
        setTimeout(function () {
            if (this.email !== '' && this.access_token !== '') {
                console.log('under if statement');
                var auth = {};
                auth['accesstoken'] = this.access_token;
                auth['emailid'] = this.email;

                console.log(auth); // show variable output as required
// no problem till here

            }
            self.http.postRequest(auth, 'fbinvestors') // this line throws error as shown below
                .subscribe(
                data => {
                    console.log('Server respond is ');
                    console.log(data);
                }
                );

        }, 7000);
    }

the new Error is similiar to the old one ... but now its not calling the service method - Error shown is
TypeError: Cannot read property 'postRequest' of undefined

UPDATE: on line self.http.postRequest(auth, 'fbinvestors') ... self is undefined basically ... so now I solve this problem if
1. I can pass class scope ('this') as a parameter to this callback function
2. If I can provide a array of callback functions instead of just one callback function
Please help - I am trying this to get solved from 2 days now....

A:  function (resp: any) {

should be
(resp: any) =>

otherwise this. won't point to your current component instance.
See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

A: Take a look at this excellent Stackoverflow thread. It explains the issue you're having and the solution to it.
The this in your callback function is referring to the wrong context, because it is eventually being called from somewhere inside the facebook API code, not your class. Thus, you cannot access your other class functions with this this.
Thankfully, the solution to this is pretty simple:
...
var self = this;
FB.api('/me?fields=name,email', function (resp: any) {
    ...
    self.send_registeration(auth);

By putting this in a temorary variable, and using that inside of the callback, you will be referring to the right context.

A: I changed the original function
onFacebookLoginClick() {
        FB.login(this.statusChangeCallback);
    }

statusChangeCallback(resp: any) {

        if (resp.status === 'connected') {
            this.access_token = resp.authResponse.accessToken;

        FB.api('/me?fields=name,email,first_name,last_name,age_range,gender,picture', (resp: any) => {
                this.email = resp.email;
        }, { scope: 'email,public_profile' });

        }

        var self = this;
        setTimeout(function () {
            if (this.email !== '' && this.access_token !== '') {
                console.log('under if statement');
                var auth = {};
                auth['accesstoken'] = this.access_token;
                auth['emailid'] = this.email;

                console.log(auth); // show variable output as required
// no problem till here

            }
            self.http.postRequest(auth, 'fbinvestors') // this line throws error as shown below
                .subscribe(
                data => {
                    console.log('Server respond is ');
                    console.log(data);
                }
                );

        }, 7000);
    }

to this
    onFacebookLoginClick() {
            var self = this;
            FB.login(this.statusChangeCallback);
            var callback = setTimeout(function () {
                if (this.email !== '' && this.access_token) {
                    console.log('send the http request from here');
                    var auth = {};
                    auth['emailid'] = this.email;
                    auth['accesstoken'] = this.access_token;
                    self.httpTest.postRequest(auth, 'fbinvestors')
                        .subscribe(
                        data => {
                            console.log('Server respond is ');
                            console.log(data);
                        }
                        );
                } else {
                    this.callback(); // gave a recursion untill post is not done.
                }

            }, 2000);
        }
statusChangeCallback(resp: any) {

        if (resp.status === 'connected') {
            this.access_token = resp.authResponse.accessToken;

            // var self = this; // as shown on online to solve the 'this' keyword problem
            console.log(this.httpTest + ' is the service I want to access');
            FB.api('/me?fields=name,email,first_name,last_name,age_range,gender,picture',
                (resp: any, httpService: any = this.httpTest) => {
                    this.email = resp.email;
                });
        } else if (resp.status === 'not_authorized') {

        } else {

        }
    }

Waiting for the response from fb via recursion callback is obviously not a good idea ... but for now it has solved by problem until I do not find the right solution


text:
Q: Flex 4 fails to parse XML with quoted text <?xml version="1.0" encoding="utf-8"?>
<WorkItems>
  <WorkItem Duration="1" ID="1" Title="this breaks: ""></WorkItem>
</WorkItems>

I embed this XML into my Flex 4 app:
<fx:XML source="data.xml" id="Data">
</fx:XML>

And I get an error: TypeError: Error #1090: XML parser failure: element is malformed.
If I remove the quot part of the title it works fine. How come? Isn't this the proper way to escape "?

Edit: Opened a bug with Adobe.

A: That's valid XML, possibly a bug in Flex...? Try parsing it in ActionScript instead and see what happens.

A: You could look into using <![CDATA[ ]]> , maybe that will help your efforts.

http://www.actionscript.org/forums/showthread.php3?t=224590"Naam"]]>BlockquoteBlockquote

A: I've had a similar issue - though I was working with free standing "&" characters and had to do preprocess the XML with:
        $xml = str_replace("&", "&", $response->getBody());

Can you pre-process the XML to change the escape string into character literals?


text:
Q: Парсинг JavaScript-кода ECMA 6 на Python Нужно распарсить (а желательно, выполнить) JavaScript-код на Python.
В нём есть стрелочные функции, поэтому Js2Py абсолютно не подходит.
Пробовал регулярными выражениями, одна из попыток: https://regexr.com/6djpm
Корректно ими менять a => a*2 на function(a){return a*2} не получается.
В общем, нужна либо другая библиотека, либо нормальный regexp.

A: Накидал решение для выполнения javascript и получения результат, используя QWebEnginePage.runJavaScript
Установка PyQt5:
pip install PyQt5
pip install PyQtWebEngine

Код:
from typing import Any

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEnginePage

app = QApplication([])

def run_js(code: str) -> Any:
    result: Any = None
    callback_finished = False

    def _callback(v):
        nonlocal result, callback_finished
        result = v
        callback_finished = True

    page = QWebEnginePage()
    page.runJavaScript(code, _callback)

    while not callback_finished:
        QApplication.processEvents()

    return result

Тест:
print(run_js("2+2"))
print(run_js("let f = a => a*2; f(10)"))
print(run_js("""
    let f = a => a*2;
    f(10);
"""))
print(run_js("""
    function f(a) {
        return a * 2;
    }
    f(10);
"""))

Результат:
4
20
20
20

A: Можно, конечно, и регуляркой попробовать. Но тут нужно как можно больше примеров и то результат не гарантирован :)
Например:
text = 'a => a*2'
m = re.search('(.+?)=>(.+)', text)
if m:
    text = 'function(%s){return %s}' % (m.group(1), m.group(2))

print(text)
# function(a ){return  a*2}


text:
Q: Access on prem DB2 from DSX I am trying to access on prem DB2 data from DSX using a Python notebook in Jupyter.  I have uploaded db2jcc.jar & license jar files to my home directory but how do I add the directory to the classpath ? Is there another to

A: You can alternatively use connector available on DSX to connect to DB2 on prem.
from ingest import Connectors
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
DB2loadOptions = {
                 Connectors.DB2.HOST              : '***********',
                 Connectors.DB2.PORT              : '***********',
                 Connectors.DB2.DATABASE          : '*********',
                 Connectors.DB2.USERNAME          : '***********',
                 Connectors.DB2.PASSWORD          : '***********',
                  Connectors.DB2.SOURCE_TABLE_NAME         : '***********'}
DB2DF.printSchema()
DB2DF.show()

Ref:-
https://datascience.ibm.com/docs/content/analyze-data/python_load.html#ibm-db2
I believe you must be using gateway or some way to connect to your on-prem db2.
https://datascience.ibm.com/blog/working-with-on-premises-databases-step-by-step/
Thanks,
Charles.


text:
Q: Не могу зарегистрироваться в Azue Всем привет, может кто сталкивался и уже имеет ответ на данный вопрос. Прохожу курс по Azure и там необходим аккаунт есть 2 варианта  - бесплатный пробный и pay as go. Так вот ни в один меня не регистрирует. Нахожусь в Беларуси, может кто сталкивался с такими проблемами, не нашёл информации о том, чтобы майкрософт закрыл доступ РБ и РФ.
P.s - пробовал под 3-мя разными аккаунтами и пробовал привязывать разные карты

A: На скрине написано, что нет прав на использования аккаунтом.
Microsoft приостановил продажу товаров и услуг. Написано для России, но похоже там не разбирались и заблокировали для двух стран, либо где-то есть дополнительная информация.

*

*https://blogs.microsoft.com/on-the-issues/2022/03/04/microsoft-suspends-russia-sales-ukraine-conflict/

*https://habr.com/ru/news/t/657601/

*https://devby.io/news/google-cloud-bolshe-ne-registriruet-novyh-polzovatelei-iz-rossii
Попробуйте использовать VPN для бесплатной версии. Возможно для платной версии вам понадобится карта/счет другой страны, если оплата не будет проходить.


text:
Q: Reliable way to sniff XMLHttpRequest (browser sniffing for AJAX requests) in ASP.NET? I want to add an additional roadblock in my application to prevent automating it via javascript, specifically when the automated requests are being done via XMLHttpRequest from any of the popular browsers.
Is there a reliable tell-tale sign of a XMLHttpRequest that I can use in ASP.NET?
And I guess the other related question is, is it hard for XMLHttpRequest to appear to be an ordinary human driven request?  Because if it is, then I guess I'm on fools errand.
UPDATE: I might be phrasing the question too narrowly.  The goal is to detect : code written by someone else, not submitted by a ordinary browser, might be a bot, might not be from a my intranet customers, etc.  So far XHR and .NET WebRequest requests come to mind.

A: no, there is no way of doing this.  a lot of the popular libraries like jquery put a special header ("x-requested-with" for jquery) to indicate it's an ajax call, but that's obviously voluntary on the part of the client.
you must assume that any request you receive may be malicious unfortunately

A: You could always use a CAPTCHA to ensure that a human is responsible for submitting the request. recaptcha.net is free and helps to digitize books.
Edit:
If you know what type of malicious behavior you are trying to prevent, you could develop simple algorithms for detecting that behavior.  When that behavior is detected you could challenge the client with a CAPTCHA to ensure that a human is responsible.  This approach is starting to become common practice.  Take a look at this post on this topic.

A: You can perform a few sneaky things, but unfortunately it won't deter everyone. For example, you could place some JavaScript on a start/login page that is run when the page is loaded. This JavaScript causes a redirect and potentially writes an encrypted cookie value that is sent back to the server. Using XMLHttpRequest (or others) obviously just returns the content and doesn't execute any JavaScript, so you can can filter these requests out because they don't have the cookie value set by the script. Running some obfuscation on the JavaScript would be even better.

A: There's no way to find out if a request is forged or not. With the .NET HttpWebRequest class you can perfectly mimic any valid HTTP request from a browser. But depending on your application, you can consider one of the following:

*

*Look at HTTP headers to find the most blatant attempts

*Prevent too many requests from the same IP address in a short time frame

*Require a login

*Only allow certain IP address ranges

*CAPTCHAs

*Run some Javascript code before submit to make a hack with .NET HttpWebRequest harder (see Mark Barnard's answer)

You have to find out why people would try to do this, and then find a way to make it very inconvenient for them. Possibly in such a way that you can easily modify the validation procedure, so that they have to keep up all the time.

A: You could implement a strategy using request challenge tokens, not unlike what might be used for CSRF/XSRF protection. Another possible alternative might be using authentication, although if you have a public website this might not be very friendly.

A: As far as I know, all implementations of XMLHttpRequest add a header to the request.
Edit:
Sorry, the header (at least under PHP) is 'HTTP_X_REQUESTED_WITH'


text:
Q: XAML don´t know the Resource folder I tried to set up a Icon in XAML from the Resources.resx but it cant find the resources.
Code:
....
xmlns:resx="clr-namespace:Admin_Overwatch.Properties"
Title="MainWindow" Height="400" Width="600" Icon="{x:Static
resx:Resources.TitelLogomRand1}">

Error:
"The name "Resources" doesen´t exist in the namespace...."
The courious thing is that in the autoformat it finds every icon in the Resources file. I have Rebuild it without any success and tried a new Resource folder also with no success.
Why doesn´t it find the Folder(s) ?
Edit:
I tried this tutorial also without any success, I got the same error, it can´t find the resources....
http://social.technet.microsoft.com/wiki/contents/articles/22420.binding-to-resources-resx-files-in-xaml.aspx

A: The Answer was to use the Assembly in addition to the normal clr:
xmlns:resx="clr-namespace:Admin_Overwatch.Properties;assembly=Admin-Overwatch"
xmlns:local="clr-namespace:Admin_Overwatch;assembly=Admin-Overwatch"

The Assembly name can be found by
Right Click on the Project name under Properties --> Application.
But the important part is that it is not possible to load the pictures from the resx in wpf that goes only in win forms.
see here:
How to use Resources.resx to link images

A: I had simmilar problem. Added a placeholder image to use as default ImageSource in XAML on startup. I created it trough Project+Right-Click->Properties>Resources>Add Resource>New Image etc.
Then got to Resource folder in the project, selected the image and down bellow in properties I just selected Build Action to Resource. And now it works!


text:
Q: Make em units relative to an ancestor that is not the parent Is it possible to make em units relative to say an outer paragraph element instead of it's immediate parent? Override the cascade?
In the example below, the word world's font-size will end up (1.5em x 1.2em x 1em) large.
While maintaining the same html structure, can we somehow make it just (1.5em x 1em) large?

     Hello world.

UPDATE:
In my case simply using rem units appears to be the best best. It's supported by IE 9+ (in addition to Chrome 4+, Firefox 3.6+, Opera 11.6+ and Safari 4.1+)
rem Represents the font-size of the root element (typically ). When used within the root element font-size, it represents its initial value (a common browser default is 16px, but user-defined preferences may modify this).
https://developer.mozilla.org/en-US/docs/Web/CSS/length#rem
:root Selects the root element of the document:  in the case of HTML
https://developer.mozilla.org/en-US/docs/Web/CSS/:root
/* css */
:root {
    font-size: 1em;
}

html:

    Hello

    world.

Also using em units alone this could have been worked out with the css calc() function (which is also supported by IE 9+) and some javascript.
https://developer.mozilla.org/en-US/docs/Web/CSS/calc
Thank you everyone for your answers and help with this!

A: Maybe the calc() function can help:

   Hello
     world.

What you have:

   Hello world.

What you want, by using calc() function:

   Hello world.

Explanation
Here's your code:

     Hello world.

Let's say the body element is set to 16px and is the parent of your p element.
Since em units are relative to the parent, this means that the p has a font size of 16px.
1em = 16px

As a result, the child of p – the first span – has a font size of 19.2px.
1.2em * 16px = 19.2px

The child of the span – another span – then has a font size of 28.8px.
1.5em * 19.2px = 28.8

You want your second span to be 24px, which is the font size of its grandparent (16px) times 1.5.
So this would be the calculation:
font-size: calc(1.5em * (1/1.2))

1em / 1.2em     = .833em
1.5em * .833em  = 1.25em
1.25em * 19.2px = 24px


text:
Q: Set Parameter On click C3Js from columns/data name Is it possible to pass the value of data columns into the event onclick on c3Js ?

var chart = c3.generate({
  bindto: '#chart',
  data: {
    columns: [
      ['data1', 30, 200, 100, 400, 150, 250],
      ['data2', 50, 20, 10, 40, 15, 25]
    ],
    onclick: function() {
      alert('a');
    }
  }
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.css" rel="stylesheet" />

Case
Can i change the alert('a') to alert(columns[0][0]) // or what,sorry i have no idea, which output will be data1 if i clicked the blue line, and so are if i clicked the yellow ones it will be alerting data2.

Purpose
What i'am trying to do is.. i want to make new link by click the graph and sent the primary key from the data parameters.. The Problem is i don't know how to pass the columns name from the selected line.

A: According to the documentation,
data.onclick will

receive d and element as the arguments. d is the data clicked and element is the element clicked

So try changing your code to:
onclick: function(d, element) {
      alert(d);
    }
(Or better yet, use console.log if it's just for debugging)
If you run into any further problems, let me know and I will update my answer.


text:
Q: VS2012 SiteMapNode not the same as VS2010? I'm trying to upgrade an MVC3 project from Visual Studio 2010 to Visual Studio 2012, however I'm coming across an issue at runtime with the XMLSiteMapProvider code.
I am getting a null reference exception being thrown in VS2012, even though the code happily runs in VS2010, and the code hasn't changed.
My code is as follows:
XmlSiteMapProvider site = new XmlSiteMapProvider();
SiteMapNode currentNode = site.FindSiteMapNodeFromKey(HttpContext.Current.Response.ApplyAppPathModifier(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath));

Screenshots of both VS2010 and VS2012 watches are given below:
http://i.stack.imgur.com/siajS.png
http://i.stack.imgur.com/VAsMg.png
What you should be able to see is the code above split into its constituent parts to see whats being returned. The important one is the last row in the VS2012 window which chows a null being returned, whilst the "Member Selection" value is found in VS2010.
Does anyone have any ideas?
I have checked the .Net version, and the file versions on the System.Web.dll file which contains this class, and they are the same across both versions of Visual Studio.
The only difference is that VS2012 is running in Win7, whilst VS2010 is running in WinXP.
Could this be IIS version differences?
If I write the following code, VS2012 will correctly work, however VS2010 breaks instead, so it looks as if something is not exactly the same across versions.
XmlSiteMapProvider site = new XmlSiteMapProvider();
SiteMapNode currentNode = site.FindSiteMapNodeFromKey(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath);

Any help would be much appreciated,
Nick


text:
Q: CSS: clear: left working too well? I have an issue every now and again and I'm not sure what the solution is.
I have a 2 column layout (left strit, and then main area).  In the main area, I sometimes have a secondary 2 column layout (eg - for a news section, where there is an icon, and then the news item).  When I clear left on the new item, instead of clearing the image above it (which is left floated) it clears the nav bar on the left.
Here is a sample.  This seems to be an issue on FF3.6, whereas IE8 seems fine.

A: for the #mainContent add overflow:auto; or overflow:hidden; to clear the floats. Read more here http://www.quirksmode.org/css/clearing.html

A: On your <div> that contains each news section, try adding overflow: hidden. I think that should isolate the uses of clear within that <div>.

A: Instead of using columns for you news columns to separate icons and text - what if you use a "float:left" on the image?  For example, look on this page:
http://clayclerk.com/
The Css styling for the image is:
.imageleft {
float:      left;
margin-right:   10px;
}


text:
Q: 2-bit branch prediction accuracy I am trying to solve this problem, the answer should be 15/20 = 75%.
However, I am not sure how this was calculated and want to understand the underlying concept.
A program core consists of five conditional branches. The program core will be executed thousands of times. Below are the outcomes of each branch for one execution of the program core (T = taken, N = Not taken).
 Branch 1: T-T
 Branch 2: N-N-N
 Branch 3: T-N-T-N-T
 Branch 4: T-T-T-N
 Branch 5: T-T-N-T-T-T

This behavior remains the same. For dynamic schemes, assume each branch has its own prediction buffer and each buffer initialized to the same state before execution.
What is the prediction accuracy for the 2-bit predictor, initialized to weakly predict taken? (Answer is at the beginning but I'd like to understand the concept of the calculation.)

A: First off, I think it's important for you to specify when you do these types of problems (and clarify by asking your professor) which type of 2-bit predictor is being used, because there are 2 types.
The first type makes a transition from a weak state to the alternate weak state on failure.
The second type makes a transition from a weak state to the alternate strong state on failure.
For this problem, I am assuming it is the first type, which transitions from a weak state to the alternate weak state upon failure. That is the type shown in the picture below:

Consider what happens in each case individually:
WT = weakly taken
ST = strongly taken
WN = weakly not taken
SN = strongly not taken
Branch #1
Predict WT - T : 1/1

Predict ST - T : 1/1

Total : 2/2
Branch #2
Predict WT - N : 0/1

Predict WN - N : 1/1

Predict SN - N : 1/1

Total   2/3
Branch #3
Predict WT - T : 1/1

Predict ST - N : 0/1

Predict WT - T : 1/1

Predict ST - N : 0/1

Predict WT - T : 1/1

Total : 3/5
Branch #4
Predict WT - T : 1/1

Predict ST - T : 1/1

Predict ST - T : 1/1

Predict ST - N : 0/1

Total : 3/4
Branch #5
Predict WT - T : 1/1

Predict ST - T : 1/1

Predict ST - N : 0/1

Predict WT - T : 1/1

Predict ST - T : 1/1

Predict ST - T : 1/1

Total : 5/6
Total of all branches : 15/20

A: Assuming this is a local branch predictor, the answer of 5 mispredictions and 15 correct predictions. The easiest way to visualize this problem is by creating the FSM for a 2-bit branch predictor and flowing through each branch to see what the predictor predicts and what state is moves to:

Using this FSM, we per branch see what it predicts and what it goes to next:
Branch 1:

Step:         T   T
Prediction:   T   T
State:        WT  ST
NextState:    ST  ST
Correct?:     Y   Y

Branch 2:

Step:         N   N   N
Prediction:   T   N   N
State:        WT  WNT SNT
NextState:    WNT SNT SNT
Correct?:     N   Y   Y

Branch 3:

Step:         T   N   T   N   T
Prediction:   T   T   T   T   T
State:        WT  ST  WT  ST  WT
NextState:    ST  WT  ST  WT  ST
Correct?:     Y   N   Y   N   Y

Branch 4:

Step:         T   T   T   N
Prediction:   T   T   T   T
State:        WT  ST  ST  ST
NextState:    ST  ST  ST  WT
Correct?:     Y   Y   Y   N

Branch 5:

Step:         T   T   N   T   T   T
Prediction:   T   T   T   T   T   T
State:        WT  ST  ST  WT  ST  ST
NextState:    ST  ST  WT  ST  ST  ST
Correct?:     Y   Y   N   Y   Y   Y

So, if we count the number of Ys, we get 15/20 or an accuracy of 75%. (conversely, 5/20 Ns, so 25% misprediction).

A: A two-bit predictor is just a number from 0 to 3, like this

*

*0 - strongly not taken

*1 - weakly not taken

*2 - weakly taken

*3 - strongly taken

where state (2) is what you'd get at first branch execution.

*

*Branch 1: T-T - the predictor is right the first time, and the predictor is increased (with saturation at (3)) and predicts "taken" for both iterations

*Branch 2: N-N-N - the first one is a failure, and the predictor is decreased (with saturation at (0)), predicting the next two Ns. We have 2 hits, 1 miss.

*Branch 3: T-N-T-N-T - the one here is interesting. We oscillate between (3) and (2), being wrong on each "N". 3 hits, 2 misses.

*Branch 4: T-T-T-N - this is similar; out of 4 occurrences, one is mishandled

*Branch 5: T-T-N-T-T-T - again, out of 6 occurrences, one is mispredicted.

Summing hits and misses: (2h+0m) + (2h+1m) + (3h+2m) + (3h+1m) + (5h+1m)
Summing: 15 hits, 5 misses
Accuracy = hits / (hits + misses) = 15 / 20.

A: Well, you don't even need to do the math if you note that a 2-bit predictor changes its mind if it mispredicts two times in a row.
Branch 1: always predicts right (2/2)
Branch 2: always predicts rights (3/3)
Branch 3: this one is interesting. For this one you need to write the states and do the math. it turns out you can predict correctly 3 out of 5. For this case, the initial value of the predictor is important.
Branch 4: 3 out of 4
Branch 5: 5 out of 6
total is 15 out of 20.
Takeout: A 2-bit local predictor works well for highly biased branches, but not for branches that change frequently (like Branch 3).