text:
Q: FirebaseStorage.getInstance(String url) .. what is this url? While trying to access the Firebase Storage, the app crashes. I am calling another java class file which have all the methods and the declarations of FirebaseStorage. Whenever I am trying to access this class file, I get an error at FirebaseStorage.getInstance() method.
I was wondering if there was another method to explicitly mention the url to access the storage bucket directly instead of accessing the application's context.
PS: I am opening this class from a fragment, which might be the reason for the crash.
Any thoughts ?
Thanks :)
UploadImage.java
public class UploadImage extends MainActivity{

private String path;
private StorageReference storageReference;

public UploadImage(String path){
    this.path = path;
    this.storageReference = FirebaseStorage.getInstance("gs://databasereal-bb774.appspot.com").getReference();
}

public void upload(){
    Uri file = Uri.fromFile(new File(path));
    StorageReference imageRef = storageReference.child("ParamedicImages");

    imageRef.putFile(file)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    Log.d("Uupload","Uploaded");

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e("failed upload", exception.toString());
                }
            });
}

}
Exception
10-17 10:50:19.623 23807-23807/com.example.emil.integrated E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.emil.integrated, PID: 23807
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzbq;
    at com.google.firebase.storage.FirebaseStorage.getInstance(Unknown Source:11)
    at com.example.emil.integrated.MainActivity.onCreate(MainActivity.java:52)
    at android.app.Activity.performCreate(Activity.java:7084)
    at android.app.Activity.performCreate(Activity.java:7075)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2765)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2890)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1611)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:171)
    at android.app.ActivityThread.main(ActivityThread.java:6633)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbq" on path: DexPathList[[zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/base.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_resources_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/lib/arm64, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.google.firebase.storage.FirebaseStorage.getInstance(Unknown Source:11)
    at com.example.emil.integrated.MainActivity.onCreate(MainActivity.java:52)
    at android.app.Activity.performCreate(Activity.java:7084)
    at android.app.Activity.performCreate(Activity.java:7075)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2765)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2890)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1611)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:171)
    at android.app.ActivityThread.main(ActivityThread.java:6633)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
    Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.emil.integrated-uhFwZ_bugwGNWNgjr6d59A==/split_lib_resources_apk.apk
    at dalvik.system.DexFile.openDexFileNative(Native Method)
    at dalvik.system.DexFile.openDexFile(DexFile.java:353)
    at dalvik.system.DexFile.<init>(DexFile.java:100)
    at dalvik.system.DexFile.<init>(DexFile.java:74)
    at dalvik.system.DexPathList.loadDexFile(DexPathList.java:374)
    at dalvik.system.DexPathList.makeDexElements(DexPathList.java:337)
    at dalvik.system.DexPathList.<init>(DexPathList.java:157)
    at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
    at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
    at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
    at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
    at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:69)
    at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:35)
    at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:695)
    at android.app.LoadedApk.getClassLoader(LoadedApk.java:729)
    at android.app.LoadedApk.getResources(LoadedApk.java:956)
    at android.app.ContextImpl.createAppContext(ContextImpl.java:2282)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5714)
    at android.app.ActivityThread.-wrap1(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1680)
            ... 6 more

build.gradle (app module)
apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.example.emil.integrated"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-firestore:17.1.1'
implementation 'com.google.firebase:firebase-auth:16.0.4'
implementation 'com.google.firebase:firebase-core:16.0.4'

implementation 'com.mindorks:placeholderview:0.2.7'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:27.0.0'
implementation 'id.zelory:compressor:2.1.0'
implementation 'pub.devrel:easypermissions:0.2.1'
implementation 'com.google.firebase:firebase-storage:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

build.gradle (project module)
apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.example.emil.integrated"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner     "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),     'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-firestore:17.1.1'
implementation 'com.google.firebase:firebase-auth:16.0.4'
implementation 'com.google.firebase:firebase-core:16.0.4'

implementation 'com.mindorks:placeholderview:0.2.7'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:27.0.0'
implementation 'id.zelory:compressor:2.1.0'
implementation 'pub.devrel:easypermissions:0.2.1'
implementation 'com.google.firebase:firebase-storage:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

A:
FirebaseStorage.getInstance(String url) .. what is this url?

You need to pass URL of your Firebase Storage Bucket in FirebaseStorage.getInstance() method
From Docs
FirebaseStorage getInstance (String url)

*

*it Returns the FirebaseStorage, initialized with the default FirebaseApp and a custom Storage Bucket.

Parameters

*

*url    The gs:// url to your Firebase Storage Bucket.

EDIT
You need to update your firebase-storage dependencies
implementation 'com.google.firebase:firebase-storage:16.0.3'


text:
Q: GCC compiler warning: format '%c' expects argument of type 'char *', but argument 2 has type 'int *' [-Wformat] I get the following warning when I try to compile the code:
exercise6.c:32:14: warning: format '%c' expects argument of type 'char *', but argument 2 has type 'int *' [-Wformat]
What is causing this warning and how do I fix it?
/*Write a program that displays the contents of a file at the terminal 20 lines at
a time. At the end of each 20 lines, have the program wait for a character to be
entered from the terminal. If the character is the letter q, the program should
stop the display of the file; any other character should cause the next 20 lines
from the file to be displayed.*/

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int c, i;
    FILE *file;

    if ( (file = fopen ("text", "r")) == NULL )
    printf ("Error opening the file.\n");

    for ( i = 0; i < 20; ) {
        c = getc (file);

        if ( c == EOF ) {
            fclose (file);
            exit (EXIT_SUCCESS);
        }

        putc (c, stdout);

        if ( c == '\n' )
            ++i;

        if ( i == 20 ) {
            scanf ("%c", &c);
            if ( c == 'q' ) {
                fclose (file);
                exit (EXIT_SUCCESS);
            }
            i = 0;
        }
    }
}

A: Define a char ch and use that in scanf.
int c, i;
char ch;

/* ... */
scanf ("%c", &ch);

Using mismatched arguments for scanf is technically undefined behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get count of number of opened windows in WPF I have a requirement that, if one window is opened then user can not allow to open other window, for that I have tried following code.
if(System.Windows.Application.Current.Windows.Count == 0)
 {
 //My code
 }

I am checking for currently opened window count, if it is greater then 1 then user can not open other window and that I will mention inside if statement,
but when I run this code it gives me the error

"Object reference not set to an instance of an object."

Any Solution

A: You would be probably getting this error because, even for the first windows to be loaded, you would be applying this check. For this you can apply null check in your code.
and for list of loaded windows, you can get it using Application,
var loadedWindows = Application.Current.Windows.Cast<Window>()
                                               .Where(win => win.IsLoaded);

A: If you want to know how many windows are opened from your application instance, you can do this
 l_WindowCount = 0;

 foreach(var Window in App.Current.Windows)
 {
    l_WindowCount += 1
 }

if(l_WindowCount > 1)
{
//do what you want to do here
}


text:
Q: Answer Count not Appearing on Category Page I have noticed over quite some time that some questions appearing on the category page do not show any answer count to their left. When I click on the question and go to its page, I see a number of answers, some even with votes. The questions are sometimes half an hour before. What is the possible reason?
Edit
This is the screen shot of one such recent post. It does not show difference in answer count though it shows difference in votes.

And this is the shot of the original post.


text:
Q: DJI android sdk camera profile Does anyone know the profile of the RAW 264 format from the camera through the API? Is it main or is it possible to change to baseline profile in the code?

A: Which camera and drone are you using?
I don't believe there is a way to know and change the H.264 profile - if I hear something different I'll update this post.  But in general the video and storage settings can be played with here: method loadSettingsFromProfile
If this doesn't help, then email dev@dji.com describing in detail what you want to do (include which SDK you would like to use) and what DJI products you're using - we can look into making this a feature request.


text:
Q: No module name _tkinter error while tkinter is installed When trying to run my python 3 program that uses matplotlib via the command line, I get the following error:
import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

The same happens when simply inputting:
>>>import tkinter

Suggested fixes such as installing python3-tk, python3.5-tk or python3.6-tk do not work, the result is:
python3.6-tk is already the newest version (3.6.6-1+xenial1).

and using matplotlib.use('agg') does not work as I need to output figures:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

with pip install tkinter, python-tk or python3-tk the result is :
Could not find a version that satisfies the requirement python3-tk (from versions: )
No matching distribution found for python3-tk

I also tried updating and reinstalling python3 but nothing seems to work (version 3.6.4). Could it be that python-tk is version 3.6.6 and my python 3.6.4?
Is there any other method I can try?


text:
Q: GEMMLowP at lower bit depths Specifically in the context of Tensorflow's use of GEMMLOWP for quantized operations, I would like to run quantized operations at varying bit depths.
This readme  seems to have some useful information but I still don't quite understand how to use it or what the impact will be - when it says the final data type is still a uint8, but lower accuracy, does this just mean that for example 7 bit arithmetic will return values from 0 to 127 despite being stored in a uint8 variable? Not sure if I'm interpreting that right.
Tensorflow seems to make use of GemmLowP's MultiThreadGemm function - this can be found in /tensorflow/core/kernels/meta_support.cc.
The MultiThreadGemm function takes in one Params structure; I can't see how to integrate the BitDepthParams which as far as I can see sets the precision into the Params structure in order to adjust Tensorflow's use of MultiThreadGemm for arbitrary bit depths.
Any insight/suggestions would be useful!

A:
when it says the final data type is still a uint8, but lower accuracy, does this just mean that for example 7 bit arithmetic will return values from 0 to 127 despite being stored in a uint8 variable?

Yes, it says that less than 8bit values are just stored as full 8bit bytes (in uint8_t; it will have too high cost to unpack array of real 4-bit or 6-bit values into something compatible with vector ALU/AVX/GPU operations). More it says that input was (for the "present" before feb 2017) still full range 8-bit ints:
https://github.com/google/gemmlowp/blob/master/doc/less-than-8-bit.md#how-does-bitdepthsettingparams-affect-inputoutput-uint8-matrix-data

Input/output matrix data is all uint8's, ranging from 0 to 255, regardless of the BitDepth{Setting,Params}.

Internally gemmlowp did repack input data into uint8_t storage with narrower range at packing stage (internally to gemmlowp, just before doing actual gemm matrix multipy, check general pseudocode of gemm in design.md - impact of low precision, note pack and unpack):
https://github.com/google/gemmlowp/blob/master/doc/less-than-8-bit.md#packing-stage

Here, we have to scale input matrix values from their original range of [0 ... 255] to the range specified by the BitDepthParams, which is [0 ... (2^N)-1] where N is the number of bits for the matrix at hand (Lhs or Rhs). For example, for a bit depth of 5 bits, we need to scale down to [0 ... 31].

https://github.com/google/gemmlowp/blob/master/doc/design.md#impact-of-low-precision-computation-on-gemmlowp-design

Inputs and outputs are matrices of uint8 values, but internally we are accumulating int32 values, only converting them back to uint8 at the end.

There were huge changes in February 2017 in handling of less than 8 bit.
BitDepthParams probably were integrated into the library in past, but the commit from Feb 2017 adds "This 'present' state just became the past (February 2017)." to the less-than-8-bit.md documentation and also removes usage of BitDepthParams in real code. Probably now input whould be not in full 8-bit range. Didn't find the place of kernel selection...
https://github.com/google/gemmlowp/commit/4746387c02f2b9542fe5d4a6ac4bb4d81f88ef15#diff-69cce824f316d701d9c3c23afcb00694 "Remove the old requantizing less-than-8-bit stuff."

Remove the old requantizing less-than-8-bit stuff. Map the
  DefaultL7R5BitDepthParams setting to DefaultL8R8BitDepthParams so that
  this change does not break any user relying on it, since the whole
  point of requantization was to make this an implementation detail.
Instead, from now on, using actual less-than-8-bit settings will only
  have the effect of selecting a different GEMM kernel. In other words,
  it is now the responsibility of the user to know the actual bit-depth
  (i.e. range) of their 8bit values. In exchange for that
  responsibility, users of lower-than-8-bit depths will enjoy the
  increased performance of corresponding kernels without the overhead of
  requantization.
-        PackLhs<BitDepthParams>(&packed_lhs, lhs.block(r, 0, rs, depth));
+        PackLhs(&packed_lhs, lhs.block(r, 0, rs, depth));
-        UnpackResult<BitDepthParams>(&result, curr_result_block, packed_result,
+        UnpackResult(&result, curr_result_block, packed_result,
-    PackRhs<BitDepthParams>(&packed_rhs, rhs.block(0, c, depth, cs));
+    PackRhs(&packed_rhs, rhs.block(0, c, depth, cs)); internal/pack.h:
-std::uint8_t Requantize(


text:
Q: Pentaho Report Use parameter in host name in JDBC Data Source I created a report shown in Pentaho Dashboard.
The Dashboard is implemented on many machines.
So, I must edit JDBC DataSouce in all SubReports in my report to match the hostname to introduce environment. (I am using MySQL)
Can I use a parameter in the hostname in DataSource ex. ${HostName}?
I tried to do that, but then the value wasn't shown in DataSet when I clicked DataSource and clicked SelectQuery.

A: I solved it myself.
I make report in Pentaho Report Designer with JNDI connection.
I published its report to my BI Server.
I edited these two files.
\biserver-ce\tomcat\conf\context.xml
\biserver-ce\tomcat\webapps\pentaho\WEB-INF\web.xml
Then the report showed data in datasource in context.xml.


text:
Q: ForYouFragment Fragment doesn't update Hi i have permission check on my forYou fragment when the app starts start and you give the permission and it makes a api call and get the weather for you current location the problem is I must switch the fragment for getting the call and switch again for showing it in the reclyerview the problem is when I give the permission for the location it doesn't do the api after that, I must refresh the fragment
    fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
        if (location != null) {
            currentLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            val currentAddress = getAddress(location.latitude, location.longitude)
            Log.d("TAG", "klagenfurt : ${currentAddress}")
            retrofitOneCallResponse(location.latitude, location.longitude, currentAddress)
            dataService.getFavorites(this)

        }

    }
    if (ActivityCompat.checkSelfPermission(
            requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(
            requireActivity(),
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
            MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE
        )

        return
    }

A: Create one method like this.
private fun getLocation(){
fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
        if (location != null) {
            currentLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            val currentAddress = getAddress(location.latitude, location.longitude)
            Log.d("TAG", "klagenfurt : ${currentAddress}")
            retrofitOneCallResponse(location.latitude, location.longitude, currentAddress)
            dataService.getFavorites(this)
        }else{
         getLocation()
        }
    }
}

then from here
if (ActivityCompat.checkSelfPermission(
            requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        requestPermissions(
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
            MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE
        )
    }else{
      getLocation()
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray): Unit {
      if(requestCode==MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE){
          if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
              getLocation();
          }
      }
}

Also, override the onRequestPermissionsResult in the fragment. and check if permission granted the call getLocation().

A: enter image description here
HERE it says and you write the code without ActivityCompat on the requestpermisson line it doesn't work etiher


text:
Q: Problem grub won't display on my tv at boot up When I start my computer it won't show my grub screen this box just appears saying something along the lines of "this tv cannot handle this resolution or refresh rate" but after a couple seconds it brings me to the log in screen. Any idea what exactly the problem is and how do I fix it? thanks!

A: You more then likely can not fix it.
TVs are notoriously bad for supporting PC resolutions, some only support 1 or two "main" resolutions and others support only their TV native resolution.
For example my TV only supports 1024x768 if you use the VGA cable, even though it's a 720p TV.
To correct this, you can force grub and Linux  VTYs to use a specific VGA mode that you know your TV will support.
Basically: (file names and locations might change, depends on config)
Edit /etc/default/grub

GRUB_CMDLINE_LINUX_DEFAULT="video=vesafb:mtrr:2"
  ....
  GRUB_GFXMODE=1024x768
  GRUB_GFXPAYLOAD_LINUX=KEEP

Then update grub and add the device to your initramfs
sudo update-grub2
echo FRAMEBUFFER=y | sudo tee /etc/initramfs-tools/conf.d/splash
sudo update-initramfs -u
More Information here


text:
Q: Redirect to action based on role not working. Maybe routing needed? I have the following controller
public class GlobalAdminController : Controller
{
    // GET: GlobalAdmin
    [AuthorizeUser(Roles = "admin")]
    public ActionResult Index()
    {
        return View();
    }
}

And the home controller which is the main landing page for the app
public ActionResult Index()
{
    if(User.IsInRole("admin"))
    {
        RedirectToAction("Index", "GlobalAdmin");
    }
    return View();
}

The redirect to action is executed in the debugger
However the index action itself is not being executed on the global admin
I wonder if there is a better way to do this? maybe throught routing?

A: You have to use return to provide the redirect informations (url) to the browser. And the browser will redirect to the new location.
public ActionResult Index()
{
    if(User.IsInRole("admin"))
    {
       return RedirectToAction("Index", "GlobalAdmin");
    }
    return View();
}

The point of the routes is to provide a way to access the actions from controller. Instead of accesing GlobalAdmin/Index you use the route to provide another way like admin/index
routes.MapRoute(
     name: "Default",
     url: "admin/{action}/{id}",
     defaults: new { controller = "GlobalAdmin", action = "Index", id = UrlParameter.Optional } );

routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );


text:
Q: Magento2 - Reuse gift-options.js in other JS file I want to reuse the functionality of module-gift-message/view/frontend/web/js/action/gift-options.js and use it in one of Module_Checkout JS file.
Ex: In update-shopping-cart.js.
How do I do this and how to use it?


text:
Q: Visual Studio 2022 can't add service reference and no assembly references node I have a VS2022 class library project that looks strange in a number of ways:

*

*Cannot add a service reference (see screenshot)

*There is no References node (for assembly references) - see screenshot

*The project properties UI looks very different

When I right-click on my class library project -> Add -> Service Reference, I'm taken to this screen that has only Connected Services and not Service References:

When I click "Add a service dependency", I'm presented with all these options that are not what I need:

I need to add a service reference like this (only exists in my Winforms project):

Notice 2 things in the screenshot below: (1) Dependencies instead of References?? Also, note that I have a reference to System.ServiceModel, so I see no reason why I cannot add a service reference.

This Project Properties UI looks very different:

Compare the above against my more traditional-looking Project Properties UI for a Winforms project in the same solution (we're still in VS2022):

What is going on? I can't add a Service Reference, I don't have a References node (it's a Dependencies node instead), and the project properties UI is quite different.

A: This looks like you've created a project based on the .NET SDK (not .NET Framework), and so VS offers a different experience for it - notably some features are new (like the look and functionality of the property pages) and some are missing (like support for .NET Framework specific tooling such as Service References).
When the project was created, it was probably created from the red template, but you're expecting the blue one:

The simplest solution is to stash your source files, create the project from scratch with the correct template, then retrieve your stashed files into the new project.


text:
Q: Save output of a php file to a two html pages I have a php script to calculate and display information about administrators and managers. The php file is status_report.php. I use param (called "type") to distinct two users. I am using this script.  It create a file for admins, but doesn't create a file for managers.
Please help me to get it works.
session_start();
ob_start();
$_GET['type'] ="admin";
include('status_report.php');
file_put_contents('reports/admins.html', ob_get_contents());
ob_end_clean();

// for manages
ob_start();
$_GET['type'] ="manager";
include('status_report.php');
file_put_contents('reports/managers.html', ob_get_contents());
ob_end_clean();

This is an extension of this question- Save output of a php file in a html file

A: create a method to enclose the repeating things
function f1($params){
    ob_start();
    $_GET['type'] =$params;
    $page = 'reports/'. $params  .'.html';
    include('status_report.php');
    file_put_contents($page, ob_get_contents());
    ob_end_clean();
}

then call it for number of times
f1("admin");
f1("managers");

....


text:
Q: How to control font size in png? I am trying to make figures for a manuscript, that should be written with MS Word, which does not accept figures in pdf format. The journal asks first draft with figures embedded in the Word file. These figures should have resolution minimum of 300 dpi and have a width of either 169 mm or 81 mm (two/one column). I notice that when I specify the resolution of the picture to 300 (res = 300), the font size is bound to this value. This works fine with some figures (the first example, example.png), and worse with others (example2.png). How can I control the font size so that the dimensions and resolution of the figure remain fixed?
library(ggplot2)
library(grid)

data(iris)

vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)

p <- ggplot(iris, aes(Species, Petal.Length))
q <- ggplot(iris, aes(Species, Petal.Width))
len <- p + geom_boxplot()
wid <- q + geom_boxplot()

png("example.png", width = 169, height = 100, units = "mm", res = 300)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(len, vp = vplayout(1, 1))
print(wid, vp = vplayout(1, 2))
dev.off()

png("example2.png", width = 81, height = 100, units = "mm", res = 300)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(len, vp = vplayout(1, 1))
print(wid, vp = vplayout(1, 2))
dev.off()

In other words, I would like to decrease the font size in example2.png, but keep the layout and dimensions of the two plots as they are.

Example.png

Example2.png

A: Using the base_size argument to the theme_XXX() function, you can change the overall font sizes for all the text.
png("example2.png", width = 81, height = 100, units = "mm", res = 300)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(len + theme_gray(base_size=12*(81/169)), vp = vplayout(1, 1))
print(wid + theme_gray(base_size=12*(81/169)), vp = vplayout(1, 2))
dev.off()

A: Simply change the pointsize attribute of png. For example:
png(filename="plot4.png", width=580, height=700, pointsize=20)

A: As far as I can tell the fontsize is the same regardless of the resolution and device size. You can check it in the following examples:
library(grid)

png("example1.png", width = 30, height = 5, units = "mm", res = 200)
g <- grid.text("testing font size", gp=gpar(fontsize=12))
width <- convertUnit(grobWidth(g), "mm")
height <- convertUnit(grobHeight(g), "mm", "y")
grid.rect(width=width, height=height, gp=gpar(lty=2, fill=NA))
dev.off()

png("example2.png", width = 60, height = 5, units = "mm", res = 500)
grid.text("testing font size", gp=gpar(fontsize=12))
grid.rect(width=width, height=height, gp=gpar(lty=2, fill=NA))
dev.off()

But it seems you actually wanted to change the font size.


text:
Q: Issue converting table from InnoDB to MyISAM (there can be only one auto column and it must be defined as a key) I'm having issues trying to convert a table from MyISAM to InnoDB in MySQL 5.6.
The following is the table dump:
--
-- Table structure for table `companies`
--

DROP TABLE IF EXISTS `companies`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `companies` (
  `uid` int(20) NOT NULL,
  `cid` int(20) NOT NULL AUTO_INCREMENT,
  `cname` varchar(500) NOT NULL,
  `rfc` varchar(20) NOT NULL,
  `address` varchar(1000) NOT NULL,
  `dbUseExternal` tinyint(1) NOT NULL DEFAULT '0',
  `dbHost` varchar(50) NOT NULL,
  `dbPort` varchar(50) NOT NULL,
  `dbUser` varchar(50) NOT NULL,
  `dbPass` varchar(50) NOT NULL,
  `dbSSL` varchar(50) NOT NULL,
  `dbDriver` varchar(50) NOT NULL,
  `dbName` varchar(50) NOT NULL,
  `status` int(10) NOT NULL,
  PRIMARY KEY (`uid`,`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

It works as MyISAM. But, if I try to convert it to InnoDB (or if I try editing this dump to insert it on the command line as a SQL file), I get the following error:

Incorrect table definition; there can be only one auto column and it must be defined as a key

I understand that error - or at least I thought I did. I'm not really using more than one AUTO_INCREMENT column and it is defined as primary key.
Also, the information I've found regarding the error is always because of an obvious missing key or a duplicate AUTO_INCREMENT definition. One more thing I see generally commented is that the same is true for MyISAM and InnoDB.
So, why does it work for MyISAM and not for InnoDB?

A: in InnoDB, auto_increment keys have to have to: either have their own index, or at least be the primary sub-index of a compound index. (a in KEY(a,b)).
Fix this by adding a KEY(cid) after your PRIMARY KEY, like so:
CREATE TABLE `companies2` (
  `uid` int(20) NOT NULL,
  `cid` int(20) NOT NULL AUTO_INCREMENT,
  `cname` varchar(500) NOT NULL,
  `rfc` varchar(20) NOT NULL,
  `address` varchar(1000) NOT NULL,
  `dbUseExternal` tinyint(1) NOT NULL DEFAULT '0',
  `dbHost` varchar(50) NOT NULL,
  `dbPort` varchar(50) NOT NULL,
  `dbUser` varchar(50) NOT NULL,
  `dbPass` varchar(50) NOT NULL,
  `dbSSL` varchar(50) NOT NULL,
  `dbDriver` varchar(50) NOT NULL,
  `dbName` varchar(50) NOT NULL,
  `status` int(10) NOT NULL,
  PRIMARY KEY (`uid`,`cid`),
  KEY(`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


text:
Q: iOS SimpleDB Select by date Good Day,
I am trying to select an item on SimpleDB using the iOS SDK. The issue is the only way I know how to do it is to use SimpleDBGetAttributesRequest to get the item name, then check the date attribute and see if it matches the one i requested.
This is definitely a horrible way to do it as I have to keep querying the entire database just for this. Is there an easy way to check the attributes rather than the name, or a way to select date?

A: I'm not an iOS SDK expert, but sounds like SimpleDBSelectRequest would work for you with a selectExpression like :
select * from your_domain where your_date = '1970-01-01'

if you know the date, or:
select * from your_domain where your_date between '1970-01-01' and '1970-01-05'

if you only know the date range.
Remember that SimpleDB treats dates like strings, so format your dates appropriately in your query to match the way you are storing them.
-Larry

A: I have written a simple piece of code as such with your above solution
-(void)RunQuery:(NSString*)query{
NSLog(@"Running Query\n");
NSString* selectExpression=query;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    @try {
        //Code start
        SimpleDBSelectRequest *selectRequest = [[SimpleDBSelectRequest alloc] initWithSelectExpression:selectExpression];
        selectRequest.consistentRead = YES;

        SimpleDBSelectResponse *selectResponse = [sdbClient select:selectRequest];

        for (SimpleDBItem *item in selectResponse.items) {
            NSLog(@"%@",item.name);
        }
        //Code end
    }
    @catch (AmazonServiceException *exception) {
        NSLog(@"Exception = %@", exception);
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    });
});
}


text:
Q: How to load txt file to UITextView with attributedString? I added a .txt file to bundle and this file consists of like five
paragraphs and each paragraphs has a title. I successfully load that .txt
file to a string variable and display the text in my UITextView. But i
want like each title have different font and each paragraph have
different font size. Please help me.
I am using the following code:
NSString *path = [[NSBundle mainBundle]pathForResource:@"License" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self.textView setText:content];

A: You can use NSAttributedString, Set Text Font, Foreground And Background Colors, StrikeThrough And Shadow etc..
Attributed strings make an association between characters and their attributes. Like NSString objects, there are two variations, NSAttributedString and NSMutableAttributedString. Although previous versions of iOS supported attributed strings, it wasn't until iOS 6 that controls such as buttons, labels, textfields and textviews defined a property to manage attributes. Attributes are applied to a range of characters, so you can for example, set a strikethrough attribute for just a portion of a string. It's also important to note that the default font for attributed string objects is Helvetica 12-point. Keep this in mind if you set the font attribute for a range other than the complete string. The following attributes can be set with attributed strings:
NSString *const NSFontAttributeName;
NSString *const NSParagraphStyleAttributeName;
NSString *const NSForegroundColorAttributeName;
NSString *const NSBackgroundColorAttributeName;
NSString *const NSLigatureAttributeName;
NSString *const NSKernAttributeName;
NSString *const NSStrikethroughStyleAttributeName;
NSString *const NSUnderlineStyleAttributeName;
NSString *const NSStrokeColorAttributeName;
NSString *const NSStrokeWidthAttributeName;
NSString *const NSShadowAttributeName;
NSString *const NSVerticalGlyphFormAttributeName;

 // Create attributed string
 NSString *str = @"example for underline \nexample for font \nexample for bold \nexample for italics";

 NSMutableAttributedString *attributedString =
 [[NSMutableAttributedString alloc] initWithString:str];

 // Add attribute NSUnderlineStyleAttributeName
 [attributedString addAttribute:NSUnderlineStyleAttributeName
                   value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
                   range:NSMakeRange(12, 9)];
 [attributedString addAttribute:NSUnderlineStyleAttributeName
                   value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
                   range:NSMakeRange(12, 9)];

 // Set background color for entire range
 [attributedString addAttribute:NSBackgroundColorAttributeName
                   value:[UIColor yellowColor]
                   range:NSMakeRange(0, [attributedString length])];

 // Create NSMutableParagraphStyle object
 NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
 paragraph.alignment = NSTextAlignmentCenter;

 // Add attribute NSParagraphStyleAttributeName
 [attributedString addAttribute:NSParagraphStyleAttributeName
                   value:paragraph
                   range:NSMakeRange(0, [attributedString length])];

 // Set font, notice the range is for the whole string
 UIFont *font = [UIFont fontWithName:@"Helvetica" size:18];
 [attributedString addAttribute:NSFontAttributeName
                   value:font
                   range:NSMakeRange(35, 4)];

 // Set font, notice the range is for the whole string
 UIFont *fontBold = [UIFont fontWithName:@"Helvetica-Bold" size:18];
 [attributedString addAttribute:NSFontAttributeName
                   value:fontBold
                   range:NSMakeRange(53, 4)];

 // Set font, notice the range is for the whole string
 UIFont *fontItalics = [UIFont fontWithName:@"Helvetica-Oblique" size:18];
 [attributedString addAttribute:NSFontAttributeName
                   value:fontItalics
                   range:NSMakeRange(71, 7)];

 // Set label text to attributed string
 [self.mytextView setAttributedText:attributedString];

For more info Refer here

A: This may help
self.textView.attributedText =
[   NSAttributedString.alloc
    initWithFileURL:[ NSBundle.mainBundle URLForResource:@"License" withExtension:@"txt"  ]
    options:nil
    documentAttributes:nil
    error:err];

Edit : if each individual words or characters or paragraph needs to be format then its better to use html code and load it with NSAttributedString.
Thanks

A: My extension function to convert html to NSAttributedString. If the License.txt is composed by html syntax, then it could convert to NSAttributedString directly.
@implementation NSString (Html)
- (NSAttributedString *)htmlToAttributeString
{
    NSAttributedString *str = [[NSAttributedString alloc] initWithData:[self dataUsingEncoding:NSUTF8StringEncoding]
                                                               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                    documentAttributes:nil
                                                                 error:nil];
    return str;
}
@end


text:
Q: Python web scraping indeed, BeatifulSoup, unpredictable results Here I have a web scraper using Python and BeautifulSoup that scrapes indeed and gathers job titles, companies, and salary data. The salary data can be all sorts of different entries on indeed ie "5.2k per month" or "100,000 per year" etc. Thus I have a function to change this data, regardless of the format, to an actual salary (yearly) integer like '100000'. Some jobs have no salary data listed in the salary portion and for those jobs I am returning 0.
The problem I am running into is when a job has no salary data listed, sometimes its salary data gets logged as the previous jobs salary data. This does not happen every time and seems to have varrying results with how often it happens and on which jobs, some jobs with no salary data log perfectly fine as 0.
Here is an example of dictionary output with the problem from when I scraped two pages of jobs for Network Architects and Carpenters, here at the bottom is one example of the problem:
{'title': 'new Carpenter', 'company': 'County of Orange', 'salary': 67694, 'href': 'https://ca.indeed.com/viewjob?jk=0d2ce3b674852afa', 'id': 'job_0d2ce3b674852afa'}, {'title': 'new Carpenter', 'company': 'TIC', 'salary': 67694, 'href': 'https://ca.indeed.com/viewjob?jk=73f24cf56510c78a', 'id': 'job_73f24cf56510c78a'},
I have the links pulled from the site to verify if anywhere there is salary data listed aswell.
This is also my first python and webscraping project so if there is a better way to do this entirely that would also solve the issue then that would suffice as well.
Code:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import time

def extract(page, job):
    headers = headers
    url = f'https://www.indeed.com/jobs?q={job}&start={page}&vjk=e8bcf3fbe7498a5f'
    r = requests.get(url,headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    return soup

# Turn any type of salary data into one type
def filter_salary(x, knumber, number, first_list):
    if x[-1] == 'K':
        y = list(x)
        y[-1] = ''
        z = ''.join(y)
        z1 = re.sub(r'[$]', '', z)
        z2 = int(float(z1)) * knumber
        first_list.append(z2)

    else:
        y = list(x)
        z = ''.join(y)
        z1 = re.sub(r'[$]', '', z)
        z2 = int(float(z1)) * number
        first_list.append(z2)

def transform(soup):

    #get job title company and salary data from inded
    for job in soup.select('.result'):
        title = job.select_one('.jobTitle').get_text(' ')
        company = job.find(class_='companyName').text
        id1 = job.get('id')

        try:
            salary = job.find(class_='attribute_snippet').text
        except:
            salary = 0

        print(f"title: {title}")
        print(f"company: {company}")

       #filter out salary data and return in salary ie $100 an hour ->
        if salary != 0:
            salary2 = re.sub(',', '', salary)
            if 'an hour'in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 2080000, 2080, first_list)

            elif 'a day' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 365000, 365, first_list)

            elif 'a week' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 52000, 52, first_list)

            elif 'a month' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 12000, 12, first_list)

            else:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 1000, 1, first_list)

            # Average the salary range if two are give ie 10-20 becomes one int 15
            if len(first_list) == 2:

                res = int(float((first_list[0] + first_list[1]) / 2))

            elif len(first_list) == 1:

                res = int(float((first_list[0])))

            elif len(first_list) == 0 or None:

                res = 0

            else:

                res = 0

        #sleep to avoid to many url requests per second
        time.sleep(1)

        jobLinkUrl = f'https://ca.indeed.com/viewjob?jk={job["data-jk"]}'

        job = {
            'title': title,
            'company': company,
            'salary': res,
            'href': jobLinkUrl,
            'id': id1
        }
        joblist.append(job)

    return

joblist = []

#search 2 pages of each Network Architect and Carpenter
for i in range(0,20,10):
    print(f'Getting page, {i}')
    jobSearchList = ['Network%20Architect', 'Carpenter']
    for job in jobSearchList:
        c = extract(0, job)
        transform(c)
print(joblist)
print('done')

A:       if salary != 0 and != [] and != None:
            salary2 = re.sub(',', '', salary)
            if 'an hour'in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 2080000, 2080, first_list)

            elif 'a day' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 365000, 365, first_list)

            elif 'a week' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 52000, 52, first_list)

            elif 'a month' in salary2:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 12000, 12, first_list)

            else:
                salary3 = re.findall('\$\d+(?:\.\d+)?K?', salary2)
                first_list=[]
                for x in salary3:
                    filter_salary(x, 1000, 1, first_list)
     else:
          res:0

The additional else: res = 0 fixed the issue, but also added the and != [] and != None for good measure.


text:
Q: Sending different array of data via UIActivityViewController options I have an array of items to share. For example: string item and image item. How can I achieve if all options except an AirDrop sharing would use this type of data and Airdrop would use custom object?
i tried to use activityViewController:itemForActivityType: but this delegate method works only if I return a single object, so returning array does nothing.


text:
Q: Disable mouse wheel scroll on QscrollArea I would like to simply disable mouse wheel scroll on QScrollArea, in order to scroll down only by clicking on right scrollbar, but I can't find any solution on the Internet.
app = QtGui.QApplication([])
sa = pg.QtGui.QScrollArea()
win = pg.GraphicsWindow()
sa.setWidget(win)

The problem is that I have a lot of graphs in my scroll area, and when I try to mousewheel on one of them, the page will scroll up or down together with the graph.
I can't find a method to call on "sa" to disable mouse wheel scroll.
I found some posts discussing about install event filter but I can't understand how to use them in this case. For example, I tried to use this:
sa.viewport().installEventFilter(???)

but I really didn't understand what arguments to pass and how to check the event.
Thank you in advance if you can help me with this problem.

A: You have the right idea. Event-filtering requires an object that inherits QObject to watch for the relevant events. Such objects have an eventFilter method which can be overriden to provide custom handing of all events for the watched object. If this method returns True for a given event, it will not be propagated any further. Usually the main-window is used to provide the event-filtering, like this:
import sys
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.scroll = QtGui.QScrollArea()
        self.widget = QtGui.QGraphicsView()
        self.widget.setFixedSize(600, 600)
        self.scroll.setWidget(self.widget)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.scroll)
        self.scroll.viewport().installEventFilter(self)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.Wheel and
            source is self.scroll.viewport()):
            return True
        return super(Window, self).eventFilter(source, event)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 400, 300)
    window.show()
    sys.exit(app.exec_())

A: I finally managed to resolve this, using this solution:
class Scroller(pg.QtGui.QScrollArea):
    def __init__(self):
        pg.QtGui.QScrollArea.__init__(self)
    def wheelEvent(self, ev):
        if ev.type() == QtCore.QEvent.Wheel:
            ev.ignore()

app = QtGui.QApplication([])
sa = Scroller() # <======
win = pg.GraphicsWindow()
sa.setWidget(win)


text:
Q: Float and @media query doesn't seem to work together Here's my CSS:
div.imgbeequick
{
background: url('../img/beequick400-135.png') no-repeat center top;
display: inline-block;
vertical-align: center;
width:45%;
margin:auto;
height:135px;
}

aside
{
padding:5px;
vertical-align: center;
color:black;
float:right;
}

@media screen and (min-width: 1076px)
{
    div.imgbeequick
    {
    width:45%;
    }

    aside
    {
    clear: both;
    float: right;
    vertical-align: center;
    }
}

@media screen and (max-width: 1075px)
{
    div.imgbeequick
    {
    width:100%;
    }

    aside
    {
    float: none;
    width:80%;
    margin:auto;
    text-align:center;
    }
}

The problem is the aside button doesn't float right when I expand the window to more than 1076 px (but it floats if the page size during refresh is more than this size)
Here's a link to the whole page: http://javascript-ninja.fr/beequickcomm/
The aside button contains the input, the div.imgbeequick is the image of the bee

A: May be, this changes helps you to get what you need:
@media screen and (min-width: 1076px) {
    div.imgbeequick {
        width:45%;
        float: left; /* ADDED */
    }

    aside {
        /*clear: both; REMOVED */
        float: right;
        vertical-align: center;
    }
}

@media screen and (max-width: 1075px) {
    div.imgbeequick {
        width:100%;
        float: none; /* ADDED */
    }

    aside {
        float: none;
        width:80%;
        margin:auto;
        text-align:center;
    }
}

A: Replace float:right; in the aside class with display:inline-table
@media screen and (min-width: 1076px)
{
    div.imgbeequick
    {
    width:45%;
    }

    aside
    {
    clear: both;
    display: inline-table;
    }
}

Oh, and one more thing...there's no such thing as vertical-align: center; the value you meant was propably 'middle', but it is not necessary in your case.

The inline-table value does not have a direct mapping in HTML. It
  behaves like a  HTML element, but as an inline box, rather than
  a block-level box. Inside the table box is a block-level context. (source)


text:
Q: What does :: before array means in C++ explicitly in below code? In the below code I could not understand what does :: before array add[i] means. Can anyone give me a general idea of what does this means in c++ if added before array data structure?(This is general for reference only code)
#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)

    FOR(i, 1, n) {
        scanf("%d %d", &x, &y);
        double add = dist(Tx, Ty, x, y);
        all += add * 2;
        suff[i] = pre[i] = dist(Cx, Cy, x, y) - add;
        ::add[i] = dist(Kx, Ky, x, y) - add;
    }

A: It means it is referencing the array add defined in the global namespace rather than the local variable add defined in the block of code following the FOR macro.
Usually you'd just give the local variable a different name. And most times you wouldn't have a global mutable variable either.


text:
Q: How To Have A Blog Where Users Can Only Edit Posts For A Limited Time in Ruby on Rails I've made a very simple blog where users can Create, Edit and Delete posts however I want to add functionality where users can only Edit for a limited time (say 3 days). My understanding of Ruby is not strong enough to know how to do this so any help is appreciated.
This is my Notes (my name for Posts) controller
class NotesController < ApplicationController
before_action :find_note, only: [:show, :edit, :update, :destroy]

def index
    @notes = Note.where(user_id: current_user)
end

def show
end

def new
    @note = current_user.notes.build
end

def create
    @note = current_user.notes.build(note_params)

    if @note.save
        redirect_to @note
    else
        render 'new'
    end
end

def edit

end

def update
    if @note.update(note_params)
        redirect_to @note
    else
        render 'edit'
    end
end

def destroy
    @note.destroy
    redirect_to notes_path
end

private

def find_note
    @note = Note.find(params[:id])
end

def note_params
    params.require(:note).permit(:title, :content)
end

end

I assume somewhere in the edit method I need to write a rule for restricting the ability to edit posts to only 3 days, using the created_at function somehow? I'm just at a loss as to exactly how to do this.
Any help is appreciated.

A: Perfect solution for that is :before_filter
class NotesController < ApplicationController
    before_filter :check_time!, only: [:edit, :update]

    def edit
    end

    def create
    end

    private

    def check_time!
      if Time.now() > @note.created_at + 3.days
        flash[:danger] = 'Out of 3 days'
        redirect_to note_path(@note)
      end
    end
end


text:
Q: Where do I put a piece of code that I want to run right before a multi-form Windows form app exits? (no matter how the program exits) I have a C# application that consists of multiple forms, and there is no particular one which will always be closed last.
Where should I put a piece of code (i.e. dumping some information to a file) to ensure that no matter how the program exits, this happens just before the program closes?

A: Well one option would be to call a method to do what ever you want right before the main method exits.
ETA:
by default the main method is in the program.cs file.
here is an example of what I mean
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

        //** this code will not be reached until form1 closes.
        bool blah = true;
        doWhatEver(blah);
    }


text:
Q: How to add element components from in and out of promise I am trying to create an image with it's source set to a download url which is retrieved by a .getDownloadURL() function from firebase.
I also want to set the id of the image to the firebase storage path, so I can get the name of the image.
The issue however, is that when I try to make the path inside the .getDownloadURL() function, it says "can't get location of undefined", because the scope of the path variable doesn't reach inside.
My attempt at a solution was to create the image and add the id before entering the .getDownloadUrl() function, but then I can't set the .src of img inside of the 'getDownloadURL()' function because img is undefined.
Anyway I would appreciate any help, thanks for your time.
Here is my code:
for(n=0; n<subarray.length; n++){
    //add image with url src
    var path = subarray[n].location.path_; //I want the img ID to be this
    var img = document.createElement("IMG"); //this is the IMG
    img.id = path;

    storage.ref(subarray[n].location.path_).getDownloadURL().then(function(url){
        img.src = url; //error says cannot set .src of undefined
        column = "column" + columnNr //columnNr is defined earlier as 1
        columnNr = columnNr + 1;
        if(columnNr > 4){
            columnNr = 1;
        }

         document.getElementById(column).appendChild(img);
    });
}


text:
Q: i7 7700 CPU power supply Watts
Can you tell me the power supply Watts for above configured PC? At this moment I have 350 W. Is that fine or?
Note: This is a software development PC and I'll not use this as gaming or any graphic design use cases.

A: It depends what you also have in the computer. The most important being a graphics card, they can consume great amounts of power while on heavy loads.
But if you're not getting a graphics card, and relying on the CPU for graphics output, I personally think you'd be just fine with 350 watts. There is a lot of factors that play into that determination. But your 7700 isn't exactly a high end CPU that consumes crazy amounts of power.
As a general rule with any PC build in the last 10 years. I always get at least 500 watts of power for non-graphic card builds. For gamer computer builds 600-750 watts depending on the graphics card.
The reason is because the cost of a 350 to 500 watt power supply are generally the same, there is always a 500 watt power supply from a reputable company on sale that would cost the same was a 350 watt. So why not get something a little bigger.


text:
Q: Keycloak: Unable to get RPT using resource name I'm trying to get RPT without permission ticket only using resource names. While this method works when working with policies, it doesn't seem to work with users sharing their resources through account page (returns access denied). For some reason when user A shares a resource with user B, user B can get RPT for this resource only if he:
a) Requests all his permissions
or
b) Requests specific permissions by id (not name)
Is this intended behaviour? If so how can i overcome this problem and still use only resource names?
Getting RPT by resource name (doesn't work with sharing):
    curl "$PROTOCOL://$HOST:$PORT/auth/realms/$REALM/protocol/openid-connect/token" \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&permission=$RESOURCE_NAME&audience=$RESOURCE_CLIENT_ID"

Getting RPT by resource id (works with sharing):
    curl "$PROTOCOL://$HOST:$PORT/auth/realms/$REALM/protocol/openid-connect/token" \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&permission=$RESOURCE_ID&audience=$RESOURCE_CLIENT_ID"

Getting RPT for all resources (works with sharing):
    curl "$PROTOCOL://$HOST:$PORT/auth/realms/$REALM/protocol/openid-connect/token" \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&audience=$RESOURCE_CLIENT_ID"

A: This issue is fixed in version 6.0


text:
Q: How to view the output of kable and kableExtra correctly in an R notebook? I'm having a lot of trouble rendering kable and kableExtra output correctly using R Notebooks, both inline and in the HTML Preview.
I've changed the print handling in the YAML header to kable (not sure this is necessary?):
---
title: "MIPS Sample Overlap with ASC"
output:
  html_notebook:
    theme: lumen
    df_print: kable
  html_document:
    df_print: kable
  pdf_document: default
---

When I run the command inside the notebook, the output appears inline, however there are two problems:

*

*It usually has a very large empty white space at the bottom.

*It always replaces my whole notebook preview in the RStuduio Viewer with a copy of just the kable_styling() output.

When I reload the notebook preview, the table is now rendered in its proper context, but without the lines seen in the inline output. This happens with kable alone as well.

What am I doing wrong?
Thank you!


text:
Q: Why does my call to start OpenOffice service work in development but not on server? I have a ColdFusion application that reads a list of files from a directory, and then converts each MSOffice document in the list to a PDF using the JODConverter library and OpenOffice.org 3.4.1.
I wrote this application and setup my development PC according the instructions in the two articles here:
http://cfsearching.blogspot.com/search/label/JODConverter
The only difference is that I installed the necessary JARs outside of cf_root.
<cffunction name="convertNonPDFFiles" returntype="Void" output="false">
    <cfscript>
        //  CONSTANTs
        var _NON_PDF_PATH = APPLICATION.PDFSource & "\NonPDFs";
        var _PDF_PATH = APPLICATION.PDFSource & "\PDFs";
        var _VALID_FILE_EXTENSIONS = "doc,docx,ppt,pptx";

        //  Set defaults for private variables
        var _qNonPDFDir = QueryNew("");
        var _fileName = "";
        var _documentId = 0;
        var _sourceFilePath = "";
        var _destinationFilePath = "";
        var _fileExtension = "";
        var _isConversionSuccessful = true;
        var _tempSourceFilePath = "";
        var _tempImageFilePath = "";

        //  Initialize Open Office Conversion Manager
        var _openOfficeManager =
            CreateObject(
                "java",
                "org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration"
                ).setOfficeHome(
                    APPLICATION.OpenOfficeProgramPath // Location of the OpenOffice.org 3.4.1 application directory on the server
                    ).setTaskExecutionTimeout(60000).buildOfficeManager();

        _openOfficeManager.start();
    </cfscript>

    <!--- Retrieve a list of file names in the directory of unprocessed
        non-PDF files --->
    <cfdirectory
        action="list"
        directory="#_NON_PDF_PATH#"
        name="_qNonPDFDir"
        type="file"
        listinfo="name"
        sort="datelastmodified DESC" />

    <cfoutput query="_qNonPDFDir">
        <cfscript>
            _fileName = _qNonPDFDir.name;
            _fileExtension =
                REQUEST.UDFLib.File.getFileExtension(_fileName);
            _sourceFilePath = _NON_PDF_PATH & "\" & _fileName;

            //  File is a valid format for conversion
            if  (ListFindNoCase(_VALID_FILE_EXTENSIONS, _fileExtension)) {
                _documentId =
                    REQUEST.UDFLib.File.getFileNameWithoutExtension(
                        _fileName
                        );
                _destinationFilePath =
                        _PDF_PATH
                    &   "\"
                    &   REQUEST.UDFLib.File.getFileNameWithoutExtension(
                            _fileName
                            )
                    &   ".pdf";
                _isConversionSuccessful = true;
                _tempSourceFilePath =
                        APPLICATION.TempDir
                    &   "\"
                    &   _documentId
                    &   "." & _fileExtension;

                /*
                    Create of the copy of the original file in the temp
                    directory
                */
                FileCopy(
                    APPLICATION.of_aprimo_root & "\" & _documentId & ".dat",
                    _tempSourceFilePath
                    );

                //  Attempt to convert the file to PDF
                try {
                    // See convertFile() method below
                    convertFile(
                        openOfficeManager = _openOfficeManager,
                        inputFilePath = _tempSourceFilePath,
                        outputFilePath = _destinationFilePath
                        );
                }
                catch (any e) {
                    _isConversionSuccessful = false;
                }

                if  (_isConversionSuccessful)
                    FileMove(
                        _sourceFilePath,
                        _NON_PDF_PATH & "\Processed\"
                        );
                else
                    FileMove(
                        _sourceFilePath,
                        _NON_PDF_PATH & "\NonFunctioning\"
                        );
            }
            //  File is not a valid format for conversion
            else {
                FileDelete(_sourceFilePath);
            }
        </cfscript>
    </cfoutput>

    <cfscript>
        _openOfficeManager.stop();

        return;
    </cfscript>
</cffunction>

<cfscript>
    function convertFile(openOfficeManager, inputFilePath, outputFilePath) {
        CreateObject(
            "java",
            "org.artofsolving.jodconverter.OfficeDocumentConverter"
            ).init(ARGUMENTS.OpenOfficeManager).convert(
                CreateObject(
                    "java",
                    "java.io.File"
                    ).init(ARGUMENTS.inputFilePath),
                CreateObject(
                    "java",
                    "java.io.File"
                    ).init(ARGUMENTS.outputFilePath)
                );

        return;
    }
</cfscript>

This application works perfectly on my development machine, but as soon as I move it to one of my web servers, it doesn't work there.
Dev PC Setup:
 OS: Windows 7 Professional SP1
 IIS: 7
 ColdFusion: 8.0.1

Server Setup:
 OS: Windows 2003 R2 Standard Edition SP2
 IIS: 6.0
 ColdFusion: 8.0.1

When I attempt to run the application on the server - either directly in a browser or via Scheduled Tasks, it throws no exceptions. It simply appears to run until it times out after 60 minutes. In Task Manager, I can see soffice.bin start running when the application starts, but after a few seconds, soffice.bin simply disappears from the Task Manager.
Any ideas what might be the problem?

A: After some troubleshooting, I was finally able to get this to work with a few minor changes to the programming (all credit to cfSearching - I found the answer to my problem in the comments at http://cfsearching.blogspot.com/search/label/JODConverter).
Original code that configured and started the OpenOfficeManager instance:
            CreateObject(
                "java",
                "org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration"
                ).setOfficeHome(
                    APPLICATION.OpenOfficeProgramPath
                    ).setTaskExecutionTimeout(60000).buildOfficeManager();

Updated (fixed) to add setConnectionProtocol() and setPortNumber():
            CreateObject(
                "java",
                "org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration"
                ).setOfficeHome(
                    APPLICATION.OpenOfficeProgramPath
                    ).setConnectionProtocol(
                        CreateObject(
                            "java",
                            "org.artofsolving.jodconverter.office.OfficeConnectionProtocol"
                            ).SOCKET
                        ).setPortNumber(
                            8100
                            ).setTaskExecutionTimeout(
                                60000
                                ).buildOfficeManager();

A: It may be as simple as OpenOffice needing to be re-installed on the server where as it is on your dev machine.


text:
Q: Counter in Python Is there a way to collect values in Counter with respect to occurring number?
Example:
Let's say I have a list:
list = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd']

When I do the Counter:
Counterlist = Counter(list)

I'll get:
Counter({'b': 3, 'a': 3, 'c': 3, 'd': 2})

Then I can select let's say a and get 3:
Counterlist['a'] = 3

But how I can select the occurring number '3'?
Something like:
Counterlist[3] = ['b', 'a', 'c']

Is that possible?

A: You can write the following
import collections

my_data = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd']
result = collections.defaultdict(list)
for k, v in collections.Counter(my_data).items():
    result[v].append(k)

and then access result[3] to obtain the characters with that count.


text:
Q: ImageMagick NodeJs WriteBlob error I am using the s3-uploader module for nodejs to create several versions of an image before uploading to S3. This module relies on ImageMagick to be installed. However, I am receiving this WriteBlob error when the command runs.
The files are written to one of the project directories, and I've set permissions correctly. It's been a tricky one, and I believe I've exhausted google :p
Here's the error produced when I print out a nodejs spawn log.
spawn called
{ '0': 'convert',
  '1':
   [ '/home/ec2-user/se/uploads/allergies-infographic-custom.jpg',
     '/home/ec2-user/se/uploads/allergies-infographic-custom.jpg.mpc' ] }
150529/235556.528, [error], message: Command failed: convert: magick/blob.c:4031: WriteBlob: Assertion `data != (const unsigned char *) ((void *)0)' failed.

What could this error indicate that I've configured wrong?

A: I've already gotten the same issue as yours. That problem came from ImageMagick library, switch to GraphicMagick will solve the problem, because s3-uploader does not provide option to make the switch, you need to clone that project and modify it manually.
Edit file index.coffee and compile it again. Change line:
gm = require('gm').subClass imageMagick: true

to:
gm = require('gm').subClass imageMagick: false


text:
Q: ¿Cómo actualizar un componente en JSF 1.2 para ocultarlo cuando su propiedad renderizada no está satisfecha? Estoy usando JSF 1.2 para construir un formulario. Se crea dinámicamente, lo que significa que no siempre serán los mismos campos, ni el mismo tipo de campo (chebox, radio button y otros). Algunos de estos campos son obligatorios, lo sabes gracias a la propiedad v.required.
Me piden que muestre un * con un mensaje que dice "Valor requerido" apenas se carga la página, para que el usuario no tenga que presionar el botón de aceptar para saber qué campos son obligatorios o no. El problema es que el sitio ha implementado mensajes de error con FacesMessages que indican con un "Caracteres incorrectos" y también "Valor requerido", entonces cuando el usuario carga la página por primera vez aparece mi * con mi mensaje, y si el usuario presiona aparece el botón "Aceptar" y luego FacesMessages con el mensaje "Valor requerido"
Así es como construyo mi *:
<h:outputText for="#{idUtil.For(v)}" ajaxRendered="true" value="*" styleClass="required" rendered="#{v.requerido and facesMessages.getCurrentMessagesForControl(idUtil.For(v)).size()==0}"
                                                                                title="Required value" />

Así aparece cuando cargo la página por primera vez: y asi me aparece cuando pulso el boton de aceptar, el * que estoy mostrando y los FacesMessages con el mismo mensaje:
¿Cómo puedo ocultar mi * cuando aparece FacesMessages? ¿Hay alguna forma de volver a renderizar los componentes por clase? No puede ser por id porque cuando estos campos se generan dinámicamente no pueden tener un id estático


text:
Q: Internet doesn't work when running windows phone 8 emulator I have installed Visual Studio 2013  which comes with Windows Phone 8 Emulator. When I am trying to run emulator my internet in both laptop and emulator doesn't work. Earlier it was working in my laptop. I checked in network connections its creating a "Bridge". I am not sure what is the issue. Internet in my laptop works only if i remove "Bridged Connection".
My friend use to share internet using Connectify Hotspot and i used to connect for internet access. I am not sure if that is the problem.


text:
Q: String interpolation with a function I wonder why string interpolation in julia works for functions like f1, but failed for findall in the following example. Is there a way for me to use functions like findall with string interpolation?
f1 = function(x, y) x + y end
"1 + 4 = $(f1(1, 4))"

findall(r"a", "abca")

"x: $(findall(r\"a\", \"abca\"))"  # failed

I am using Julia 1.6.1.

A: In string interpolation inside $(...) you can write regular Julia code, there is no need to escape " etc as in your original example. Just plug in the exact same expression:
julia> findall(r"a", "abca")
2-element Vector{UnitRange{Int64}}:
 1:1
 4:4

julia> "x: $(findall(r"a", "abca"))"
"x: UnitRange{Int64}[1:1, 4:4]"

A: This seems work after some trials. But I still do not why it fails with double quotes.
"""x: $(findall(r"a", "abca"))"""


text:
Q: Growing user control not updating I am developing in C# and .Net 2.0.  I have a user control that draws cells (columnar) depending upon the maximum number of cells.  There are some drawing routines that generate the necessary cells. There is a property NumberOfCells that adjust the height of this control; CELLHEIGHT_CONSTANT * NumberOfCells. The OnPaint() method is overridden (code that draws the Number of cells).
There is another user control that contains a panel which contains the userControl1 from above.  There is a property NumberCells that changes userControl1's NumberOfCells.
UserControl2 is then placed on a windows form.  On that form there is a NumericUpDown control (only increments from 1).  When the user increments by 1, I adjust the VerticalScroll.Maximum by 1 as well.
Everything works well and good BUT when I increment once, the panel updates fine (inserts a vertical scrolll when necessary) but cells are not being added!  I've tried Invalidating on userControl2 AND on the form but nothing seems to draw the newly added cells.
Any assistance is appreciated.  Thank you in advance.

*

*Lawrence

A: Try debugging and check that the NumberOfCells property is properly being set.  If it is and the cells still do not show after the window has invalidated (say, by minimizing then restoring the window), you have a problem with your cell-drawing method.
If after minimizing/restoring the cells show up, you need to call Invalidate(CellRegion) in the setter for NumberOfCells

A: Are you resizing the controls when you add columns? If they are not big enough to show their entire contents, then they will simply clip them and you may not see any new column(s) that have been added.


text:
Q: P-Value Adjustment for Multiple Linear Regression I am a little confused, how to utilize the p-value adjustments the correct way. And also in way over my head.
This is what I am doing so far:

*

*I am running 2 Multivariate Multiple Linear Regressions with 2 sets of 13 variables as dependent variables and the same set of 4 predictors.

*Then I go for the dependent variables trough each one and see which predictors were significant. For each DV I therefore create a Multiple Linear Regression model with all predictors and compare that to the reduced Model with only significant seeming predictors.
My question now is: Where should I correct the p-values and which should I correct for?
So 1. should I correct the p-value for the significance of the whole model OR for the significance of each predictor inside one of the models OR both?
And 2. for how many and which of the models should I correct?
Should I only correct inside the full models with all predictors OR only for the reduced models OR both?
Sorry if there are similar questions already, please point me to them if there are and they would answer this. Or other good resources, where this would be explained well.


text:
Q: LXDE ubuntu 17.04 - The use of dead keys to type accents does not seem to work The use of dead keys to type accents does not seem to work in any progam. I have physical keyboard MICROSOFT NATURAL (English) and languages installed Portuguese (Brasil) and English (USA). For example typing ' then c , or any accent with the layout 'international with dead keys' leads to a character without accent. Ibus is activated, and deactivating it does not solve the issue.

A: Lucas Simon's solution worked perfectly in my Lubuntu 18.04.1 .
As I don't normally login as root, I opened an LXTerminal and ran the sudo variant of Lucas Simon's command line:
sudo apt install ibus && ibus-setup --xim

This quickly downloaded & installed some ibus packages, after which all my dead key accents immediately worked as intended - no further steps were needed, and I didn't even need to restart anything.

A: I have the same problem in Lubuntu 17.07. my keyboard is PT_BR ABNT2 layout
Run it:
apt install ibus && ibus-setup --xim

Choose restart keyboard layout. And try again yéééééééééééééah


text:
Q: Save / recreate OpenGL Framebuffer / Renderbuffer texture during activity pause I have an Android activity using a texture with dynamic content (drawn into via Framebuffer / Renderbuffer).
When the activity is paused / resumed, the texture (like all textures) is lost and must be recreated.
Is there a way to save the content of the dynamic texture into some persistent object on pause and recreate the texture from this object on resume?
I already found some threads describing hack-like ways to prevent the textures from being invalidated on pause, but if possible I'd like to do it "by the book" and free the texture memory on pause / recreate textures on resume.

A: You can use glReadPixels to transfer the FBO's contents into a persistent buffer of your app. Then, upon resume you can load that data back into the textures. Restoring a renderbuffer would require to load into a intermediary texture, and drawing then that using a full viewport quad to the FBO with the renderbuffer attached. Hence I suggest you don't use Renderbuffers, if you can avoid them. Using a texture you can save the intermediary step.


text:
Q: Foreach and for changes a lot more items then should I have a foreach loop which iterates through a list, and the following code inside:
    foreach(var item in collection)
    {
        if(random.NextDouble() < somedouble)
        {
            item.Something = Enum.Something;
            anotherList.Add(item);
        }
    }

And then when I count items in anotherList:
   int anotherListCount = anotherList.Count;

I will receive like 40 items, and when I count items with condition like item.Something = Enum.Something with:
    int count = collection.Count(item => item.Something == Enum.Something);

I will receive like 50-60 items (a lot more).
Why does it change more items than it should? A simple for does the same.
UPDATE:
In constructor of item I set Enum.NotSomething so there can't exist any with Enum.Something. I run the Count method before loop and it says 0.

A: When checking collection, you are also getting items that had Enum.Something before the loop, but where not added to the list because of the randomness.
Remember, in C#, you have references to objects, and as such, when you change the item in the loop, it will also change in the original collection.

A: Probably, you are sharing object references somewhere unintentionally. You are trampling over shared state. Maybe the list was not empty before you added to it. Who knows.
This is the reason functional programming styles are so powerful. You should have written:
var anotherList =
collection
.Where(_ => random.NextDouble() < somedouble)
.Select(item => item.CreateCopyWithEnum(Enum.Something))
.ToList();

Once you create some object or list, try not to touch it, because you are likely to inadvertently break other code relying on the data staying stable.


text:
Q: Plot yerr/xerr as shaded region rather than error bars In matplotlib, how do I plot error as a shaded region rather than error bars?
For example:

rather than

A: Ignoring the smooth interpolation between points in your example graph (that would  require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():
from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

See also the matplotlib examples.

A: This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)

y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)

pl.show()


text:
Q: MySQL - Select specified record with some conditions multiple table
I have a little trouble with a MySQL query, I have two tables tb_user and tb_trx and the last one is the result which I'm trying to do
What I want to do is to show id_user from tb_user which have level = 0 and if id_user in tb_trx have status = 0 more than equals 2, they will not appear in result.

A: Have a go with this (N.B. I haven't tested it):
select u.id_user from tb_user u
where u.level = 0
and (select count(*) from tb_trx t
     where t.id_user = u.id_user
     and t.status = 0) <= 2

Incidentally, I don't think your data set would properly test the rule you have given (which I may have misunderstood, your statement of it is pretty unclear).


text:
Q: How to make child in ExpandableListView a textbox instead of a list for Android? So I have an ExpandableListView. Right now I have 3 Items in The parent List. When I click on one of those, the child list (sublist pops up). What I want is for a textbox to show up underneath rather than a list.
I want a list for the parent, but a textbox for the child. I'm not sure how to do this. This is my code right now:
public void onCreate(Bundle savedInstanceState) {
    try{
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_assignment);

    SimpleExpandableListAdapter expListAdapter =
        new SimpleExpandableListAdapter(
                this,
                createGroupList(),              // Creating group List.
                R.layout.group_row,             // Group item layout XML.
                new String[] { "Group Item" },  // the key of group item.
                new int[] { R.id.row_name },    // ID of each group item.-Data under the key goes into this TextView.
                createChildList(),              // childData describes second-level entries.
                R.layout.child_row,             // Layout for sub-level entries(second level).
                new String[] {"Sub Item"},      // Keys in childData maps to display.
                new int[] { R.id.grp_child}     // Data under the keys above go into these TextViews.
            );
        setListAdapter( expListAdapter );       // setting the adapter in the list.

    }catch(Exception e){
        System.out.println("Errrr +++ " + e.getMessage());
    }
}

//Create Headings of Assignment attributes
private List createGroupList() {
    ArrayList result = new ArrayList();

    //Create string array for Assignment Topic headings
    String[] topics = {"1", "2", "3"};

    //Iterate through array of names to lay them out correctly
    for( int i = 0 ; i < 3 ; ++i ) {

      HashMap m = new HashMap();
      m.put( "Group Item", topics[i] ); // the key and it's value.
      result.add( m );
    }
    return (List)result;

}
@SuppressWarnings("unchecked")
private List createChildList() {

    ArrayList result = new ArrayList();
    for( int i = 0 ; i < 3 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
      /* each group need each HashMap-Here for each group we have 3 subgroups */
      ArrayList secList = new ArrayList();
      for( int n = 0 ; n < 3 ; n++ ) {
        HashMap child = new HashMap();
        child.put( "Sub Item", "Sub Item " + n );
        secList.add( child );
      }
     result.add( secList );
    }
    return result;
}

Obviously, I'm creating a childList when I want the child to be a text box. Not sure how to implement this tho. Any help greatly appreciated!

A: try to place only an edittextview  in "R.layout.child_row" . If it gives an error then place a textview also but make it invisible.I hope that will solve the problm

A: It's very simple, you should create a layout called: child_layout_row like so...
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="match_parent">
    <EditText android:id="@+id/text_edit_child"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" />
</LinearLayout>

and instead of R.layout.child_row, use R.layout.child_layout_row that's it....


text:
Q: How would I programmatically click a button in JavaFX from another method? I have a listener class that is networked into my phone to receive input from an application called TouchOSC. In that class, I can call methods whenever I press a button on my phone. What I need to do is to click a JavaFX button to trigger an event in that method whenever my computer receives the input from my phone. How would I trigger something like that?

A: button.fire()

Invoked when a user gesture indicates that an event for this ButtonBase should occur.

When a button is fired, the button's onAction event handler is invoked.

The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.

Sample Code
Creates a button and automatically fires it four times.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.stream.IntStream;

public class RapidFire extends Application {
    private static int nClicks = 0;

    @Override
    public void start(Stage stage) throws IOException {
        // setup button and action handler.
        Button button = new Button("Click Me!");
        button.setOnAction(event -> {
            nClicks++;
            System.out.println("Clicked " + nClicks + " times.");
        });
        button.setPadding(new Insets(10));
        button.setPrefWidth(100);

        // show the button.
        stage.setScene(new Scene(button));
        stage.show();

        // fire the button a few times in succession.
        IntStream.range(0, 4).forEach(
                i -> button.fire()
        );
    }

   public static void main(String[] args) {
        launch(args);
    }
}

Output of the sample is:
Clicked 1 times.
Clicked 2 times.
Clicked 3 times.
Clicked 4 times.


text:
Q: How do I access a shared folder using credentials other than the ones I logged in with? I have a lab full of Windows 7 machines, and a shared login (user360) that all my students use.  I also have a shared folder that they can all have read/write access to (for moving files around easily).
My problem is that I also want to be able to create a shared folder for each student for submitting assignments.  I can set up a shared folder with permissions for just a single user, and not the 'user360' account.
The problem is, when I'm logged in as user360, and I try to open the 'StudentA', Windows never asks me for alternate credentials, it just refuses access because the user360 account is not allowed access.
Can anyone suggest a fix for this?

A: In Win7. While accessing Shared Folder with different credential still FAILED and DENIED even using correct USERNAME and appropriate password, make sure your 'Credential Manager' is free from inappropriate cached.

Thank you. :)

A: What you need to do is to have the shared folder mapped on each computer, which allows you to use different credentials.
In My Computer, click on Tools (hidden by default, show by pressing ALT), Map Network Drive, and there, type in the path for the drive and underneath, click on "Connect using different credentials"
Good luck!
EDIT:
For the credentials to be accepted the correct format is for the username is:
\\SERVERNAME\username
Then just the normal password for the account.


text:
Q: In sinon how do you spy on a module imported via "* as" when there are no functions I'm trying to spy on the marked package (https://www.npmjs.com/package/marked).
I imported in my code like this
import * as renderMarkdown from 'marked';

and use it like this
renderMarkdown(readme)

So how can I spy on it using sinon? Normally I spy on a imported method like this
import * as someImport from '../xxx'

...

const spy = sinon.spy(someImport, 'methodName');

...

sinon.assert.callCount(spy, 1);
spy.restore();

But in this case I don't have a "methodName" that I can use in the spy. Can anyone tell me how I can spy on this in my test to make sure it is called?
I tried
const spy = sinon.spy(someImport);

But the test errors and the method someImport is never called
AssertError: expected marked to be called once but was called 0 times


text:
Q: Acessing elements of permutation group in sagemath if I consider an element of a permutation group in sagemath, for example
SymmetricGroup(7).list()[1900],
which is (1,6)(2,5,4)(3,7),
I can get the cycles like elements from a list, so
SymmetricGroup(7).list()[1900][1],
will return (2,5,4).
However, I do not find a way, to get the elements of this object, as it looks like a tuple, but actually it is not, as
SymmetricGroup(7).list()[1900][1][1]
gives the error "list index out of range", instead of returning 5.
Does somebody know, how I can get direct access to the entries of the cycle?
Thank you in advance.

A: I used tab-completion to find the method cycle_tuples:
sage: a = SymmetricGroup(7).list()[1900]
sage: a
(1,6)(2,5,4)(3,7)
sage: a.cycles()
[(1,6), (2,5,4), (3,7)]
sage: type(a.cycles()[1]) # not what we want
<class 'sage.groups.perm_gps.permgroup_element.SymmetricGroupElement'>
sage: a.cycle_tuples()
[(1, 6), (2, 5, 4), (3, 7)]
sage: type(a.cycle_tuples()[1]) # what we want!
<class 'tuple'>
sage: b = a.cycle_tuples()[1]
sage: b
(2, 5, 4)
sage: b[1]
5

(By "using tab-completion," I mean typing "a." and then hitting the TAB key.) cycle_tuples is documented here.


text:
Q: jQuery .wrap Добавляет много класс jQuery.noConflict();
jQuery(document).ready(function($){
$(".content .bbc").wrap('
');
$(".content .bbc").each(function() {
$(this).after('' );
})
});

Нужно всего лишь один .altwrap и один .srcchanger
Как предотвратить добавление много классов?
Щас получаю примерно такой HTML:

Нужно вот такой, если можно:

A: Все нормально он добавляет, 1 обертку

jQuery(document).ready(function($){
$(".content .bbc").wrap('
');
$(".content .bbc").each(function() {
$(this).after('' );
})
});

A: Попробую немного дованговать, вам нужен Child Selector

$(document).ready(function() {
  $(".content > .bbc").wrap('
');
  $(".altwrap > .bbc").each(function() {
    $(this).after('');
  })
});


text:
Q: Using array_keys with search_value parameter I have trouble understanding how the function array_keys works when I need it to return keys that have a certain value associated with it. For example, lets say we have an array like this:
$testArray = array
 (
    [key1] => value1,
    [key2] => value2,
    [key3] => 0
 )

My understanding of array_keys function tells me that calling this function on the given array like this:
array_keys($testArray,"value1")

should give this kind of response:
Array
(
    [0] => key1
)

But actually this is what I get:
Array
(
    [0] => key1
    [1] => key3
)

Which is strange, I think. Further testing revealed that this kind of thing happens always if I have number zero as a value in an array. It doesn't matter what value I search it for, it always returns the key that has zero as a value. Also, this happens only when the third parameter of array_keys, called strict, is set to false. If I set that parameter to true, the function works as I expect.
Am I missing something or is this an issue in PHP? I'm using PHP version 5.5.9.

A: When strings are compared, they are converted to numbers.
Try with -
array_keys($testArray,"value1", true);

Passing third parameter true will make it to compare with ===.

strict: Determines if strict comparison (===) should be used during the search.

array_keys


text:
Q: Dump H2 insert statements Hi How can I dump data only for an instance of H2 In Memory DB.
What I currently have
    PreparedStatement preparedStatement = connection
            .prepareStatement("SCRIPT SIMPLE NOSETTINGS");
    ResultSet resultSet = preparedStatement.executeQuery();
    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    while (resultSet.next()) {
        String columnValue = resultSet.getString(1);
        out.print(columnValue);
        out.println();

This dumps the entire db structure however not just the insert data.  Basically what I want to do is backup the data I insert during development mode so the next time the database is started I can script the data back in.
The table structure isn't a problem as it is done by JPA.

A: To filter out just inserts, you could use:
if (columnValue.startsWith("INSERT")) {
    out.println(columnValue);
}


text:
Q: "is bad about" idiom/phrase can be either a negative or positive assertion? I was chatting with a friend who is a proficient but non-native speaker of English, and a misunderstanding came up about my usage of a phrase of the form "<something> is bad about <doing something bad>", with the intended meaning that the thing in question commonly does the bad thing. e.g. "Willow trees are bad about causing damage to water lines".
My friend's point was that doesn't make sense, because if they are bad about doing that, that logically means they don't do it. So I got to looking/searching/thinking, and it seems like there are examples of either case, where that form of phrase could mean that a thing commonly happens, or a thing commonly doesn't happen.
For example, "They are bad about brushing their teeth" vs. "They are bad about not brushing their teeth". In my mind, both phrases mean the same thing - that they don't commonly brush their teeth.
Does the meaning of the phrase depend on whether the action/effect is perceived to be good or bad? So either a thing perceived as good doesn't commonly happen, or a thing perceived as bad commonly does happen?
Or I guess maybe another way to look at it is that the phrase is always used in the sense that has the negative connotation?

A few other examples of similar phrases, for reference.

Women, too, are bad about prying into the affairs of men.

Conversation with the High Priest of Coosa, Charles M. Hudson, page 7, books.google.com

Human eyes are bad about misjudging tall objects.

Shotgunning: The Art and the Science, Bob Brister, page 136,
books.google.com

I don't eat the pears off that tree because they are bad about having body hair in them.

Stories by Charlie: Mtn. View Arkansas, Charles E. Forte, page 62, books.google.com

A: For me, a native BrE speaker, Tommy is bad about brushing his teeth. communicates information about Tommy; the frequency of his brushing is inferred. It implies that Tommy (most likely) lacks the discipline to brush when he should.
Hence, suggesting that a willow tree is bad about doing this or that intimates that the willow tree could do otherwise, which it can't.


text:
Q: Default password in .my.cnf for a specific user We've got a backup script which takes a mysql dump every night, and to authenticate we've got a .my.cnf file with
[mysqldump]
password=somepass

However, every mysql user that doesn't pass in a password seems to inherit this password.
Is it possible to lock this into a combination? e.g.
[mysqldump@backupuser]
password=somepass

so it only gets used by that specific user?

A: Sure, just use the following:
[mysqldump]
user=backup
password=password

See also: https://dev.mysql.com/doc/refman/8.0/en/option-files.html

A: I have solved this issue by using MySQL socket connection and authentication with the socket user.
First you need to make sure you have auth_socket plugin installed.
Then the user needs to be created with:
CREATE USER 'user'@'localhost' IDENTIFIED WITH auth_socket;

After this, when you log in as this user and connect to MySQL using UNIX socket, there is no password prompt.