text:
Q: Detecting compiler configuration in cmake file Either this is really easy and I'm just not able to find the correct way to do it, or I've wildly misunderstood something. I'm attempting to add a conditional to a CMakeLists.txt file to include the proper .lib file depending on which build configuration type is being used (within visual studio at the moment). So for example, if configuration in visual studio is set to Debug then use file zlibstaticd.lib vs zlibstatic.lib. Below is what I have that's not working:
add_library(ZLIB_LIBRARY OBJECT IMPORTED)
# zlib added via assimp, and I can't get CMAKE_DEBUG_POSTFIX value to overwrite (because it's set within zlibs cmake file when using MSVC)
# so we have to do this check

if($<CONFIG:Debug>)
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstaticd.lib)
else()
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstatic.lib)
endif()

I've also tried CMAKE_BUILD_TYPE but it's always an empty string. Below is my entire CMakeLists.txt file so you can see what it is I'm doing (building a singular static library which contains many other static libraries):
cmake_minimum_required(VERSION 3.20.0)

# Define our project name
set(PROJECT_NAME myProjectName)
project(${PROJECT_NAME})

# Make sure binary directory is not the same as source directory
if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR)
  message(
    FATAL_ERROR
      "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there."
  )
endif()

# This Project Depends on External Project(s)
include(ExternalProject)

set(libGLFW glfw)
ExternalProject_Add(${libGLFW}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLFW}
GIT_REPOSITORY  https://github.com/glfw/glfw.git
GIT_TAG         3.3.4
GIT_SHALLOW     ON
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLFW}/install
                -DGLFW_BUILD_DOCS:BOOL=OFF
                -DGLFW_BUILD_EXAMPLES:BOOL=OFF
                -DGLFW_BUILD_TESTS:BOOL=OFF
)

set(libGLAD glad)
ExternalProject_Add(${libGLAD}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLAD}
GIT_REPOSITORY  https://github.com/Dav1dde/glad.git
GIT_TAG         origin/master
GIT_SHALLOW     ON
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLAD}/install
                -DGLAD_INSTALL:BOOL=ON
                -DGLAD_PROFILE:STRING="core"
                -DGLAD_ALL_EXTENSIONS:BOOL=ON
                -DUSE_MSVC_RUNTIME_LIBRARY_DLL:BOOL=OFF
)

set(libGLM glm)
ExternalProject_Add(${libGLM}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLM}
GIT_REPOSITORY  https://github.com/g-truc/glm.git
GIT_TAG         origin/master
GIT_SHALLOW     ON
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLM}/install
                -DBUILD_SHARED_LIBS:BOOL=OFF
                -DBUILD_STATIC_LIBS:BOOL=OFF
                -DGLM_TEST_ENABLE:BOOL=OFF
)

set(libAssimp assimp)
ExternalProject_Add(${libAssimp}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/dep/${libAssimp}
GIT_REPOSITORY  https://github.com/assimp/assimp.git
GIT_TAG         v5.0.1
GIT_SHALLOW     ON
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/dep/${libAssimp}/install
                -DASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT:BOOL=OFF
                -DASSIMP_BUILD_ALL_EXPORTERS_BY_DEFAULT:BOOL=OFF
                -DBUILD_SHARED_LIBS:BOOL=OFF
                -DASSIMP_BUILD_ASSIMP_TOOLS:BOOL=OFF
                -DASSIMP_BUILD_TESTS:BOOL=OFF
                -DASSIMP_BUILD_FBX_IMPORTER:BOOL=ON
                -DASSIMP_BUILD_OBJ_IMPORTER:BOOL=ON
                -DASSIMP_BUILD_OBJ_EXPORTER:BOOL=ON
                -DASSIMP_LIBRARY_SUFFIX:STRING=
                -DLIBRARY_SUFFIX:STRING=
                -DCMAKE_DEBUG_POSTFIX:STRING=
                -DASSIMP_INJECT_DEBUG_POSTFIX:BOOL=OFF
)

# Note set_target_properties will need conditionals for windows/linux since extensions differ

# Create the oject files we will join together to create our singular static library, using the projects
# that were previously added above via ExternalProject_Add
# INSTALL_DIR not being set to value of CMAKE_INSTALL_PREFIX, so manuallysetting
#ExternalProject_Get_Property(${libGLFW} INSTALL_DIR)

# SETUP GLFW
set(GLFW_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLFW}/install)
add_library(GLFW_LIBRARY OBJECT IMPORTED)
set_target_properties(GLFW_LIBRARY PROPERTIES IMPORTED_OBJECTS ${GLFW_INSTALL_DIR}/lib/glfw3.lib)

# SETUP GLAD
set(GLAD_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLAD}/install)
add_library(GLAD_LIBRARY OBJECT IMPORTED)
set_target_properties(GLAD_LIBRARY PROPERTIES IMPORTED_OBJECTS ${GLAD_INSTALL_DIR}/lib/glad.lib)

# SETUP GLM
# GLM is header only library, so we simply include it's include directory in target_include_directories below
set(GLM_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/dep/${libGLM}/install)

# SETUP ASSIMP and it's dependencies
set(ASSIMP_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/dep/${libAssimp}/install)
add_library(ASSIMP_LIBRARY OBJECT IMPORTED)
set_target_properties(ASSIMP_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/assimp.lib)

add_library(IRRXML_LIBRARY OBJECT IMPORTED)
set_target_properties(IRRXML_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/IrrXML.lib)

add_library(ZLIB_LIBRARY OBJECT IMPORTED)
# zlib added via assimp, and I can't get CMAKE_DEBUG_POSTFIX value to overwrite (because it's set within zlibs cmake file when using MSVC)
# so we have to do this check

if($<CONFIG:Debug>)
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstaticd.lib)
else()
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstatic.lib)
endif()

# Documentation states not to do this, but do it anyway for the time being since it prevents us from having
# to manually list all project files
file(GLOB_RECURSE headers CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/inc/*.h")
file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")

# Create a single .lib file containing our compiled objects, and the compiled objects of all other dependencies
add_library(${PROJECT_NAME} STATIC ${headers} ${sources}
    $<TARGET_OBJECTS:GLFW_LIBRARY>
    $<TARGET_OBJECTS:GLAD_LIBRARY>
    $<TARGET_OBJECTS:ASSIMP_LIBRARY>
    $<TARGET_OBJECTS:IRRXML_LIBRARY>
    $<TARGET_OBJECTS:ZLIB_LIBRARY>
)

# Add all include file paths
target_include_directories(${PROJECT_NAME}
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/inc
    PUBLIC ${GLFW_INSTALL_DIR}/include
    PUBLIC ${GLAD_INSTALL_DIR}/include
    PUBLIC ${GLM_INSTALL_DIR}/include
    PUBLIC ${ASSIMP_INSTALL_DIR}/include
)

# Specify the order in which libs depend on each other, use the name of the ExternalProject, not the name of the
# library object you create and use with add_library
add_dependencies(${PROJECT_NAME} ${libGLFW} ${libGLAD} ${libGLM} ${libAssimp})

A:
add_library(ZLIB_LIBRARY OBJECT IMPORTED)
# zlib added via assimp, and I can't get CMAKE_DEBUG_POSTFIX value to overwrite (because it's set within zlibs cmake file when using MSVC)
# so we have to do this check

if($<CONFIG:Debug>)
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstaticd.lib)
else()
    set_target_properties(ZLIB_LIBRARY PROPERTIES IMPORTED_OBJECTS ${ASSIMP_INSTALL_DIR}/lib/zlibstatic.lib)
endif()

Generator expressions are evaluated after the configuration step has run, so they're just literal strings when the if() statement sees them. Basically, the CMake configure step is meta-programming a declarative language of targets and generator expressions that gets compiled into Ninja build files (or whatever) by the generator.
You can set the library up as follows:
add_library(zlib OBJECT IMPORTED)
set_target_properties(
  zlib
  PROPERTIES
    IMPORTED_OBJECTS_RELEASE "${ASSIMP_INSTALL_DIR}/lib/zlibstatic.lib"
    IMPORTED_OBJECTS_DEBUG "${ASSIMP_INSTALL_DIR}/lib/zlibstaticd.lib"
)

CMake first tries IMPORTED_OBJECTS_$<CONFIG> before trying IMPORTED_OBJECTS when resolving a library path.

All that said, I have to wonder why you don't just use find_package, vcpkg, Conan, or maybe add_subdirectory / FetchContent to manage your dependencies. This seems like a lot of pain given that all of those libraries (I think) either provide their own find_package config packages or CMake provides a find module for them.


text:
Q: How to return a relational data from DB in ASP.Net Core Web API Controller I have 3 relational table
1-Posts ,
2-Comments ,
3-Images
"Comments" and "Images" tables have "posts" Foreign Key . I want to return complete information about a post from all tables together in an ASP.Net Core Web API with GET Method . I know how to create controller and such things . My problem is about retrieving and returning data.

A: If you are using the EFCore, you can do this.

*

*Create an ApiController

*Inject your DbContext from Constructor

*Read data from DB

*Return data

[Route("api/[controller]")]
[ApiController]
public class PostController : BaseController
{
    private readonly ApplicationDbContext _dbContext;//Your DbContext
    public PostController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    [HttpGet]
    public IActionResult Get()
    {
        var data = _dbContext.Post.Include(a=> a.Comments).Include(a=> a.Images).ToList();
        return Ok(data);
    }

}

In .Net Core Lazy loading is disable and when you select a table from database none relation loaded by default.
If you want get all data with relations you must use Include to load relations like this
dbContext.Post.Include(a=> a.Comments).Include(a=> a.Images).ToList();

your database tables should be like this
public class Post
{
    public ICollection<Images> Images { get; set; }
    public ICollection<Comments> Comments { get; set; }
}
public class Comments
{
    public Post Post { get; set; }
}
public class Images
{
    public Post Post { get; set; }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to move files in Shell I have two folder xyz and Bin. I want to move xyz directory and it's sub directory as well to Bin folder.
I want output like this:
Bin/xyz/q.html
       /images/0.gif

How can do move files and subdirectory and I will get that type of output.

A: Move (mv) can be thought of as rename. If mv is used to move a file from one drive to another, then a copy will be made and the original will be deleted.
If the file is a directory (folder), then all of the contents of that directory are also moved.
$ mv -v xyz Bin

moves the file called xyz, no matter what kind of file it is, even if it is a directory, into the existing directory called Bin. If Bin does not exist, then the move command will rename xyz to Bin.
If you only want to move a few files, for example, Bin/1.html is to be moved to Bin/xyz/1.html, then file being moved is a file called 1.html (not a directory called bin or xyz).
$ mv -v Bin/1.html Bin/xyz/1.html

will perform the move if the Bin/xyz exists and is a directory. If directory Bin/xyz does not exist, then this mv command will error because mv does not create parent destination directories.
$ mkdir -v Bin/xyz

will create an empty directory called xyz in an existing directory called Bin. Then files can be moved into the existing Bin/xyz directory.
The -v (--verbose) tells mv and mkdir to report what happened. The output that they produce given a success is what -v does. The most common way to list the content of a directory is ls, but the indentation that you desire will require some programming.
$ man mv
$ man mkdir

will show all the features of the mv an mkdir commands.


text:
Q: Pandas combining same row into new column while preserving the row(not a simple group-by) I am a pandas beginner and in need of some help.
I have the following pandas dataframe:
ID         Val-A   Val-B

aab12      lower   -30
dbc11      lower   -10
aab12      upper   50
dbc11      upper   20

I want to produce a new dataframe from the previous one and can't think of a way to do it:
ID         Val-A  Val-B  upper-lower
aab12      lower  -30    80
aab12      upper  50     80
dbc11      lower  -10    30
dbc11      upper  20     30

Any help will be highly appreciated!

A: I think you need sort_values first with reset_index for nice monotonic unique index and then transform with abs and sum:
df = df.sort_values('ID').reset_index(drop=True)
df['upper-lower'] = df['Val-B'].abs().groupby(df['ID']).transform(sum)

print (df)
      ID  val-A  Val-B  upper-lower
0  aab12  lower    -30           80
1  aab12  upper     50           80
2  dbc11  lower    -10           30
3  dbc11  upper     20           30

A: Assuming you have two positive number:
df['upper-lower']=df.groupby('ID')['Val-B'].apply(lambda x : x.diff().abs().bfill())
df.sort_values('ID')
Out[394]:
      ID  Val-A  Val-B  upper-lower
0  aab12  lower    -30         80.0
2  aab12  upper     50         80.0
1  dbc11  lower    -10         30.0
3  dbc11  upper     20         30.0


text:
Q: gnuplot contour plot pm3d not visible for unstructured mesh I am a newbie to gnuplot, I would like to plot my CFD data as contour using the pm3d. I do not have visible figure due to the number of grid,  here is the code and the plot
reset
set size 1.,1.
set origin 0,0.
unset contour
set nokey
set view map
set dgrid3d 50,50,2
set pm3d
#set zrange[0.5:1]
set xrange[0:800]
set yrange[0:400]
splot var2 us ($1):($2):($3) w pm3d

Fig CFD data with gnuplot

Using ParaView, the CFD data plot is


text:
Q: How can I add tooltip on content of table I am very new to java script. I wanted to add tooltip to given below content. There is one way of doing it that is we can do by Adding title to every td tag. Now How can I add title to every td with same value. I am not allowed to touch html code below written here as It is automatic generated code using Jtbale Plugin.

    admin-ui
    /admin/manage/client
    Client Manager
    Used for redirecting to Client Management page

    admin-ui
    /admin/manage/configuration
    Configuration Manager
    Used for redirecting to configuration page

Any Help Will be appreciated.

A: You can add a title-tag via the .attr()-function and just invoke the tooltip after that:
$('table td').attr('title', 'testtitle').tooltip();

To expand the tooltip to the width of it's content you may have to add the following css:
.ui-tooltip{
    max-width: 100%;
}

Demo

A: You could do something like this, its for all td's because I'm not sure what do you mean by 'every td with same value':
$(function(){
    $.each($('td'), function() {
        $(this).attr("title", $(this).text());
    });
});

Here is fiddle.

A: To add title to the td with same value you can do it as below:
DEMO
$.each($('td'),function(){
   if($(this).text()==="admin-ui")
       $(this).attr('title',$(this).text())
});


text:
Q: Android: why am I not able to open pdf downloaded from DownloadManager inside public Download/myfolder directory in Android 11? I wasn't facing this issue in Android 9 and in Android 10 i opted out for Legacy Storage. But in Android 11, I am not able to open the file downloaded from Download Manager. The same file can be opened from file Manager, though.
Also, I checked the owner of that file, it is showing com.android.providers.downloads and not my app.
I am also creating a pdf file in Document/myfolder directory, and it can be easily openable using intent and there my app is the owner of that file.
Also, if I am saving the downloaded file to Document/myfolder directory, it still can't be opened using that intent.
As per my understanding, from Android 11, they introduced scope storage, and if the owner of that file is  accessing it. It will allow to read/write through READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permission.
For both the file, I am using the same Intent.
Anyone has idea how to change the owner of my downloaded file so that i can gain open or what is the exact reason i am not able to open that downloaded file?
 Intent intent = new Intent(Intent.ACTION_VIEW);

 intent.setDataAndType(uri, PDF_TYPE);

 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);

 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

Here PDF_TYPE is correct and uri is also correct.
DownloadManager code is also correct here a small snippet
                        .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath.getPath());

A: I am having the same issue, but in Android 10.
This works for me in Android 11
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);

A: I was facing the same issue even though I was saving my files to downloads directory. When I register a receiver and open it after download is completed then it's working fine with below code
    private void openPdf(File file) {

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = FileProvider.getUriForFile(BudgetBookActivity.this, "com.demo.fmsapp", file);

    intent.setDataAndType(uri, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    try {

        startActivity(Intent.createChooser(intent, "Open File"));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(BudgetBookActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Log.d(BudgetBookActivity.class.getSimpleName(), "Some error for budget" + e.getMessage());
    }
}

and this is my download code I was using
                    dialog = ProgressDialog.show(activity(), "", "Downloading file please wait", true);

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                request.setTitle(fileName);
                request.setDescription("Budget Volume PDF");
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);

                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                downloadID = manager.enqueue(request);

I was getting uri from the download id using this : Uri uri = dm.getUriForDownloadedFile(downloadID);
then I get file from URI then pass it to openPdf method but the problem was that it wasn't working when I am trying to access it by this when I only had filename
                File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),fileName);

so what I unexpectedly did is just add a subpath to the download directory when saving and accessing file like this
private static final String APP_DOWNLOAD_PATH = "/test/";
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, APP_DOWNLOAD_PATH + fileName);

File file = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),APP_DOWNLOAD_PATH + fileName);

So I am using file provider so you need to configure same first. It's working fine.I don't why it's not working when saving to download folder itself though.


text:
Q: Regex to match any character without trailing / leading whitespace + min / max length I try to figure out how to match following values via preg_match using:
^[\S].*[\S]{3,10}$

Unfortunately, the min works from size of 4 and the max of 10 is being ignored at all as the pattern still machtes on a lenght of 11.

*

*Disallow leading and trailing spaces

*Allow any character inside

*Allow space within characters

*Enforce min of 3 and max of 10 (not working)

Testset that could be used with: https://www.phpliveregex.com
[
    [
        "Test",
        true
    ],
    [
        "Test Test",
        true
    ],
    [
        "Test-Test",
        true
    ],
    [
        "Test'Test",
        true
    ],
    [
        "Test,Test",
        true
    ],
    [
        null,
        false
    ],
    [
        "   ",
        false
    ],
    [
        " Test ",
        false
    ],
    [
        "12",
        false
    ],
    [
        "12345678901",
        false
    ]
]

Thanks for your help in advanced

A: You may use
^(?=.{4,10}$)\S.*\S$

See regex demo
Details

*

*^ - start of string

*(?=.{4,10}$) - four to ten chars other than line break chars up to the end of string allowed

*\S  - a non-whitespace char

*.*  - 0 or more chars other than line break chars as many as possible

*\S  - a non-whitespace char

*$ - end of string.


text:
Q: handleFacebookAccessToken returns error with Test Users This code works properly for ALL real life Facedbook Testers and mAuthNew.getCurrentUser() returns a valid user.
But using FAcedbook generated Test Users, created with v8.0 - user_friends, email, public_profile permissions, signInWithCredential
allways fails with "The supplied auth credential is malformed or has expired.."
Profile profile = Profile.getCurrentProfile() returns correct profile. isLoggedIn is true.
I'm probably missing something simple but brain is now addlepated and just can't see it.
Question is why/what?
 private void doFBLogin() {
        if (FBuser == null) {
                LoginManager.getInstance().registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Profile profile = Profile.getCurrentProfile();
                    Boolean hasExpired = AccessToken.getCurrentAccessToken().isExpired();
                    boolean isLoggedIn = AccessToken.getCurrentAccessToken() != null && !AccessToken.getCurrentAccessToken().isExpired();
                    //True for ALL logins
                    if (isLoggedIn) {
                        handleFacebookAccessToken(AccessToken.getCurrentAccessToken());
                    }
                }

               @Override
                public void onCancel() {
                    doFBLoginCB(-2, "Cancelled");
                }

                @Override
                public void onError(FacebookException exception) {
                    doFBLoginCB(-1, exception.getMessage());
                }
            });

            List<String> permissionNeeds = Arrays.asList("public_profile", "email", "user_friends");
            LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, permissionNeeds);
        } else {
            handleFacebookAccessToken(AccessToken.getCurrentAccessToken());
        }
    }

     private void handleFacebookAccessToken(AccessToken token) {
        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuthNew.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success

                           // Through here ONLY for all real life Facedbook Testers

                            FBuser = mAuthNew.getCurrentUser();
                        } else {
                            if (task.getException().getMessage().contains("invalid access_token")) {

                            } else if (task.getException().getMessage().contains("The supplied auth credential is malformed or has expired")) {
                            // Through here for all  Facedbook generated Test Users profiles

                            } else {
                               doFBLoginCB(-3, "Sign In failed");
                            }

                        }

                    }
                });

    }
    }


text:
Q: Google ML. Reading data and accessing specific folders from the Bucket So far to manage getting data from the bucket I use download_to_file() to get it downloaded on the instance that it is using and access the files/folders locally. Though what I want to achieve is being able to just read from the cloud. How can I go about doing that? There doesn't seem to be a way for me create a relative path from the ML Job instance and the google cloud bucket.

A: You can use TensorFlow's file_io.FileIO class to create file_like objects to read/write files on gcs, local, or any other supported file system.
See this post for some examples.


text:
Q: Give a deduction of $\forall zP(z)$ from $\forall xP(x)$. I am to give a deduction of the formula $\forall zP(z)$ from the given $\forall xP(x)$. So far I know that, because $x$ is always substitutable for itself, I have $P(x)$. My next step I think is to substitute $z$ for $x$ to get $P(z)$. However, I'm not sure how to proceed from here, or even if I'm allowed to substitute $z$ for $x$. A hint would be greatly appreciated. Thanks.

A: From the first quantifier rule, $(\forall x)P(x) \to P(z)$ entails that $(\forall x)P(x) \to (\forall z)P(z)$ (taking $\psi$ to be $(\forall x)P(x)$). But $(\forall x)P(x) \to P(z)$ is instantiation (note that the notation $\varphi^x_t$ means ``$\varphi$ with $x$ replaced with a term $t$'', and $z$ is a term).
This is made slightly fishy by the fact that the rules as you stated them only allow you to deduce $(\forall x)P(z)$, not $(\forall z)P(z)$; I suspect it says somewhere that in the quantifier rules, any variable may be used in place of $x$ in the quantifiers.

A: From the first quantifier axiom :

$(∀xϕ)→ϕ^x_t$

we can derive the instance: $(∀xP(x))→P(z)$.
What about the proviso that $z$ must be substitutable for $x$ in $P(x)$ ?
It is obviously satisfied, because $P(x)$ is not a schema, like $ϕ$: $P(x)$ is a unary predicate letter, with only one argument place. Thus, there are no "hidden" quantifiers that can "capture" $z$.
Now you can apply the first quantifier rule.
There are no free variables in  $(∀xP(x))$ and thus the proviso of the quantifier rule: "whenever $x$ is not free in $\psi$ ....", is satisfied with every variable, including $z$.


text:
Q: Reloading apache kills running FastCGI php scripts i am using apache 2.4 with php as fpm. Whenever i reload apache (graceful restart), a running php script is getting killed. The user then sees an error 500 and the following is getting logged:
Connection reset by peer: [client xx.xx.xx.xx:52240] FastCGI: comm with server "/usr/lib/cgi-bin/php5-fcgi" aborted: read failed

FastCGI: incomplete headers (0 bytes) received from server "/usr/lib/cgi-bin/php5-fcgi"

Is there a way to reload apache without "disturbing" running php processes?


text:
Q: How can I email a document from iWork without the recipient seeing the intermediate saved versions? It looks like we don't need to keep different files like on Windows 7:
speech 2012 rev 01.doc
speech 2012 rev 02.doc
speech 2012 rev 03.doc

So on Lion, we can just use "Save a version" and all versions will be there later on to "revert" to any version...  The functionality introduced with Lion's "Save a Version" is cool, but what if we want to email somebody but don't want the earlier versions to be sent?
So are all the old version separate files in the hard drive? (then what if I want to clear those versions out to make space?)   Or are those version embedded within the document?  What if I want to email speech rev final.pages to somebody and don't want to include all the versions then?

A: The versions are not embedded in the files, but instead get stored elsewhere.
Due to the nature of how Lion stores versions, small files get saved entirely, but larger files can track only the parts of the file that changed in fairly snazzy ways to reduce the chance that some trivial change to a very large file uses more than a trivial amount of version space.
When you mail any file, you don't send the version, just the last saved copy.
When you delete a file, the system checks and cleans out versions so you are generally never going to see a large amount of space tracking files that no longer exist.
If you are curious - this terminal command will tell you the sum total of the tracking and storage on your main drive: sudo du -sm /.DocumentRevisions-V100/
I have yet to see a mac with more than 200 meg of storage here, but post a new question if you ever find a bug or situation where this storage seems out of line. Lots of good information on this is on the site as well as elsewhere:

*

*Do OS X Lion's Versions and Resume features store the cached data for encrypted .sparsebundle images in a secure way?

*John Siracusa's very nice Mac OS X 10.7 Lion: the Ars Technica review : Versioning Internals


text:
Q: Selenium testing number input field (primefaces and jquery) I use primefaces in my application. There is an inputnumber widget among the extensions.
http://fractalsoft.net/primeext-showcase-mojarra/views/inputNumber.jsf
Under the hood it uses the autoNumeric Jquery plugin, that's why I tagged the question to jquery too.
My problem is when I try to fill the input, selenium IDE won't recognize it as a command. I think it's becouse of the underlying javascript, which deletes invalid (not number) input.
Any sugesstions, workarounds?
UPDATE
I want to use java webdriver or selenium server api. Couldn't make it work with them neither.

A: I had my answer at primefaces forum. Thank you @fenoloco.
http://forum.primefaces.org/viewtopic.php?f=14&t=35008&p=112415#p112415
input.sendKeys(Keys.??);
input.sendKeys(Keys.TAB);


text:
Q: Unable to run Tensorboard from command prompt tensorboard --logdir=./model/ted500/summaries

Starting TensorBoard 28 on port 6006

Sometimes it shows the url here and some times it's stuck there. I'm new to tensorboard, so have followed couple of tutorials in order to run it but seems its still not working.
Can someone please advice how to launch tensorboard ?

A: Generally we launch Tensorboard by writing:-
tensorboard --logdir='/your/path/here'

It may happen that some processes are using the port currently you are invoking for tensorboard. So, you can try changing the port at which tensorboard starts by writing:-
tensorboard --logdir='/your/path/here' --port=xxxx

write any unused port (Range:0 to 65535) in place of xxxx.
You can see the logs of tensorboard in terminal by writing:-
tensorboard --logdir='/your/path/here' --port=xxxx --debug

maybe it could help you.


text:
Q: Android resource linking failed that error appeared to me I got this error when I am trying to run my app, so how to fix it ?
C:\Users\oem.gradle\caches\transforms-2\files-2.1\b29f469d834fe6ac53c0c0e264e4ef98\core-1.7.0\res\values\values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

A: For those who have this issue in android change the version dependencies
ex implementation 'androidx.appcompat:appcompat:x.x.x'


text:
Q: how to use fs functions? Getting ERROR fs.readFileSync is not a function I am using PDFkit.js to export pdf. My page contains images. TO add images i am using
            var doc = new PDFDocument({
                bufferPages: true
            });

            var stream = doc.pipe(blobStream());
            var iframe = $('iframe')[0];
            var x = 0;
            var y = 0;
            var img;

     doc.image('http://mylogo.png', 20, 15, {width:100})
    .text('Proportional to width', 0, 0);
     doc.flushPages();

            // end and display the document in the iframe to the right
            doc.end();
            stream.on('finish', function() {
                iframe.src = stream.toBlobURL('application/pdf');
            });

Included In script:
<script src="{{asset('/js/pdfkit.standalone.js')}}"></script>
<script src="{{asset('/js/blob-stream.js')}}"></script>

But it is not displaying Image in PDF.
ERROR: fs.readFileSync is not a function


text:
Q: Save avatar from facebook in allauth There are questions here which answer this, but my case is different.
Instead of letting allauth create a new user I'm catching wheter or not the email exists and performing a login using
   user = User.objects.get(email=email)
   sociallogin.connect(request, user)
   social_account_added.send(
                sender=SocialLogin,
                request=request,
                sociallogin=sociallogin,
            )

But, I can't set the avatar here due to the way my conditions are setup and this may never be hit.
The alternative is in get_redirect_url from what I see, but this isn't called if I use sociallogin.get_redirect_url so it seems theres opportunity for both to be skipped.
There's a signal user_logged_in = Signal(providing_args=["request", "user"]) under account app in allauth but what if they have multiple socials connected? How would I determine the proper avatar to get...

A: Is your question:

*

*how to capture the avatar at signup?

*how to choose which avatar if there are multiple social accounts?

*how to hook the signup and instead connect the potential new user to an existing accout?

I'll address all three.
Capturing avatar at signup
My approach to this is receive the user_signed_up signal. I also extract the user name (if available) at this time.
This is the function I use:
@receiver(user_signed_up)
def set_initial_user_names(request, user, sociallogin=None, **kwargs):
    """
    When a social account is created successfully and this signal is received,
    django-allauth passes in the sociallogin param, giving access to metadata on the remote account, e.g.:

    sociallogin.account.provider  # e.g. 'twitter'
    sociallogin.account.get_avatar_url()
    sociallogin.account.get_profile_url()
    sociallogin.account.extra_data['screen_name']

    See the socialaccount_socialaccount table for more in the 'extra_data' field.

    From http://birdhouse.org/blog/2013/12/03/django-allauth-retrieve-firstlast-names-from-fb-twitter-google/comment-page-1/
    """

    preferred_avatar_size_pixels = 256

    picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format(
        hashlib.md5(user.email.encode('UTF-8')).hexdigest(),
        preferred_avatar_size_pixels
    )

    if sociallogin:
        # Extract first / last names from social nets and store on User record
        if sociallogin.account.provider == 'twitter':
            name = sociallogin.account.extra_data['name']
            user.first_name = name.split()[0]
            user.last_name = name.split()[1]

        if sociallogin.account.provider == 'facebook':
            user.first_name = sociallogin.account.extra_data['first_name']
            user.last_name = sociallogin.account.extra_data['last_name']
            # verified = sociallogin.account.extra_data['verified']
            picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format(
                sociallogin.account.uid, preferred_avatar_size_pixels)

        if sociallogin.account.provider == 'google':
            user.first_name = sociallogin.account.extra_data['given_name']
            user.last_name = sociallogin.account.extra_data['family_name']
            # verified = sociallogin.account.extra_data['verified_email']
            picture_url = sociallogin.account.extra_data['picture']

    profile = UserProfile(user=user, avatar_url=picture_url)
    profile.save()

    user.guess_display_name()
    user.save()

That's from a Django-allauth starter example I wrote
When the user signs in that function is called. It grabs the user's name and avatar data if it can.
Choosing which avatar if there are multiple accounts
My view is that this is a user choice thing. A user can't sign up with multiple social providers in the same instant.
There is always a sequence, e.g. Google first then they connect Facebook.
As such, my view is the system uses the avatar from the first social provider. The allauth UI lets the user add
other social providers once they've set up the initial one (try the deo-allauth-bootrap above and you'll see).
If the user adds another social network, add some UI to choose that avatar when they want to.
Hook signup to connect existing account
This would take some experimentation but overall I feel like this is not solving a real problem.
The built-in allauth UI allows the user (once registered) to add existing social providers. That's the correct
way to do it and it works out-of-the-box.
If the user signs up with another social provider then it's arguably either a mistake or they want two
separate accounts.
Granted, this needs some experimentation with users to see what is the most intuitive experience.
It could be, for example, that the site notes that the user has signed in with Google before and shows the Google
button slightly differently or "sign in again with Google", so the user doesn't accidentally sign up with a
different social account.


text:
Q: Background image center and resize I'm working on a site for a client in which there's a background image that will be centered on the page with text, links, etc. overlayed.
I currently have the image resized as follows:
img.bg
   {
   height:100%;
   position:absolute;
   }

This fits the image to the height of the browser, but aligns it to the left. I need it to be centered.
Since I need it to be conditionally responsive to browser-height variations, the usual centering tricks aren't working.
Thanks!

A: Try removing "position:absolute" and adding margin: 0 auto. For example:
img.bg
{
   height:100%;
   margin: 0 auto;
}

A: or may be just place it inside a table

"image goes here"
 it's easier to manage cause you can add more items to the webpage in future without difficulty, add borders, change colours of tables, etc.

A: I can think of a couple ways to go about it (untested, so you'll probably have to tweak):
img.bg {
   position: absolute;
   /* Top and/or bottom for stretching it vertically as needed. Setting both will likely make it the size of the whole body, so beware. Remove bottom to keep it from doing that if necessary. */
   top: 0;
   bottom: 0;
   /* Left and/or right for sizing/positioning */
   left: 25%; /* Percentage position will make it adjust to browser window size, exact percent may need to be tweaked to get right and will depend on the image's size. */
}

img.bg {
   display: block;
   height: 100%;
   width: 500px; /* Whatever your desired width is. */
   margin: 0 auto; /* This should work as long as width is set. */
}

Depending on your exact design, either of these should work and be responsive to the size of the browser window. The second one is probably the most flexible and easiest to implement, since you don't have to fiddle with positioning.

A: The answer depends on exactly what you are after.
If you want an image displayed in the background of the website (which I think you are saying) then I am not sure what method you are using, but if you do away with your img.bg{} in your html and css, and just put the following into your CSS you will get what you want...
body{
    background-image:url('background.gif'); // substitute background.gif for the correct file path
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center;
    background-size:auto 100%;
}


text:
Q: java.io.FileNotFoundException: http://localhost:8080/manager/text/list I'm learning Spring MVC with http://docs.spring.io/docs/Spring-MVC-step-by-step/part1.html. There's an error when executing "ant list":
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
Buildfile: /home/mycityofsky/java_workspace/springapp/build.xml
Trying to override old definition of task javac

list:

BUILD FAILED
/home/mycityofsky/java_workspace/springapp/build.xml:142: java.io.FileNotFoundException: http://localhost:8080/manager/text/list
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1835)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at org.apache.catalina.ant.AbstractCatalinaTask.execute(AbstractCatalinaTask.java:228)
    at org.apache.catalina.ant.AbstractCatalinaTask.execute(AbstractCatalinaTask.java:148)
    at org.apache.catalina.ant.ListTask.execute(ListTask.java:50)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
    at org.apache.tools.ant.Main.runBuild(Main.java:851)
    at org.apache.tools.ant.Main.startAnt(Main.java:235)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

Total time: 0 seconds

Some of the files are as follows.
build.xml:
<?xml version="1.0"?>

<project name="springapp" basedir="." default="usage">
    <presetdef name="javac">
        <javac includeantruntime="false" />
    </presetdef>

    <property file="build.properties"/>

    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="springapp"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <fileset dir="${appserver.lib}">
            <include name="servlet*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>

    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="build     --> Build the application"/>
        <echo message="deploy    --> Deploy application as directory"/>
        <echo message="deploywar --> Deploy application as a WAR file"/>
        <echo message="install   --> Install application in Tomcat"/>
        <echo message="reload    --> Reload application in Tomcat"/>
        <echo message="start     --> Start Tomcat application"/>
        <echo message="stop      --> Stop Tomcat application"/>
        <echo message="list      --> List Tomcat applications"/>
        <echo message=""/>
    </target>

    <target name="build" description="Compile main source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
               deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="deploy" depends="build" description="Deploy application">
        <copy todir="${deploy.path}/${name}" preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>

    <target name="deploywar" depends="build" description="Deploy application as a WAR file">
        <war destfile="${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
        <copy todir="${deploy.path}" preservelastmodified="true">
            <fileset dir=".">
                <include name="*.war"/>
            </fileset>
        </copy>
    </target>

<!-- ============================================================== -->
<!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
<!-- ============================================================== -->

    <path id="catalina-ant-classpath">
        <!-- We need the Catalina jars for Tomcat -->
        <!--  * for other app servers - check the docs -->
        <fileset dir="${appserver.lib}">
            <include name="catalina-ant.jar"/>
            <include name="tomcat-coyote.jar"/>
            <include name="tomcat-util.jar"/>
        </fileset>
        <fileset dir="${appserver.home}/bin">
                    <include name="tomcat-juli.jar"/>
        </fileset>
    </path>

    <taskdef name="install" classname="org.apache.catalina.ant.DeployTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="list" classname="org.apache.catalina.ant.ListTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="start" classname="org.apache.catalina.ant.StartTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>

    <target name="install" description="Install application in Tomcat">
        <install url="${tomcat.manager.url}"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"
                 path="/${name}"
                 war="${name}"/>
    </target>

    <target name="reload" description="Reload application in Tomcat">
        <reload url="${tomcat.manager.url}"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"
                 path="/${name}"/>
    </target>

    <target name="start" description="Start Tomcat application">
        <start url="${tomcat.manager.url}"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"
                 path="/${name}"/>
    </target>

    <target name="stop" description="Stop Tomcat application">
        <stop url="${tomcat.manager.url}"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"
                 path="/${name}"/>
    </target>

    <target name="list" description="List Tomcat applications">
        <list url="${tomcat.manager.url}/text"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"/>
    </target>

<!-- End Tomcat tasks -->

</project>

build.properties:
# Ant properties for building the springapp

appserver.home=/usr/share/tomcat7
appserver.lib=${appserver.home}/lib

deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager
tomcat.manager.username=tomcat
tomcat.manager.password=s3cret

How to solve the problem?

A: You need to start tomcat before you try to access its resources, and you need to deploy the application as well


text:
Q: pagination using post id Am new to php, i am try to use pagenation , where i post a unique id to a page then use that to load content with the respective id then pagenate all the content with that respective id.
Here below is what have been trying
<?php

    if (isset($_GET["post"]))
 {
$page  = $_GET["post"];
} else
 {
$page = 1;
 };
 $limit = 2;
 $total_records = $pagination;
  $total_pages = ceil($total_records/$limit);
  $lastpage = ceil($total_pages/$limit);

$page != 0;
$prev = $page - 1;                 //previous page is page - 1
$next = $page + 1;                          //next page is page + 1
  //lastpage is = total pages / items per page, rounded up.

if($prev == 0)
 $prev = 1;
 $next <= $lastpage;
   //if no page var is given, default to 1.

$pagLink = "
";

$pagLink .= "

    «
    Next

";

for ($i=1; $i<=$total_pages; $i++) {

 $pagLink .= "
".$i."
 ";

};

 $pagLink .= "

    »
    Next

";
  echo $pagLink . "
";

   ?>

Here is how i want to pagenate contents per id
enter image description here


text:
Q: How to use webmock regex matcher? How to match a URL like:
http://www.example.com/foo/:id/bar
http://www.example.com/foo/1/bar
http://www.example.com/foo/999/bar

stub_request(:post, "www.example.com")

A: You can use %r{} instead of // for your regular expression in Ruby to avoid having to escape the forward slashes in URLs.  For example:
stub_request(:post, %r{\Ahttp://www.example.com/foo/\d+/bar\z})

A: The second argument to stub_request must be a regular expression, not a string.
stub_request(:post, /http:\/\/www.example.com\/foo\/\d+\/bar/)

A: http://www\..*?\.com/foo/\d+/bar should work for you.


text:
Q: Notation and terminology for functions, interpreting $f(y)$ It seems to me there are two different interpretations of a symbol $f(y)$.
I will explain what I mean:
Suppose I have a function $f(x) = x$. (I took the identity map to have a simple example).
Also suppose I have a dependence between $x$ and $y$ which is another variable.
Say $x = 2y$.
I seems to me I can interpret $f$ and particularly the symbol $f(y)$ in two different ways:

*

*$f$ is strictly a map and it taken whatever variable we give it and maps it accordingly. In this case $f(y) = y$ as $f$ is the identity map so just maps $y$ to itself.

*$f$ is a variable dependent on $x$, since I've defined $f(x) = x$, then when I denote $f(y)$ I can interpret it as the variable $f$ but now expressed in terms of $y$ instead of in terms of $x$, so in this case $f(y) = x = 2y$.
In this case I viewed $f$ as already being defined in terms of x and the symbol $f(y)$ merely gives me this predefined variable $f$ in terms of $y$.
My question is what is the usual interpretation, and if there is convenient notation and/or common terminology which distinguish the two.

A: It is better to consider the composition of functions specifying range and domain.
Let us work in the easy setting:
$$f:\mathbb R\rightarrow \mathbb R,~~z\mapsto f(z):=z, ~~(*)$$
and
$$y:\mathbb R\rightarrow \mathbb R,~~x\mapsto y(x):=\frac{1}{2}x.$$
When you write $f(y)=y$ in $1.$ you are just considering the function $f$ on any element $y$ (call it $y$, $z$, $x$ etc...it is the same: you are using $(*)$).
When you write $f(y)=x=2y$ in $2.$ notation is confusing, instead. I believe you should introduce the composition the composition $g:=f\circ y:\mathbb R\rightarrow\mathbb R$, where
$$g(x)=f(y(x))=y(x)=\frac{1}{2}x.$$

A: I'll restrict this answer to the case where $f$ is a real function defined on the whole real line, ($f\colon \mathbb R\to \mathbb R$).
Since the domain of $f$ is $\Bbb R$, its input are real numbers. Therefore, the symbol $f(y)$ is meaningless if $y$ is not a real number.
In your example you set $f=\text{id}_\mathbb R$. Let $y$ be a real number. If it is the case that there exists $x\in \mathbb R$ such that $y=2x$, then $f(y)=f(2x)=2x$, by virtue of the definition of equality and of $f$.
If $y$ is a function (for simplication, let $\text{dom}(y)=\mathbb R$ and let it take only real values), then, as said before, $f(y)$ doesn't make sense. Something that makes sense is $f\circ y$ and, given $x\in \mathbb R$, $f(y(x))$ also makes sense because $y(x)\in \mathbb R$.
Now answering your question, the usual interpretation is that $y$ is a function and that you should look at $f(y)$ as $f\circ y$ (accompanied by a deep sigh), which is the convenient notation. Common terminology is saying that '$y$ is a function of $x$', which doesn't excuse the wrongness of $f(y)$.


text:
Q: Test transition from Windows Authentication to SQL Server authentication I have a windows forms application which connects to an SQL Server 2008 R2 database using variously SMO, databinding, and ODBC connections.
Currently it uses entirely Windows authentication, but a client has requested that we also allow SQL Server logins.
Given the only Windows login I have, and can have, is my own, what can I do to test whether my code is actually using the SQL Server login and not simply connecting using my own Windows login?
Alternatively, what can I do to refine this question so it makes sense?
Thanks

A: Your question is too general but here are some steps you should take.

*

*Create new sql login and only give necessary permissions to this user

*Update all connection strings in your application. If these are not consolidated in one config file now is the good time to do this. You can even consider creating a separate class that will handle this.

*Add login form to your app that will be shown at the application startup so that user can enter credentials

Best way to test this is to simply disable your windows user in SQL Server and see if application is still running.


text:
Q: How to stop htaccess rewrite rule updating browser URL I've read through many of the similar requests such as:
Apache rewrite rule - prevent rewritten URL appearing in browser URL bar
But I can't figure out what I'm doing wrong, any help would be much appreciated.
I'm using codeigniter 3 and it's root is at the following location:
https://example.com/api/v1.0

I've set up a basic route and all is working fine with Codeigniter E.g.  If I navigate to:
/api/v1.0/index.php/pages/view/about

the appropriate page appears so all seams well. What I really want is for the URL to get rewritten so that when I enter:
/api/v1.0/pages/view/about

it goes to the same page. I've added a htaccess file that rewrites the rule and all works as expected:
Options +FollowSymlinks
RewriteEngine on
RewriteBase /api/v1.0/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

The problem is, when I enter the the url:
/api/v1.0/pages/view/about

it goes to the correct page, but the browser URL gets updated to:
/api/v1.0/index.php/pages/view/about

My question is, how can I stop the browser URL from being updated?
Update - my web servers site behind an AWS ELB that acts as the https end point. I have the following in the httpd.conf to ensure that any non 'www' prefixed URLS and any http calls are redirected to https://www
<VirtualHost *:80>
    RequestHeader set X-Forwarded-Proto "http"

    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{REQUEST_URI} !^/_hostmanager/
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

    RewriteCond %{HTTP_HOST} !^www\.  [NC]
    RewriteCond %{HTTP_HOST} !^test\. [NC]
    RewriteCond %{HTTP_HOST} !^signup\. [NC]
    RewriteCond %{REQUEST_URI} !^/_hostmanager/
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

I don't think this rule is causing an issue as its not being invoked, I'm providing the correct prefix and protocol.
Many thanks in advance,
Rob

A: Check that index.php isn't set for $config['index_page'].
If it is change it to:
$config['index_page'] = '';

A: OK, after much testing it would appear that my virtual host settings in httpd.conf were causing the issue. If I removed these rules and then the local .htaccess rules worked exactly as expected.
I've removed the local .htaccess rules and added the following to rule to httpd.conf:
RewriteRule    ^/api/v1\.0/([A-Za-z0-9-/]+)/?$    /api/v1.0/index\.php/$1    [NC,L,QSA]    # Process API Call

My Virtual Host section now looks like this:

    RequestHeader set X-Forwarded-Proto "http"
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{REQUEST_URI} !^/_hostmanager/
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

RewriteCond %{HTTP_HOST} !^www\.  [NC]
RewriteCond %{HTTP_HOST} !^test\. [NC]
RewriteCond %{HTTP_HOST} !^signup\. [NC]
RewriteCond %{REQUEST_URI} !^/_hostmanager/
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteRule    ^/api/v1\.0/([A-Za-z0-9-/]+)/?$    /api/v1.0/index\.php/$1    [NC,L,QSA]    # Process API Call

So now calls to:
/api/v1.0/some/directory

Will get rewritten to this:
/api/v1.0/index.php/some/directory

And this happens without redirecting the browser or affecting the browser URL. What I don't understand is why this is not entering into an infinite loop as I have no rewrite precondition to check for calls to the /api/v1.0/index.php/*
Anybody know why this is no entering into an infinite loop?


text:
Q: Online/offline status in Spring Security In my web application I need to know whether users are online or offline. I need to update the status in the database whenever users' sessions are created or destroyed, so SessionRegistry is not an option.
I implemented it using session counters - when a user logs in, his counter increments, when he logs out or his session times out, his counter decrements.
web.xml
<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

Service
@Service
public class UsersLoginLogoutListener implements ApplicationListener<ApplicationEvent> {

    @Autowired
    private AccountService accountService;

    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof InteractiveAuthenticationSuccessEvent) { // User log in
            System.out.println("User logged in...");
            InteractiveAuthenticationSuccessEvent iasEvent = (InteractiveAuthenticationSuccessEvent) event;
            String userName = iasEvent.getAuthentication().getName();
            if (userName != null) {
                System.out.println("...username is " + userName + ".");
                accountService.incrementSessionCounter(userName);
            }
        }
        else if (event instanceof SessionDestroyedEvent) { // User log out / session timeout
            System.out.println("User logged out or session timeout...");
            SessionDestroyedEvent sdEvent = (SessionDestroyedEvent) event;
            List<SecurityContext> lstSecurityContext = sdEvent.getSecurityContexts();
            System.out.println("...SecurityContexts list size: " + lstSecurityContext.size() + "...");
            for (SecurityContext securityContext : lstSecurityContext)
            {
                String userName = securityContext.getAuthentication().getName();
                if (userName != null) {
                    System.out.println("...username is " + userName + ".");
                    accountService.decrementSessionCounter(userName);
                }
            }
        }
    }
}

It's been working just fine until recently, when I noticed that one counter was incremented, but never was decremented. Thanks to the logs I was able to reproduce it.
A user opens login pages in two browser tabs and logs in on one tab, then he logs in on another tab without logging out on the first tab. If he entered the correct credentials everything works fine:

User logged in... ...username is testuser.
User logged out or session timeout... ...SecurityContexts list size:
  1... ...username is testuser.
User logged in... ...username is testuser.

Even though he logged in twice using the same browser, his first session was destroyed and my counter worked correctly.
But if he entered incorrect credentials, I see the following output:

User logged in... ...username is testuser.
(After session timeout)
User logged out or session timeout... ...SecurityContexts list size:
  0...

As you can see, in this case SessionDestroyedEvent was fired, but only after the session timeout and SecurityContexts list was empty, so user's session counter wasn't decremented.


text:
Q: Cannot access the ASP.NET Core app deployed on Kubernetes I am new to Docker and Kubernetes, and trying to deploy my ASP.Net Core 6.0 web application on Kubernetes with Docker image. I can see the service running with type: NodePort as in the last line of the screenshot 1, but I cannot access this port on my browser at all.

I can also see the Docker container created by Kubernetes Pod running on Docker Desktop Windows application as in screenshot 2, but I don't know how to access my deployed application from the browser. Any suggestion or solution would be appreciated.

A: Seems to be you  need to expose the service , so that it will allow external traffic. In order to expose the service use : kubectl expose deployment <deployment> --type="Loadbalancer"--port=8080, this will create an external IP.
Check the created external IP by using Kubectl get services  command.
If not visible, wait for a few minutes to get the service exposed. So, wait for a few minutes and check again the External IP will be visible .
Now access the service using http://<EXTERNAL_IP>:8080in the browser.
For more information Refer to this Lab on how to Deploy ASP.NET Core app on Kubernetes.


text:
Q: Is there any offline javascript API document tool available like YARD for ruby does? Mozilla online documentation are great, but sometimes I don't have the internet connection and  reference in the o'reilly javascript definitive guide is also great but lack of the handy searchable capability.
I just wonder if there anything for javascript like railsapi, or yard, or jQAPI

A: http://devdocs.io Searchable offline documentation for JavaScript, DOM Events, HTML, CSS

A: You can probably blame the lack of uniform documentation styles and the fact that there is no centrally approved Javascript "stdlib", but there seems to be no such off-line doc generators or generated documentation.
There is, strangely, a certain amount of documentation available as Windows help files (CHM):

*

*http://prototypejs.org/api,

*http://docs.jquery.com/Alternative_Resources,

*there are mootools CHM floating around the web as well.

A: Heronotes provides you many offline version of good api's documentation, including, HTML, CSS, jQuery, Ruby, Prototype etc...
All the best:)


text:
Q: JavaScript: Initializing inner variable after initializing object Update: rewriting question because original question had false assumptions (I was running code in a console that had already initialized the variables I thought were undefined).
This makes sense:
var obj = { 'whichScope': a };
obj.whichScope; //"ReferenceError: a is not defined"

But then how come this next example doesn't throw an error? And if the second line is getting run before the first line, why doesn't obj.whichScope resolve to "After"?
var obj = { 'whichScope': a };
var a = "After";
obj.whichScope; //"undefined"

If "var a" in the previous example runs before obj is initialized, does any part of 'a = "After";' also run before obj is initialized?
var a = "Before";
var obj = { 'whichScope': a };
a = "After";
obj.whichScope; //"Before"

If whichScope refers to a function that returns 'a' then it does resolve to "After" in the last example.

A: That is called variable hoisting.
References:

*

*https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var#var_hoisting

*http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

*http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
Variables (declared with var) and functions are hoisted to the top of their scope.
So technically, your script is like this:
var a;  // = undefined
var obj = { 'whichScope': a };
a = "After";

Although your first example doesn't do what you say. The value of obj.whichScope is undefined, as expected.
DEMO: http://jsfiddle.net/pRQwK/
As for your last statement, If whichScope refers to a function that returns 'a' then it does resolve to "After" in the second example. - that is because the value of a isn't captured (by a closure). When setting a property, its value is captured immediately (unrelated to a closure).


text:
Q: type out timer in Javascript Hi I have created the below time out function that runs either 2 seconds after the person  has finished typing or on pressing enter. It works as described but for some reason i get the function repeating. For instance if i type 5 letter and wait 5 2 seconds i get 5 alerts after two seconds. I want just to receive 1 alert. What do i need to change?
function doSearch()
  {

  //run js function half a second after typing has stopped
  var typingTimer;  //timer identifier
  var doneTypingInterval = 2000;

  $(document).keypress(function(e){
    $('#txtSearch').keypress(function(e){
        if(e.keyCode == 13)
        {
            clearTimeout(typingTimer);
            alert("pressesd");
        }
    });

    //on keyup, start the countdown
    $('#txtSearch').keyup(function(){
        clearTimeout(typingTimer);
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    });

    //user is "finished typing," do somethin
    function doneTyping()
    {
    alert("done");
    clearTimeout(typingTimer);
    }

}

Thank s in advance

A: you have several syntax errors in your script. Altered code:
var typingTimer;  //timer identifier

function doSearch()
  {

  //run js function half a second after typing has stopped
  var doneTypingInterval = 2000;

      //on keyup, start the countdown
   $('#txtSearch').keyup(function(e){
       if(e.keyCode == 13)
       {
           clearTimeout(typingTimer);
           alert("pressesd");
       }
       else
       {
           clearTimeout(typingTimer);
           typingTimer = setTimeout(doneTyping, doneTypingInterval);
       }
     });
   }

    //user is "finished typing," do somethin
    function doneTyping()
    {
    alert("done");
    clearTimeout(typingTimer);
    }

working fiddle here.
Edited the fiddle, now it really works :/

A: Do not use keyup event to clear the event, use keypress event instead.
var el = document.getElementById('input');
var timeOutId;

el.addEventListener('keypress', onKeyPress);

function onKeyPress(event){

    if(event.keyCode == 13){
        doStuff();
        return;
    }
    clearTimeout(timeOutId);
    timeOutId = setTimeout(doStuff, 2000);
}

function doStuff(){

    console.log('Doing Stuff');

}

Demo

A: Append the keypress event in document.ready
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script language="javascript">
    var typingTimer = null;  //timer identifier
    var doneTypingInterval = 2000;
    $(document).ready(function (e) {
        $('#txtSearch').keyup(function (e) {
            if (e.keyCode == 13) {
                doneTyping();
            }
            else {
                if (typingTimer != null)
                    clearTimeout(typingTimer);
                typingTimer = setTimeout(doneTyping, 5000);
            }
        });
    });

    //user is "finished typing," do something
    function doneTyping() {
        clearTimeout(typingTimer);
        alert("done");
    }

</script>


text:
Q: My jQuery Won't Work on my Webpage All of my HTML and CSS code works fine, and my script is properly linked (or so I assume), but I can't get the script to load or do any actions I've coded. Here's my HTML, CSS, and JS code:
HTML
<!DOCTYPE html>

    <title>Highlights</title>
    <link rel='stylesheet' type='text/css' href='testwebcss.css'/>

I'm highlighted!

Highlight me, too!

CSS
#title {
background-color: #C02942;
border-radius: 5px;
text-align: center;
font-family: Verdana, Arial, Sans-Serif;
color: #FFFFFF;
width: 200px;
height: 25px;
}

#text {
background-color: #0B486B;
border-radius: 5px;
text-align: center;
font-family: Vivaldi, Cursive;
color: #FFFFFF;
width: 200px;
height: 25px;
opacity: 0.5;
}

.highlighted {
-webkit-box-shadow: 0 0 8px #FFD700;
-moz-box-shadow: 0 0 8px #FFD700;
box-shadow: 0 0 8px #FFD700;
cursor:pointer;
}

JS
$(document).ready(function(){
$('#text').mouseenter(function(){
    $(this).fadeTo('fast', 1);
});

$('#text').mouseleave(function(){
    $(this).fadeTo('fast', 0.5);
});
});

So I don't understand why it's not working. As you can see, the script simply doubles the opacity when the mouse enters the perimeter of #text. So, why is nothing working. I got this from the console:

Uncaught ReferenceError: $ is not defined

A: Add this to the HTML head (before you include your script):

A: You have to add more jQuery
<!DOCTYPE html>

        <title>Highlights</title>
        <link rel='stylesheet' type='text/css' href='testwebcss.css'/>

I'm highlighted!

Highlight me, too!


text:
Q: retrieve randomly generated variable in a postman collection I created a collection that contains 2 requests:
The first query randomly generates an id each time it is executed in a Json object. Here's the response:

I have to get this id which is used in the 2nd request whose url has the following format:
my-test-environment/{{id}}
For this I created a variable in the collection by retrieving my id like this:

This works, but the problem is that if I replay the first query this id will be different and the second query will not return the expected status code.
How can I set this id correctly in my case ?
Thanks

A: You can just add this to the Tests script of the first request:
pm.collectionVariables.set('id', pm.response.json().id)

This will set a new id variable each time you hit send, this can be used in the next request.


text:
Q: DB query for x day that no data I have table contain multiple records for the name and DT, I need a query to check the Name don't have any new record in past 2 days based on the DT, how to create
Name     DT
ABC      2017-09-17 06:02:23.000
ACD      2017-09-15 06:02:23.000

A: Without knowing your table schema or sample data this is a wild guess at a query, but what you want should be doable with the GETDATE() function. If you want to use UTC time you can also use the GETUTCDATE() function.
Edit: Updated to include the ROW_NUMBER() function.
Edit 2: Replaced the GETDATE() where clause with a CTE to exclude names that have dt within the last 2 days.
WITH CTE AS (
SELECT
    name
FROM table
WHERE dt > GETDATE()-2
)

SELECT
    name,
    dt
FROM (
    SELECT
        name,
        dt,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY dt desc) AS rn
    FROM table
    LEFT JOIN CTE ON
        table.name = CTE.name
    WHERE CTE.name IS NULL
    ) tbl
WHERE rn = 1

A: I think You need something like this:
SELECT Name,dt
from
(SELECT Name,MAX(dt) dt
FROM your_table
GROUP BY NAME) a
where dt < GETDATE()-2

A: BEGIN TRAN

CREATE TABLE #CM (Name  NVARCHAR(06), DT DATETIME)

INSERT INTO #CM
SELECT  'ABC','2017-09-17 06:02:23.000' UNION ALL
SELECT  'ACD','2017-09-15 06:02:23.000'

SELECT * FROM #CM
WHERE CONVERT(NVARCHAR(105),dt) < CONVERT(NVARCHAR(105),GETDATE()-2)

ROLLBACK TRAN


text:
Q: Cannot call value of non-function type 'HTTPURLResponse?' I'm trying to make Alamofire request by using this code block
    request = Alamofire.request(imageURL, method: .get)
                        .validate(contentType: ["image/*"])
                        .response(completionHandler:

{ (request: URLRequest?, response: HTTPURLResponse?, data: NSData?, error: NSError?) -> Void in

but I'm getting the title of this question as a run time error.
How can I overcome this issue?
Thanks in advance...

A: Instead of using response,data,error independently alamofire provides data which involve all of these parameters
Solution:
Alamofire.request(imageURL)
         .validate(contentType: ["image/*"])
         .response { data in

we can access error on data : data.error or response by data.response


text:
Q: Query to find the subtract of each column from the following column Hi everyone hope you are doing well
   I have a table with this structure
   Table 1:
 [dbo].[ValueTest] (Date , PorojectCode , Value)

It has this data
('1397/04/01' , 'A' , 100) , ('1397/04/03' , 'A' , 120) , ('1397/04/05' ,'A',140)

I need to have the result below :
 ProjectCode    Value
-------------   -------
    A              20
    A              20

I Mean I need to have the subtract of the value of each column from the following column
I have tried this query but I did not get the result

Thanks for helping me
Select ProjectCode ,
       (Select v.Value - v2.Value
        From [dbo].[ValueTest] V2
        Where v2.DateKey >= V.DateKey)
from [dbo].[ValueTest] V

A: You could use LAG() to subtract the value from the previous value, ordered by DateKey.
SELECT ProjectCode, (V.value - LAG(v.value) over (order by Datekey)) as val
from [dbo].[ValueTest] V;

But this will give you an extra NULL for the first value since we are doing 100 - NULL (Non existing row since the row with val 100 is the first one).
One way around this is by removing the NULL with a CTE
;WITH CTE
AS
(
SELECT ProjectCode, (V.value - LAG(v.value) over (order by Datekey)) as val
from [dbo].[ValueTest] V
)

SELECT * FROM CTE
where val IS NOT NULL;

Result
ProjectCode val
A   20
A   20


text:
Q: get back a variable from ajax to view i am new to php,jquery and to programming itself.I have a model called Appoinments .I am calling an ajax query from a text field to a controller action 'appoinments/loaddates'.The  ajax query executed correctly. But from the ajax action i want to get some array of variables to the view.Can somebody help me please how to do it?
my view
            echo CHtml::activehiddenField($model,'doctor',array(
           'onchange'=>CHtml::ajax(array(
                'type'=>'POST',

                'url'=> CController::createUrl('loadDates'),
                'update'=>'#nick_result',

                'dataType'=>'json' ,

                'select'=>"js:function(event, ui) {
                   $('#nick_result').val(ui.item.x);

                                    }"
            ))
           ));

             <div id="nick_result">

             </div>

my controller
             $arr[] = array(
               'x'=>$x, //this I need in view
               'y'=>$y,
               'z'=>$z,
               'p'=>$q,
               );

       echo CJSON::encode($arr);

how to get the $x value as a variable in php as it is used by the datepicker in my form. Any help appreciated.One thing to notice is that I just need a variable to get updated, not a model attribute. I just want to get that outside of the javascript. Thanks in advance.

A: To achieve this you need to use ajax callback in your view. For example:
echo CHtml::activehiddenField($model, 'doctor', array(
              'onchange'=>CHtml::ajax(array(
                'type'=>'POST',
                'url'=> CController::createUrl('loadDates'),
                'update'=>'#nick_result',
                'dataType'=>'json',
                'select'=>"js:function(event, ui) { $('#nick_result').val(ui.item.x); }"
                'success'=>'js:function(data){
                    //do here what you want to do. Your json encoded array will be passed as data
                }'
              ))
            ));

I recommend to use firebug for this, in console you can see what you send to ajax action in your post/get and your ajax callback (data).


text:
Q: Lib Files and Defines I'm using a couple of external libraries and I'd rather not have to include all their source and header files in my main source directory or in my project file. One option would be to compile the libraries as lib files and link them like that. However I'm not sure the defines get evaluated before or after the lib file gets created (which one is it?). If it's before then obviously I can't just pack them because they might not work properly on different compilers or systems.
So if I can't pack the libraries as lib files, is there any way for me to link in the c or cpp source files? Probably not, since they would have to be compiled first, but maybe I'm wrong.
Edit: Here's a follow-up question, based on answers. Do you think it'd be too much of a hassle to have a makefile that creates the lib files? I'd still rather not add the sources to my project or in my source directory.

A: Library is a binary file, so all defines obviously already in.
Just to make order, defines are evaluated as 1st stage of compilation process - the step is called preprocess. At this stage, for each cpp files created one file containing all #include'ed in it files recursively and all macros are evaluated.
Any way 3rd party should not depend on your compilation flags with one exception - release/build lib. Only in this case you need 2 versions of 3rd lib.
As regarding to question if to compile 3rd party libs once or each time while compiling your code it depends. If you are doing it only for itself than do what looks an easies way for you, but if we're talking about development team and the project to be maintain for a long time, than more things are to be considered.
SO we're talking about some solid solution for a team and we want to compile library several times.
In this case I personally strive to compile 3rd part library once and use it many times. This reduces compilation times for each build for each developers, which means faster development.
Nice, but where you hold these libs. I like phisycal separation - 3rd party library and my code not in same tree. This can avoid some not intentional errors. A good build system, and most of time it's mandatory, should be re-buildable. This means that if you checkout your code after year, you can compile and receive exactly same binaries.
Once I used some external read only tree on my machine. This tree was managed only by me.
To make my sources re-buildable, each next version of 3rd party library put in direcoty containing it's version and my source tree was updated to point to this point. If you build on several machines, than the read only tree should be visible on all these machines.
Additioanal solution is to check if your SCM tool (I suppose you use one) gives you some  ability to combine several sub-tries from repository in one checkhout. For each 3rd party library there's one sub-tree. This way 3rd party libraries are available on all machines your build. I currenly use these method on subversion - it's called svn:external. On CVS AFAIK it's called cvs modules. Additional advantage that the libraries are managed by source control system, so you can track all changes done to 3rd party libs.

A: defines get evaluated even before compiling. They are dealt with by the pre-processor, that prepares the code for the compiler to use. So yes, they are evaluated before the libraries are created.
You can't link against source code. You can only link with object files, static libraries, or dynamic libraries (shared object files/DLLs).
Using dynamic linking can be a good option, especially if the externals are large and/or you'll be using them in many executables.


text:
Q: C# WinForms - Code works before array, but when placed after array it fails I'm trying to append a piece of text to a RichTextBox, using the following code
Form2.codeOutput.Text += "test";
This works fine when placed before my array (like this):
public static void newString(string curLine)
        {
            Form2.codeOutput.Text += "test";

            string[] parsedString = new string[3];
            parsedString[0] = "string";
            parsedString[1] = curLine.Substring(7, 12);
            parsedString[2] = curLine.Substring(23, curLine.Length);
        }

However, when I place it after my array, it doesn't work:
public static void newString(string curLine)
        {
            string[] parsedString = new string[3];
            parsedString[0] = "string";
            parsedString[1] = curLine.Substring(7, 12);
            parsedString[2] = curLine.Substring(23, curLine.Length);

            Form2.codeOutput.Text += "test";
        }

I tried searching for solutions but I didn't get any good results; any help would be appreciated.
Edit 1: I should add that when the code doesn't work, it doesn't give an error or crash or anything; the text simply doesn't appear in the richtextbox.
Edit 2: I tried the same except I replaced the Form2.codeOutput.Text += "test"; with Debug.WriteLine("test");, same issue; the code works when placed before the arrays but not after.

A: Try this
public static void Main()
{
    string value="abcdefghijklmnopqrstuvwxyz1234567890";
    newString(value);
}

public static void newString(string curLine)
{
     string[] parsedString = new string[3];
     parsedString[0] = "string";
     parsedString[1] = curLine.Substring(7, 12);
     Console.WriteLine(parsedString[1]);
     parsedString[2] = curLine.Substring(23); // Changes here
     Console.WriteLine(parsedString[2]);

     Console.WriteLine("Done");
     //Form2.codeOutput.Text += "test";
}

Check the values in the array.
This method can arise ArgumentOutOfRangeException in two conditions:
if the parameters startIndex or length is less than zero.
If startIndex + length indicates a position which is not within current instance.

A: What is value of "curLine" you pass into method?
If startIndex is less than zero or greater than the length of this instance, Substring will throw ArgumentOutOfRangeException

A: Ok that's fun. Easy peezy. First things first: always start with the docs!!
Secondly, Substring's second paramter is the length of the requested substring, not the last index desired. Do curLine.Substring(23, curLine.Length - 23); and you should be good. Right now you're telling substring to start at index 23 and give you the next curLine.length characters. Obviously that fails because it's not 23 + curLine.length  characters long.
From the docs @ https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=net-5.0#System_String_Substring_System_Int32_System_Int32_
Substring(Int32, Int32)
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

public string Substring (int startIndex, int length);

Parameters:
startIndex
Int32
The zero-based starting character position of a substring in this instance.

length
Int32
The number of characters in the substring.


text:
Q: Trying to create a histogram with ZedGraph I am trying to create a histogram with ZedGraph.
The bars and data are all good, the only thing needed is my bars to be between the tics instead of directly on the tics.
Sample data:
1, 4
2, 8
3, 1

Means that I have:
4 items that are >= 0 and < 1
8 items that are >= 1 and < 2
1 item that is >= 2 and < 3

So currently my bars are of course appearing directly on the tics (x values) 1, 2 and 3.
But I would like to see:

*

*the first bar between the tics 0 and 1,

*the second bar between the tics 1 and 2 and

*the third bar between the tics 2 and 3

What is the property to tweak in order to achieve that?
I am currently looking in XAxis and XAxis.Scale, but I haven't found anything yet...

A: You probably can't do it with normal BarItem. I use the BoxObj objects to create the histogram.
If histList is the PointPairList containing your pairs of histogram values (breakpoint and value) you can use:
for (int i = 0; i < histList.Count - 1; i++)
{
BoxObj box = new BoxObj(histList[i].X, histList[i].Y, histList[i + 1].X - histList[i].X, histList[i].Y);
box.IsClippedToChartRect = true;
box.Fill.Color = myColor;
pane.GraphObjList.Add(box);
}

Using the BoxObj you have full control on where the bar is located etc. More info in documentation
EDIT
Remember that when using BoxObj (or any GraphObj in general) the X and Y scales are not going to be set automatically. You need to set the scale ranges manually:
pane.XAxis.Scale.Min = ...
pane.XAxis.Scale.Max = ...
pane.YAxis.Scale.Min = ...
pane.YAxis.Scale.Max = ...


text:
Q: how to change `ari-label` description dynamically with javascript how to change the value of 'ARIA-LABEL` according to user's precise language
getLang(element): void {
  let lang = element.document.getElementsByTagName('html')[0].getAttribute('lang');

  const labelAria = element.document.querySelector('[aria-label]');

  if(lang === 'en'){
   ?????
  }

}

Seeem give me some guidance I will be very grateful

A: I'm not sure what you mean by element.document but here is the correct way:
const labelAria = document.getElementById('element-id');

// set attribute
if(lang === 'en'){
   labelAria.setAttribute('aria-label', 'description here');
}

But if you really want to get the element by its aria label:
const labelAria = document.querySelector('div[aria-label="description here"]');

// set attribute
if(lang === 'en'){
   labelAria.setAttribute('aria-label', 'description here');
}


text:
Q: 5-digit-year in date export (52164-01-19 00:00:00+00) I received a data export from an unspecified source system, which includes dates in the format of:

*

*52164-01-19 00:00:00+00

*52992-08-12 04:29:36+00

*52838-10-19 04:08:32.999936+00

*54022-03-12 17:20:36.999936+00

I was told that the error is caused by a faulty conversion of unix to datetime (seconds and milliseconds).
We came up with a possible approach to refactor the date in python, by separating the year into a "normal" year (2164) and convert the rest into milliseconds.
import time
import math

d0 = '52164-01-19 00:00:00+00'
d0_y = 52164
multiplier = 5

# avg gregorian year in seconds
avg_greg = (365.2425 * 24 * 3600)

d1_modulus = 52164 % (1000 * multiplier)
d1_rest = d0_y - d1_modulus

# replace orginal year with modulus
d1_time = time.strptime(str(d1_modulus) + '-10-19 04:08:32', '%Y-%m-%d %H:%M:%S')

#convert to milliseconds and add d1_rest in "seconds"
bigtime = time.mktime(d1_time) + (avg_greg * d1_rest) #in milliseconds
biggertime = bigtime / 1000 # in seconds
finaltime = time.ctime(biggertime)
# finaltime = 'Thu Mar 12 07:34:41 2020'
print(finaltime)

This code can break for different dates and result in multiplier/modulus combinations to create out of range values for time.mktime.
Can someone suggest an alternative or better approach to this?
Thanks in advance
Gabe

A: Python datetime only supports between years 1 and 9999.
So I installed astropy and it works fine :
import datetime
import re

import astropy.time as astropy_time  # installed with PIP

faulty_data = "52164-01-19 00:00:00+00"
timeformat = re.compile(r"(?P<year>\d{5})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<sign_tz>[+\- ])(?P<hour_tz>\d{2})")

match = timeformat.fullmatch(faulty_data)
assert match
assert len(match.group("year")) == 5
assert match.group("hour_tz") == "00"
missing_thousand_years = int(match.group("year")[0])

time = astropy_time.Time({"year": int(match.group("year")),
                          "month": int(match.group("month")),
                          "day": int(match.group("day")),
                          "hour": int(match.group("hour")),
                          "minute": int(match.group("minute")),
                          "second": int(match.group("second"))
                          },
                         scale="utc")
print(time)
milliseconds = time.unix
print(milliseconds)
actual_datetime = datetime.datetime.fromtimestamp(milliseconds / 1000)
print(actual_datetime)

(52164, 1, 19, 0, 0, 0.)
1583971200000.0
2020-03-12 01:00:00

So it seems that the original date was 2020-03-12 01:00:00, which is close to what you got with your method.
NB: it raises two warnings, that you can silence


text:
Q: 8086 ASM: Reading constants from input file in DosBox I have declared constants above the program, like
cal          equ    16
length       equ    1000

And my question is: can I declare constants in my .txt files like this:
cal,cal,cal

To read from the file I use
mov bx, ax       ;file handler
mov ah, 3fh      ;interrupt number
mov cx, length
mov dx, offset music
int 21h

and I have declared in data segment
db  tab length dup (0)

Everything works properly while reading, but we need to read constants and not the ASCII number of characters. For example, if I have:
cal

It reads :
tab[0]= ascii of c
tab[1]= ascii of a etc

but I need
tab[0]= 16

Is that possible in DosBox with ASM?
Sorry for my english and thank You in advance ;).

A: It seems you are confusing a lot of things. The constants you defined above are translated from text strings via EQU to integer values at assembly time(when you assemble the program). The strings you are trying to read from your text file are not integer values - they are still just text (without any mapping to the integer values you want).
Reconstructing this mapping from the binary file would be highly complicated if even possible.
I doubt that this is even possible - unless by creating a separate dictionary before assembling - because the text->value relation between cal and 16 is used by the PreProcessor for text replacement before assembling and not even the assembler knows of it. Therefore it won't be present in the Debug-info(like a .PDB-file or so) also.
Even if the Debug-info would be included in the binary file or delivered with it, it would be quite complicated to reconstruct such a relationship from it.

So, the short answer is:
You have to create a Dictionary or some other mapping from cal(string) to 16(int) by yourself to parse the .txt files and get your desired values.


text:
Q: ayuda con array en php tengo esto
 <?php
 session_start();

 if(isset($_GET['p'])){
  $_SESSION['producto'][$_SESSION['contador']] = $_GET['p'];
 $_SESSION['contador']++;
 }

if (isset($_GET['c'])){
$_SESSION['cantidad'][$_SESSION['contador']] = $_GET['c'];

}

for ($i=0; $i < $_SESSION['contador']; $i++){
    $query = mysqli_query($conect,'SELECT * FROM Productos WHERE
   id='.$_SESSION['producto'][$i].'');

    while ($fila = mysqli_fetch_array($query)) {

        $cab = $_SESSION['cantidad'][$i+1];

        $total = $fila['Precio']*$cab;

            echo '
';
            echo ''.$fila['Nombre'].'	';
            echo '';
            echo '<input type=number name=ja class="la"
          value='.$cab.'>';
            echo '	';

            echo ''.number_format($total,2).'	';
            echo '';

el problema resulta que cuando ingreso en el input numeric me pasa unos datos con el valor y otros vacios en especial el 1 2 vienen con el valor y el 3 sale sin ningun valor y asi al 7 igual nose que pasa


text:
Q: What do unfiltered_html and unfiltered_upload actually filter? Among WordPress' capabilities are unfiltered_html and unfiltered_upload, however I have yet to find any documentation about what specifically they allow or prevent in their filtering.
The only mention I've found on WordPress' site about unfiltered_html is:

Allows user to post HTML markup or even JavaScript code in pages,
  posts, comments and widgets.

I've seen that JavaScript is filtered out for non-admins, but what HTML is being filtered?
And for unfiltered_upload:

This capability is not available to any role by default (including
  Super Admins). The capability needs to be enabled by defining the
  following constant:
define( 'ALLOW_UNFILTERED_UPLOADS', true );

With this constant defined, all roles on a single site install can be
  given the unfiltered_upload capability, but only Super Admins can be
  given the capability on a Multisite install.

And again, the description doesn't spell out what's permitted and what's filtered out.
Can someone tell me exactly what elements, code, or file types the unfiltered_html and unfiltered_upload capabilities allow or prevent?

A: It is hard to come up with precise answer since capabilities are often used more broadly than they imply. For example check for manage_options is usually synonym to check for admin user and can come up in contexts that don't actually have much to do with options.
Usually it will be a difference between subject content passing or not passing through wp_kses(). Specific kses settings and what is considered allowed would depend on the context and might wary.
For unfiltered_upload as far as I remember it's more straightforward. Without it only white listed file types are allowed. The list is based on wp_get_mime_types().

A: I appreciate this is an old thread, but restricted unfiltered_html was causing us huge problems on our news site.
The in-house writers (a special class of user) are required to place photos and videos in their story. While photos are not a problem, embedding iframe's into the page with the video code embedded saw the embedded code vanish when they saved their stories.
If the video was embedded for them by an editor the writers would still lose the iframe when they saved their stories.
By unblocking unfiltered_html our staff writers can embed the video content and lay up their post properly.
As for unfiltered_uploads, I belie that has been answered.
Hope this helps someone.

A: unfiltered_html in network
These capabilities block the possibility for all users except super admins to insert JavaScript iframe code etc. in WordPress pages or posts and if one of them(admin, editor ECC) edits a page with an active iframe or JS it is removed.
To give administrators the possibility to add such codes, these abilities must be enabled and to do so you can use this plugin
https://wordpress.org/plugins/unfiltered-mu/


text:
Q: eslint - async arrow function return value error Currently experiencing a little bit of an annoyance rather than a problem. I have the following function:
export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => {
  const token = getTokenCookie(req)

  if (!token) return

  const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
  const expiresAt = session.createdAt + session.maxAge * 1000

  // Validate the expiration date of the session
  if (Date.now() > expiresAt) {
    throw new Error('Session expired')
  }

  return session
}

and eslint(consistent-return) is telling me: Async arrow function expected no return value.
I thought, why not try it like this instead:
export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => {
  const token = getTokenCookie(req)

  if (token) {
    const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
    const expiresAt = session.createdAt + session.maxAge * 1000

    if (Date.now() > expiresAt) {
    throw new Error('Session expired')
    }

    return session
  }
}

but then I am getting eslint's: Expected to return a value at the end of async arrow function.
A fix is to return to the first iteration and return false from if (!token) return false which fixes the problem.
My question is

*

*is that the best way to handle it when we usually wouldn't explicitly return false?

*I am new to Typescript, is a return type of Promise<undefined | User> appropriate?

type User contains id: string, username: string, etc...

A: Answering your question, yes there is a better way. You should always reject the promise if the result of the promise is not of the type you expect it to be. Returning undefined will still have the caller of that promise handle this case and it becomes a bit confusing in my experience.
I would change it for something like this:
export const getLoginSession = async (req: NextApiRequest): Promise<User> => { // <-- this promise will return a user or throw
  const token = getTokenCookie(req)

  if (!token) {
    throw new Error('invalid token') // <-- unexpected we should throw
  }

  const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
  const expiresAt = session.createdAt + session.maxAge * 1000

  // Validate the expiration date of the session
  if (Date.now() > expiresAt) {
    throw new Error('Session expired')
  }

  return session
}

This way we have a better control flow and it's easy to reason about.
try {
  const session = await getLoginSession(req)
  // do something with the session
} catch (error) {
  // handle the error
  console.log(error)
}

About the consistent return, it's because you didn't defined a value after the return. So return false works but return undefined or return void 0 will also work.
From the docs:

require return statements to either always or never specify values

ref: consistent-return

A: In the below code, session is not existing when you are returning, const/let values are block-scoped hence session scope only exists inside that if block not outside of it. You need to either. return inside from if block and return error promise or just do the fallback when token is getting falsy and if not then return the session
if (token) {
    const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
    const expiresAt = session.createdAt + session.maxAge * 1000

    if (Date.now() > expiresAt) {
    throw new Error('Session expired')
    }

    return session
  }


text:
Q: POST jersey with HeaderParam annotation I get null when I send a POST. Please someone know how to pass value with Angular using @HeaderParam in Jersey?
I have this in backend:
 @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Users loginUser(@HeaderParam("username")String username,@HeaderParam("password") String password){
        System.out.println("What happen"+userService.loginService(username, password));
       return userService.loginService(username, password);
    }

and this in front-end, using Angular:
 $scope.getUserFunction = function () {
      $http({
        method  : 'POST',
        url     : 'http://localhost:8080/JersyBackEnd/resources/login'+data,
        contentType:'application/json',
        data    : {username: "akram",password:"yes"},
      })
        .then(function(data) {
          console.log(data);
        });
    };

I get 204 because of the null data.
Can anyone help me, either using HeaderParam, PathParam or FormParm annotations in Jersey?

A: data is sent as the request body. What you really want is headers.
From the docs:

*

*data – {string|Object} – Data to be sent as the request message data.

*headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.

Example:
$http({
  ...
  headers: {
    username: "akram",
    password: "yes"
  }
})

A: When you use @HeaderParam, you have to pass the values from .JS using  headers: { 'something': 'anything' }. As i can see currently you are using data    : {username: "akram",password:"yes"}. try to use headers: { 'something': 'anything' } instead of this.
Please try header, hope it will solve your null issue.