text:
Q: Why is the user details vanishes from the Firestore? I am using Firebase PhoneAuth for user registration with my app. Users are verified successfully and started using the app without any issues. But, It happened to me a couple of times that user details vanished from Firestore database, not all users details have gone though. When I check the collection users in the Firestore, the document does exist for the user but some data was gone, in fact, it's overwritten the old data as if this is new user registration (However, the User UID under the Authentication is remain same). For example, the default value is user_type = "customer", as you can see in the fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential). Later I change this value accordingly to my need and when this issue happens the changes I made to this field and other fields are changed back to the default values.
Following is the code in my SignInWithPhone which will be called from the SplashScreen
class SigninWithPhoneActivity: BaseActivity() {

    private lateinit var binding: ActivitySignInWithPhoneBinding
    private lateinit var mAuth: FirebaseAuth
    var code = ""
    var number = ""
    var phoneNumber = ""
    var storedOtpID = ""
    private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySignInWithPhoneBinding.inflate(layoutInflater)
        setContentView(binding.root)
        }

        mAuth = FirebaseAuth.getInstance()

        binding.btnGetOtp.setOnClickListener {

            code = binding.etCountryCode.text.toString().trim()
            number = binding.etMobileNumber.text.toString().trim()
            phoneNumber = code + number

            if (number.isNotEmpty()) {
                binding.etMobileNumber.isEnabled = false
                binding.flOtp.visibility = View.VISIBLE
                binding.btnGetOtp.visibility = View.GONE
                binding.btnSignIn.visibility = View.VISIBLE

                sendVerificationCode(phoneNumber)
            } else {
                Toast.makeText(this, "Please enter a valid mobile number", Toast.LENGTH_LONG).show()
            }
        }

        binding.btnSignIn.setOnClickListener {

            val otp = binding.etOtp.text.toString().trim()

            if (otp.isNotEmpty() || otp.length != 6) {
                verifyVerificationCode(otp)
            } else {
                Toast.makeText(this, "Please enter the OTP received through SMS", Toast.LENGTH_LONG)
                    .show()
            }
        }

    }

    private val mCallBack: PhoneAuthProvider.OnVerificationStateChangedCallbacks =
        object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            override fun onVerificationCompleted(credential: PhoneAuthCredential) {
                val code = credential.smsCode

                if (code != null) {
                    binding.etOtp.setText(code)
                    binding.pbOtp.visibility = View.GONE
                }
            }

            override fun onVerificationFailed(p0: FirebaseException) {

                binding.etMobileNumber.isEnabled = true
                binding.flOtp.visibility = View.GONE
                binding.btnGetOtp.visibility = View.VISIBLE
                binding.btnSignIn.visibility = View.GONE

                Toast.makeText(this@SigninWithPhoneActivity, "Login Failed", Toast.LENGTH_LONG)
                    .show()
            }

            override fun onCodeSent(otpID: String, token: PhoneAuthProvider.ForceResendingToken) {
                super.onCodeSent(otpID, token)

                Toast.makeText(
                    this@SigninWithPhoneActivity,
                    "OTP is send to your number",
                    Toast.LENGTH_LONG
                ).show()
                storedOtpID = otpID
                resendToken = token
            }
        }

    private fun sendVerificationCode(phoneNumber: String) {

        binding.pbOtp.visibility = View.VISIBLE
        Toast.makeText(this@SigninWithPhoneActivity, "Sending OTP", Toast.LENGTH_LONG).show()

        val options = PhoneAuthOptions.newBuilder(mAuth!!)
            .setPhoneNumber(phoneNumber)
            .setTimeout(60L, TimeUnit.SECONDS)
            .setActivity(this)
            .setCallbacks(mCallBack)
            .build()
        PhoneAuthProvider.verifyPhoneNumber(options)

    }

    private fun verifyVerificationCode(code: String) {

        Toast.makeText(
            this@SigninWithPhoneActivity,
            "Verifying credentials",
            Toast.LENGTH_LONG
        ).show()

        val credential = PhoneAuthProvider.getCredential(storedOtpID, code)
        signInWithPhoneAuthCredential(credential)
    }

    private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
        mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {

                    val firebaseUser: FirebaseUser = task.result!!.user!!
                    val userPreliminaryDetails = User(
                        firebaseUser.uid,
                        user_type = "customer",
                        mobile = binding.etMobileNumber.text.toString()
                    )

                    FirestoreClass().checkIfUserAlreadyExist(
                        this@SigninWithPhoneActivity,
                        firebaseUser.uid,
                        userPreliminaryDetails
                    )

                } else {

                    showErrorSnackBar(task.exception!!.message.toString(), true)

                    if (task.exception is FirebaseAuthInvalidCredentialsException) {

                        binding.etMobileNumber.isEnabled = true
                        binding.flOtp.visibility = View.GONE
                        binding.etOtp.text?.clear()
                        binding.btnGetOtp.visibility = View.VISIBLE
                        binding.btnGetOtp.text = "Resend OTP"
                        binding.btnSignIn.visibility = View.GONE

                        Toast.makeText(this, "OTP entered is wrong", Toast.LENGTH_LONG).show()

                    }
                }
            }
    }

    fun userRegistrationSuccess() {
        finish()
        startActivity(Intent(this, ServiceAreaActivity::class.java))
        Toast.makeText(this, "Signed Up successful", Toast.LENGTH_LONG).show()
    }

    fun userSignInSuccess() {
        finish()
        startActivity(Intent(this, ServiceAreaActivity::class.java))
        Toast.makeText(this, "Signed in successfully", Toast.LENGTH_LONG).show()

    }

}

EDIT:
The following function is called to check if the user already exists and accordingly sign in or register a new user.
        fun checkIfUserAlreadyExist(
        activity: SigninWithPhoneActivity, userId: String, userDetails: User
    ) {

        mFireStore.collection("users")
            .whereEqualTo(Constants.USER_ID, userId)
            .get()
            .addOnSuccessListener { document ->
                if (document.documents.size > 0) {
                    activity.userSignInSuccess()
                } else {
                    FirestoreClass().registerUser(activity, userDetails)
                }

            }
            .addOnFailureListener { e ->

            }
    }

    private fun registerUser(activity: SigninWithPhoneActivity, userInfo: User) {

    mFireStore.collection(Constants.USERS)
        .document(userInfo.user_id)
        .set(userInfo, SetOptions.merge())
        .addOnSuccessListener {
            activity.userRegistrationSuccess()
        }
        .addOnFailureListener { e ->
            activity.hideProgressDialog()
        }
}


text:
Q: Height of match_parent not appearing for WebView My WebView can only appear if i set an specific height for example 300dp but does not work for match_parent. I know that is bad to set a specific value for height because devices can change in size.
This is my code:
 <FrameLayout
        android:id="@+id/campaign_mood_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="WebViewLayout">

        <br.test.android.presentation.utils.WebViewYouTubePlayer
            android:id="@+id/campaign_video_mood"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:visibility="gone"
            />

        <ImageView
            android:id="@+id/campaign_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="-1dp"
            android:background="@drawable/place_holder_drawable"
            android:scaleType="fitXY"
            android:transitionName="@string/campaign_image" />

    </FrameLayout>

A: In this case, if you want to set layout_height="match_parent" to your WebView, its parent FrameLayout's layout_height also should be match_parent (or whatever other than wrap_content).
<FrameLayout
        android:id="@+id/campaign_mood_holder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="WebViewLayout">

Also deleting android:visibility="gone" is required.
<br.test.android.presentation.utils.WebViewYouTubePlayer
            android:id="@+id/campaign_video_mood"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a second monitor go off after the connected laptop is closed? I use Ubuntu 18.04.3 gnome laptop with a second monitor connected with HDMI. If I close the lid of my laptop it successfully locks (after I reopen it I have to type my password) but the windows opened on my second screen stay in place. I mean they can be seen after the lid is closed. I want them to go away in that situation (the second screen must go black), how do I do that?

A: If you change the primary display to your Built-In display, it does it automatically. I use a tv as a second monitor and this seemed to work for me. The tv only went blank but did not turn off.

A: If you don't mind a slightly longer startup time, you can set your laptop to hibernate rather than suspend when you close the lid. If you want to try this, you can follow the directions on this article - https://tipsonubuntu.com/2018/04/28/change-lid-close-action-ubuntu-18-04-lts/. I've copied them below.
First, open the terminal and run:
sudo gedit /etc/systemd/logind.conf

In the configuration file that opens up, there should be a line that reads:
#HandleLidSwitch=suspend

You want to change that to:
HandleLidSwitch=hibernate

(Remove the "#" and replace "suspend" with "hibernate")
Afterwards, save the configuration file. For the changes to take effect, go back to your terminal window and run:
systemctl restart systemd-logind.service

Your laptop should then hibernate rather than suspend when you close the lid, and it shouldn't be able to output any image while hibernating.


text:
Q: Why pop_back() method is different in vector and list class? I am studying C++ Standard Template Library and I have noticed something. Here is the code:
int arr[] = {80, 70, 50, 30};
vector<int> ivect(arr, arr+4);

for (int i = 0; i < ivect.size(); i++) {
    cout << ivect.back() << " ";
    ivect.pop_back();
}

The output of this code snipped is this:
30 50

But when I changed the type of ivect to list, for example:
int arr[] = {80, 70, 50, 30};
list<int> ilist(arr, arr+4);
int size = ilist.size(); // Also I don't understand this.
for (int i = 0; i < size; i++) {
    cout << ilist.back() << " ";
    ilist.pop_back();
}

It gives me a proper output:
30 50 70 80

I mean, when I use vector class, it excludes some parts. Why is that happens?

A: Actually, it has nothing to do with using vector instead of list
when you do:
for (int i = 0; i < ivect.size(); i++)
the vector size is evaluated in each iteration. As it decreases with each pop_back, it finishes after two iterations.
On the other hand, when you do
int size = ilist.size();
for (int i = 0; i < size; i++)

the loop condition is fixed to i<4, whether the actual size changes or not.

A: consider this
  for (int i = 0; i < ivect.size(); i++) {
    cout << ivect.back() << " ";
    ivect.pop_back();
 }
//first iteration i=0 to 3; Now after pop_back size reduces by 1
//second oteration i=1 to 2;Now after pop_back size reduces by 1
//3rd iteration i=2 to 1;//loop does'nt execute.

In every iteration you are calculating the size of the vector and size is reduced by 1 everytime.
EDIT: Now since the code is changed,in the list version size is not calculated everytime,hence the different result.

A: Both should work the same, although I think the real issue is that you expect your code to pop all the elements of the vector/list but the way you wrote it, it will actually only pop half the list.
ivect.size() is being evaluated every time through the loop. Since you are popping items off, the size is decreasing, meaning once i is 2, the size will be 2, and the loop will stop. What you need to do is store the size before the loop in some variable.


text:
Q: I want to add data-id="1" data-slug="home" to
* in wordpress actually i want create menu like this in wordpress, i am beginner in wordpress can any one guide how is it possible?

Home

About

Resume

Portfolio

my word press code is this

           <?php
            $args = array(
                'theme_location'=> 'primary'
              );
          ?>

        <?php wp_nav_menu($args);  ?>

A: Before printing, all menu items should run through a filter. You can use wp_nave_menu_items to tack items on to the menu:
// Filter wp_nav_menu() to add additional links and other output

function new_nav_menu_items($items) {
$homelink = '
' . __('Home') . '

';
// add the home link to the end of the menu
$items = $items . $homelink;
return $items;
}
add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );


text:
Q: How detectors in particle colliders can differentiate neutrons from antineutrons? Their mass is the same. None of them interacts with EM fields. And their decay (around 1000s) is far too slow to see their decay products yet in the detector.
How is it then possible to differentiate them?

A: The experiment which has measured the most stringent limit on neutron to anti-neutron oscillations (i.e. produce neutrons, let them fly for some time and then look if you find anti-neutrons) has used a 130 micrometer thick and 110 cm diameter carbon foil. This target had a probability greater than 99% for anti-neutrons to interact (and thus produce secondary particles) and a high transparency for neutrons.
This target was surrounded by a tracking detector (for measuring the momentum of charged particles), scintillator counters and a calorimeter (for measuring the energy of charged and neutral particles). These are used to look for the products of an anti-neutron annihilating with the protons or neutrons of the carbon nuclei (while the neutrons would mostly only scatter elastically, i.e. leave the foil without breaking up).
Admittedly, the neutrons used in this experiment have relatively low energy, 0.002 electronvolt on average, corresponding to a velocity of 600 meters per second.

A: Detectors at particle colliders are layered like onions around the collision vertex.

The CMS detector at CERN

First there  are charged particle sensitive detectors where charged particles leave tracks because of ionisation, but mass density is low so  strong interactions do not happen often;  their momentum can be measured by the curvature in the imposed magnetic field.
Then there are electromagnetic calorimeters, where photons leave their energy and charged particles continue as tracks.
Then come the hadronic calorimeters with a lot of mass so that strongly interacting particles, hadrons, protons neutrons antiprotons antineutrons  deposit their energy.  Protons will have a continuous path up to the hadronic calorimeter due to their charge. Antiprotons will have negative charge. Neutrons will deposit energy without a previous track trace. Antineutrons will also deposit energy without a track, except due to the annihilation with matter the shower will be more energetic.
At LHC energies the difference in the multiplicity due to the annihilation for antineutrons will not be distinguishable. At low energies , antineutrons have higher multiplicity showers.
Generally in colliders the existence of antineutrons  might be guessed at by conservation of charge and baryon numbers, in low  multiplicity events.


text:
Q: Inequality on Trigonometric polynomials My question comes from trying to understand a technical step in this paper by Bourgain.
Let $R,L$ be positive integers and let $f(x)=\sum_{|n|\leq RL}a_ne^{2\pi inx}$ be a trigonometric polynomial. Assume $f(x)>0$.
Let $F_L(x)=\sum_{|n|\leq L}\frac{L-|n|}Le^{2\pi inx}$ be the Fejer kernel.
Define (as usual) the convolution
$$(f*F_L)(x)=\int_0^1f(t)F_L(x-t)dt=\sum_{|n|\leq L}a_n\frac{L-|n|}Le^{2\pi inx}$$
Does it follow (and how) that
$$f(x)\leq10R(f*F_L)(x)$$?
In the paper we have a concrete $f(x)$, so maybe this is not true in general. There we have
$$a_n=1-\cos\left(2\pi\frac{RL-|n|}N\right)$$
where $N$ is a large positive integer, (at least bigger than $4RL$).

A: That is true for all non-negative trigonometric polynomials, though not entirely obvious unless you are a Fourier analyst yourself. To see it, just note that the convolution with $K_{RL}=2F_{2RL}-F_{RL}$ recovers $f$ faithfully and $F_{RL}\le RF_L$. Of course, to Jean such things are as obvious as $2\times 2+1=5$ (he writes $10$ instead of $5$ just out of the traditional analyst's habit to have a 100% security margin in the constants), but I agree that it may be a bit perplexing for poor mortals like you and me. Joe Diestel just told me at a beer party tonight that the most common phrase in Bourgain's early papers was "By standard techniques we conclude from here that". :)


text:
Q: UIViewController may not respond to methodName::: I'm trying to use methods to pass values from text fields in one view to corresponding text fields in another view. The action valuesChanged is wired to the event "Editing Did End" on the text fields. I tried using "Value Changed" with similar results (it doesn't work.). The only warning I receive is in a method call.
Here's the code for the VolumeViewController:
@implementation VolumeViewController

@synthesize boxWidth;
@synthesize boxHeight;
@synthesize boxLength;
@synthesize sphereRadius;
@synthesize boxResult;
@synthesize sphereResult;
@synthesize areaViewController;

-(IBAction)valuesChanged:(id)sender
{
    NSString *length = boxLength.text;
    NSString *width = boxWidth.text;
    NSString *radius = sphereRadius.text;

    NSLog(@"length: %@", length);
    NSLog(@"width: %@", width);
    NSLog(@"radius: %@", radius);

    [areaViewController changeValues:width :length :radius];
}

-(void)changeValues:(NSString*)widthString :(NSString*)lengthString :(NSString*)radiusString
{
    boxWidth.text = widthString;
    boxLength.text = lengthString;
    sphereRadius.text = radiusString;
}

As you can see, the valuesChanged action instantiates three NSString objects, each corresponding to the text properties of a text field. These strings are then passed to the changeValues method of the areaViewController. The areaViewController's changeValues method is identical to the volumeViewController's method, other than the text field names being different. However, the NSLog commands that I have never show anything in the console, so it's obvious that despite my text fields being connected to the action, it is not being called. What do I need to fix?
The warning is given after the method call "[areaViewController changeValues:width :length :radius], and it reads 'UIViewController' may not respond to '-changeValues:::'

A: Define the method it in your header.

A: What you can do to "declare" it in .m an not in .h (because it's kind of a private method for you, and it should not visible from outside) is add this before @implementation VolumeViewController :
@interface VolumeViewController()

- (void)changeValues: : : ;

@end

EDIT: It's better to name all the arguments in your method name. The signature should be:
-(void)changeWidth:(NSString*)widthString lenght:(NSString*)lengthString radius:(NSString*)radiusString;
This is more readable when you use it:
[areaViewController changeWidth:@"4" length:@"2" radius:@"6"];

A: You are calling changeValues on areaViewController, but you have defined that method for the VolumeViewController class
Try changing [areaViewController changeValues:width :length :radius];
to [self changeValues:width :length :radius];


text:
Q: how to include jquery library to a pure javascript file script to create a node server(node_server.js) , i want to include jquery library to that file.
i want to use jquery in this file ,  how to include jquery library to this javascript file ,
note that , i am not including this file to a view , this is a node server written in javascript .
part of my server
var server = http.createServer(function (request,response)
{
    var pathRegex = new RegExp('^/publish/?$');
    var pathname = url.parse(request.url).pathname;

    if (pathRegex.test(pathname)) {
       publish(request, response);
    } else {
       render404(request, response);
    }
});

A: Seeking a new maintainer, but you might give node-jquery a try. See also the SO thread "Can I use jQuery with node.js?"


text:
Q: cURL Mail Attachment (Imagines, .exe file, .rar/.zip files) I was wondering if I can send different type of files to an email as an attachments. I only know how to send a text file using cUrl. Could someone give me some examples of how can I accomplish my goal ?
This is what I have so far :
curl --url "smtps://smtp.gmail.com:465" --mail-from "mail.gaming@gmail.com" --mail-rcpt "mail2@gmail.com" --ssl --user "mail@gmail.com:password" --upload-file "C:\Folder\File.txt"

Thank you for all the effort !

A: You can use multipart/mixed content to transmit your text body and each of your binary attachments.
Here is a template of file you could use to display a text file and attach 2 binary files :
From: Some Name <sender@gmail.com>
To: Some Name <receiver@gmail.com>
Subject: example of mail
Reply-To: Some Name <sender@gmail.com>
Cc:
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MULTIPART-MIXED-BOUNDARY"

--MULTIPART-MIXED-BOUNDARY
Content-Type: multipart/alternative; boundary="MULTIPART-ALTERNATIVE-BOUNDARY"

--MULTIPART-ALTERNATIVE-BOUNDARY
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: base64
Content-Disposition: inline

This is an email example. This is text/plain content inside the mail.
--MULTIPART-ALTERNATIVE-BOUNDARY--
--MULTIPART-MIXED-BOUNDARY
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="file.rar"
<HERE BASE64 ENCODED RAR FILE>

--MULTIPART-MIXED-BOUNDARY
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="file.zip"
<HERE BASE64 ENCODED ZIP FILE>

--MULTIPART-MIXED-BOUNDARY--

Note that the binary files are encoded in base64 and are transmitted as attachment.
Here is an example of building this file and send the email with a bash script :
#!/bin/bash

rtmp_url="smtp://smtp.gmail.com:587"
rtmp_from="sender@gmail.com"
rtmp_to="receiver@gmail.com"
rtmp_credentials="sender@gmail.com:secretpassword"

file_upload="data.txt"

echo "From: Some Name <$rtmp_from>
To: Some Name <$rtmp_to>
Subject: example of mail
Reply-To: Some Name <$rtmp_from>
Cc:
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=\"MULTIPART-MIXED-BOUNDARY\"

--MULTIPART-MIXED-BOUNDARY
Content-Type: multipart/alternative; boundary=\"MULTIPART-ALTERNATIVE-BOUNDARY\"

--MULTIPART-ALTERNATIVE-BOUNDARY
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: base64
Content-Disposition: inline

This is an email example. This is text/plain content inside the mail.
--MULTIPART-ALTERNATIVE-BOUNDARY--
--MULTIPART-MIXED-BOUNDARY
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"file.rar\"" > "$file_upload"

# convert file.rar to base64 and append to the upload file
cat file.rar | base64 >> "$file_upload"

echo "--MULTIPART-MIXED-BOUNDARY
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"file.zip\"" >> "$file_upload"

# convert file.zip to base64 and append to the upload file
cat file.zip | base64 >> "$file_upload"

# end of uploaded file
echo "--MULTIPART-MIXED-BOUNDARY--" >> "$file_upload"

# send email
echo "sending ...."
curl -s "$rtmp_url" \
     --mail-from "$rtmp_from" \
     --mail-rcpt "$rtmp_to" \
     --ssl -u "$rtmp_credentials" \
     -T "$file_upload" -k --anyauth
res=$?
if test "$res" != "0"; then
   echo "sending failed with: $res"
else
    echo "OK"
fi

The received email will have the inline text/plain document and both of attachment document of type application/octet-stream :


text:
Q: Retrieving Activity Feed: Firebase After doing a bit of research it seems Firebase isn't very well suited to perform a task such as activity feed, being there is no IN operator like MySQL has.
My question is, wouldn't activity feed become quite expensive or time consuming to carry out with Firebase since you would have to make a loop and query each individual User ID in an array of the user ID's of the people someone follows to find recent posts that those people have made.
I couldn't find much information on the cons of using Firebase for a feed model. Maybe I am misunderstanding how Firebase operates but this just seems very inefficient on a large scale. Would it be probable to use MySQL to carry out this task?
Thanks,
Troy

A: If you come from a background with relational databases, Firebase's NoSQL data model may take some getting used to. Most assumptions about its limited scalability are based on that lack of experience. Once you adapt to the NoSQL data model of Firebase Realtime Database or Cloud Firestore, they can scale to quite extreme number of concurrent reads.
I recommend:

*

*reading NoSQL data modeling.

*watching Firebase for SQL developers (made for the Realtime Database, but a lot also applies to Cloud Firestore).

*watching Todd's new video series for Cloud Firestore (episode 1 and episode 2).


text:
Q: Returning variable-width data by value in C I'm looking for a way to write a function in C that returns a string of bytes by value. I know that this is usually solved by allocating from the heap, or by making the caller pass a pointer to some buffer. However, in my case, the function must not do any heap allocations for performance reasons (so no malloc, just alloca), and the string length is determined by the function, so there's no way for the caller to know how much space to allocate for it, and there is no defined maximum length either. I also can't split the function into two halves; one that determines the length and one that generates the string.
In short, the callee must be the one that determines the length, allocates the string on stack and fills it. When the function returns, the caller may need to do some fancy stuff in order to store the string safely, but again, it must be stored on the stack, and without calling the function multiple times.
I know this isn't good practice, this would only be used in computer-generated C code. I don't suppose this can be done in "safe" standard C, since everything allocated on the stack is scoped and dies on scope exit. But in reality, those values are still somewhere on the stack (at least until they are overridden), even though the C standard says that reading them is undefined behavior. Does anybody know some good way to do this on x86/x86_64?

A: This is not solvable in C. Once the function exits, all stack-allocated variables are obliterated. You might be tempted to return a pointer to alloca()-provided address from your function, but that would squarely put you into undefined behavior, and you will be a fair game for optimizer.

A: Don't ever do this, it's nasty.  The way snprintf(3) works is usually good (see below)
I did manage to achieve this under limited circumstances (user-space code on Linux, with some empty inline-asm statements to defeat the optimizer, see implementation below), by having the caller claim the returned buffer (below its stack pointer) with its own alloca.  This expands the caller's stack frame to include the buffer (i.e. puts RSP below it), in a way that the compiler knows about/understands, preventing it from synchronously clobbering your data.
The major weakness is that your data is below ESP/RSP temporarily.  You need to avoid asynchronous clobbering of the data by avoiding signal handlers entirely, or using an alternate signal stack (so you have an effectively infinite red-zone).  If you can't do that (e.g. in kernel code where interrupt handlers will use the current stack), you can't avoid a window of vulnerability where your data below ESP/RSP could be asynchronous clobbered.  (i.e. you can't use this.)
Without an infinite red-zone, I think the only way to really do this is to write both the caller and callee in assembly language, so the caller is expecting the callee to return with a different RSP.  (Normally, RSP is call-preserved, and copying the return address somewhere else before running a RET instruction will break things.)
@DavidHoltzer suggests that you might manage to do something with inline-asm, but messing around with the caller's EBP and returning with ESP modified will only work if you force the compiler to make a stack frame with EBP in the caller, and somehow make sure it doesn't make any assumptions about ESP relative to EBP.  Maybe if the caller is simple, and you use __attribute__((noinline))...

The only truly portable / safe way:  cheat.  Turn your whole "function" into a macro.  You can use alloca (or a C99 variable length array).  Since it's a macro, it happens inside the "caller".
alloca stays valid until the end of the function, not just the scope (like a C99 VLA), so you could use a GNU C statement-expression to have a macro you can use as char *p = MY_INSANE_MACRO(arg1, arg2);

The "normal" way to do this is the way snprintf(3) works:

*

*function takes a buffer and a size as args.

*If the data fits in the buffer, all is good and it returns the size.

*If the data doesn't fit, it returns the size of buffer required.  (snprintf fills the buffer up to the end with truncated output, but if the caller is always going to retry, you could just leave the contents undefined.)

*Normally the caller just passes a buffer that's big enough the first time (based on a rough estimate, or just a constant size that's usually good), and everything works with no retry.  In computing, small numbers are extremely common, and optimizing for the small-number case is usually a win.

Tested and working solution, if my assumptions are correct
I think signal-handlers are the only thing that can asynchronously clobber the stack in a Linux user-space process.  By using a separate stack for signal handlers, you may be able to have an arbitrary-size red-zone.  Glibc supports the 4.4BSD sigaltstack API.
See the code + asm on the Godbolt compiler explorer.  It runs and works, and more importantly I've inspected the asm output to verify that it does what I wanted it to, so this should actually be safe.  I can't guarantee that it won't break as part of a more complicated program, or with a more complex return_stackmem, though.
The padding constants might not be big enough, and there might be an alternate way of making sure the space is big enough.
Without the DEFEAT_OPTIMIZER usage in both places, important parts of this really did optimize away.  Have a look on Godbolt!
DEFEAT_OPTIMIZER gives its operand as an input to an inline asm block with a "memory" clobber.  Since the compiler doesn't try to understand the inline asm code (in this case the empty string: zero instructions), it has to have any memory the inline asm might read or write in a consistent state that matches the state of the C abstract machine at that point.  (This always includes the memory pointed to by input operands, and sometimes global variables).  See also Chandler Carruth's CppCon 2015 talk about microbenchmarking with perf, where he uses the same technique in a macro called ESCAPE to similarly stop the compiler from optimizing away work it thinks isn't necessary.
/*****   PLEASE DO NOT EVER DO THIS IN REAL CODE.
*** This relies on a bunch of platform-specific and optimizer-specific hacks.
**  It might compile to asm that's 100% safe now, but on a future compiler
**  or a different platform, or with some source changes, it might not.
***/

#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

// you might have seen a macro like this called ESCAPE
#define DEFEAT_OPTIMIZER(p)  asm volatile("" : : "g" (p) : "memory")

// writing this function in assembly language might be necessary to grow the buffer on the fly,
// if it's not possible to work out ahead of time how big it needs to be.

__attribute__((noinline))   // otherwise the strcpy just inlines into the caller (and optimizes away without DEFEAT_OPTIMIZER)
char *return_stackmem(char *input, uint32_t *bufsize)
{
    // Figure out the buffer size somehow;
    *bufsize = 1234;
    // Allocate some padding at the top to make sure the caller doesn't step on
    // any part of the buffer we will use.  Hopefully 128B is enough...
    char *buf = alloca(*bufsize + 128);

    // store into buf;
    strcpy(buf, "abcdefghijklmnopqrstuvwxyz");

    // clang normally optimizes away the strcpy because according to C rules,
    // the buffer is dead before anything can look at our return value
    // current gcc doesn't do that, but this is definitely a good idea.
    DEFEAT_OPTIMIZER(buf);
    return buf;
}

void insane_caller(char *input)
{
    uint32_t bufsize;  // not size_t because 4GB is already more than will work.
    char *buffer_below_the_stack = return_stackmem(input, &bufsize);

    // alloca another buffer that entirely covers the first one, placing RSP below the buffer
    char *claim_the_space = alloca(bufsize + 256);    // some extra padding, since the buffer probably wasn't right at the top of the callee's stack frame.
    DEFEAT_OPTIMIZER(claim_the_space);  // make sure the alloca really happens
    assert(claim_the_space < buffer_below_the_stack);
    char *safe_buffer = buffer_below_the_stack;

    printf("safe to make further function calls now, and do stuff like print the buffer: %s\n", safe_buffer);
    // returning destroys all the alloca()ed memory
}

int main(int argc, char**argv) {
    stack_t altstack = { .ss_sp = malloc(SIGSTKSZ), .ss_size = SIGSTKSZ, .ss_flags = 0 };
    sigaltstack(&altstack, NULL);  // error checking not shown, and I may have misread the docs on this
    // or make sure you never install any signal handlers.

    insane_caller(argv[1]);
}

peter@tesla:~/src/SO$ gcc -std=gnu11 -O3 buffer_below_the_stack.c
peter@tesla:~/src/SO$ ./a.out
safe to make further function calls now, and do stuff like print the buffer: abcdefghijklmnopqrstuvwxyz

A: How about using a static char* inside the function, and then malloc() memory to hold the string?
char* foo(some args, I guess)
{
    static char *str;
    ...
    if ((str = malloc(somelen)) == NULL)
        return NULL;

    ....
    return str;
}

It's not a good solution, but at least it's legal C.


text:
Q: Induced group action of the left regular representation strongly continuous Let $G$ be a compact group and let $\lambda: G \rightarrow \mathcal{U}(L^2(G))$ be the left regular representation, i.e. $\lambda_sf(t)=f(s^{-1}t)$. Why is the  induced group action $\overline{\lambda}:G \rightarrow \mathrm{Aut}(\mathcal{K}(L^2(G)))$, $\overline{\lambda}_s(T)= \lambda_s T\lambda_{s^{-1}}$ strongly continuous?
Thank you.

A: Let $g_j\to g$ a convergent net in $G$ and let $T\in\mathcal K$. We need to show that $\lambda_{g_j}T\lambda_{g_j^{-1}}$ converges to $\lambda_g T\lambda_{g^{-1}}$ in the strong topology. Now $\lambda_{g_j}$ converges to $\lambda_g$ strongly, i.e., $\lambda_{g_j}f$ tends to $\lambda_gf$ in the $L^2$ norm. This is seen for continuous $f$ by uniform convergence and for general $f$ by $L^2$-approximation with continuous functions. Now  write $$
\lambda_{g_j}T\lambda_{g_j^{-1}}f-\lambda_{g}T\lambda_{g^{-1}}f
=(\lambda_{g_j}T\lambda_{g_j^{-1}}f-\lambda_{g_j}T\lambda_{g^{-1}}f)
+(\lambda_{g_j}T\lambda_{g^{-1}}f-\lambda_{g}T\lambda_{g^{-1}}f)
$$
and use the triangle inequality as well as the fact that $\lambda_g$ preserves norms.


text:
Q: Changing column name in SQL Server 2000 Is there a way to change a column name in sql without having to recreate the table?
I've tried alter table dbo.Conforming rename column [xxx] to [xxx] and it doesn't work.  any other ideas?

A: use sp_rename:
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO


text:
Q: MySQL CONCAT add comma after I am struggling to get comma after value but this query is adding before value
ipaddress = CONCAT(IFNULL(ipaddress,''), ',$ipaddress')

The field's default value is NULL
Even I have tried this too but result is the same. Adding comma before not after.
ipaddress = CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress')

A: Use the CONCAT_WS function. It inserts the separator between items, but ignores null items.
ipaddress = CONCAT_WS(',', ipaddress, '$ipaddress')

So if ipaddress is initially null, it will be ignored, so this won't put the separator between it and the added $ipaddress value.
However, the fact that you need to do this suggests that you're putting a comma-separated list into a SQL column. This is very poor design. You should normalize your schema, and move this to a separate table with a separate row for each value, and a foreign key relating back to this table.

A: If ipaddress is NOT NULL then the string is formatted correctly.
E.g. 127.0.0.1,127.0.0.2

In case where ipaddress IS NULL, the string will look like
,127.0.0.2

You can use MySQL's TRIM function to fix this.
 TRIM(LEADING ',' FROM CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress'))
 TRIM(LEADING ',' FROM CONCAT(IFNULL(NULL,''), ',', '127.0.0.2'))

Hope this helps!


text:
Q: How do I get the Array value using Codeigniter I have this select
    $this->db->select('modulo_regra.regra_descricao');
    $this->db->from('modulo_regra');
    $this->db->where('modulo_regra.modulo_regra_id', id);
    $query = $this->db->get();

that return to me 2 elements in
  return $query->result_array();

Then I put the return in a Array
   $permissoes =array('areas' => $this->Regra_model->user_has($regra['regra_id']));

then I the $permissoes  to the session
   $this->session->set_userdata($permissoes);

So the real problem comes here.
when I'm loading the value from session
   $permissoes = array('areas');
   $permissoes = $this->session->userdata('areas');

this is its content:
array(2) ([0] => array(1) ([regra_descricao] => (string) clientes_cadastrar)
          [1] => array(1) ([regra_descricao] => (string) clientes_visualizar))

So i can't validate it with the in_array(), or other way...I would like to know if there is how if there is away to compare  the value in this array with one another variable
like
if(in_array('clientes_cadastrar',$permissoes)){}

I'm new on it... so sorry for the way i ask.

A: don't put entire array in return i.e
foreach ($query->result() as $row)
{
   $return[] = $row->regra_descricao;
}
return $return;

THEN
you can easily find using:
if(in_array('clientes_cadastrar',$permissoes[**'areas'**])){}

hope this helps

A: U can use the same scope.
 $this->db->select('modulo_regra.regra_descricao');
     $this->db->from('modulo_regra');
     $this->db->where('modulo_regra.modulo_regra_id', id);
     $query = $this->db->get();

    foreach ($query->result() as $row)
    {
       $permissoes = array['areas'];
    }

    $this->session->set_userdata($permissoes);


text:
Q: Microsoft Teams cloud calling/graph-is there a way to have a bot add a PSTN participant to a meeting? Using the C# calling SDK for Graph, I can join a bot to a meeting, and add participants by GUID from the same tenant.  Where this falls apart though is adding a participant from PSTN/direct routing.  If I have a regular user add a participant, I see this update:
          "@odata.type": "#microsoft.graph.participant",
          "info": {
            "@odata.type": "#microsoft.graph.participantInfo",
            "identity": {
              "@odata.type": "#microsoft.graph.identitySet",
              "phone": {
                "@odata.type": "#microsoft.graph.identity",
                "id": "+19054181287",
                "identityProvider": "None"
              }
            },
            "endpointType": "default"
          },

Seems reasonable enough, so I tried adding a participant like this:
            InvitationParticipantInfo target = new InvitationParticipantInfo { Identity = new IdentitySet(), };
            target.Identity.SetInAdditionalData("phone", new Identity() { Id = targetID });
            target.Identity.AdditionalData["phone"].SetInAdditionalData("tenantId", m_tenantID);
            target.Identity.AdditionalData["phone"].SetInAdditionalData("identityProvider", "None");
            target.EndpointType = EndpointType.Default;
            await call1.Participants.InviteAsync(new List<InvitationParticipantInfo>() { target });

Which generates a request that looks like this (interesting that the identityProvider changed):
"participants": [
    {
      "@odata.type": "#microsoft.graph.invitationParticipantInfo",
      "identity": {
        "@odata.type": "#microsoft.graph.identitySet",
        "phone": {
          "@odata.type": "#microsoft.graph.identity",
          "id": "+19054181287",
          "tenantId": "8c6ae172-a3ea-4f50-994d-a0256822697f",
          "identityProvider": "(Generic: l3QstqQ1)"
        }
      },
      "endpointType": "default"
    }

And that comes back with this:
Action failed: 81bd4426-7200-4c50-acba-f17b7a987322
exception: Code: 7505
Message: Request authorization tenant mismatch.
Scenario Id: 46ffbff3-bf9f-4b6d-a639-974c07b959dc
Inner error:
    AdditionalData:
    date: 2020-10-13T18:45:30
    request-id: 5d152942-dc10-4baa-bb28-48bf991f944b
    client-request-id: 83f84370-3708-4e3c-a34d-2f69bd8eb8a7

Given that the meeting organizer has permissions for PSTN dialout, as do invitees, is there a reason that a bot shouldn't be able to add a participant like this?  What's interesting is that something very similar does work for redirecting/transferring incoming PSTN calls.  The "Request authorization tenant mismatch" seems like a red herring (since it's all the same tenant)-is this just a case of "not supported right now"?  I know PSTN calls from bots are (still) not officially supported, but I was curious whether anyone had a way to make this work?


text:
Q: Storage Event Trigger does not work when I upload file in Datalake using Azure Function I have created a storage event trigger to trigger a pipeline in Azure Data Factory. This trigger works when I manually put a file in the datalake. But when the file is uploaded from Azure Function, trigger doesn't work.
Below is my function to upload file in datalake.
public void UploadFileToDatalake(FileUpload file, string containerSasUri, string stage, string dir, ILogger log)
        {
            log.LogInformation("inside uploadFileTodatalake");
            UriBuilder sasUri = new UriBuilder(containerSasUri);
            DataLakeServiceClient dataLakeServiceClient = new DataLakeServiceClient(sasUri.Uri);

            string container = Globals._transientContainer;
            var fileSystemClient = dataLakeServiceClient.GetFileSystemClient(container);

            string pathFileDL = file.Name;

            string directory = dir;

            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(File.ReadAllText(file.FullPath));
            sw.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            file.Content = ms;

            DataLakeDirectoryClient directoryClient = fileSystemClient.GetDirectoryClient(directory);
            try
            {
                if (directoryClient.Exists())
                {
                    log.LogInformation(directoryClient.Name);
                    DataLakeFileClient fileClient = directoryClient.CreateFile(pathFileDL); // 0kb blob
                    file.Content.Position = 0;
                    fileClient.Upload(file.Content, true);
                    log.LogInformation($"{stage}: {file.Name} uploaded to {pathFileDL}");
                    file.Content.Close();
                }
            }
            finally
            {
                //fileSystemClient.Delete();
            }
        }

FileUpload is a model class I am using.
public class FileUpload
    {
        public string Name { get; set; }
        public Stream Content { get; set; }
        public string FullPath { get; set; }
    }

Thanks in advance.

A: I am tried with the blog  for upload a file in azure blob using azure function.
Before creation of azure function, I was created the pipeline Storage Event Trigger to get trigger when the new file arrives/created on storage blob.
Tried with manually to uploading a file using azure portal. The event grid triggered.
After created and published the azure function on azure. Now run the azure function. It generates the random files on storage container and the expected Storage Event Trigger also run. I can see the Triggered output on the portal.

A: By using ADLS FileClient, you should set Close option to true. Then the Storage Event will be sent yet another time after the upload stream was closed.
        var options = new DataLakeFileUploadOptions();
        options.Close = true;


text:
Q: how to clone input type file content? I have this input typed file, when a user uploads a photo(not submit), it clones this photo and appends it to the div
<input type="file" class="upload"></input>
<button class="submit"></button

A: On your input change use the FileReader object and read your input file property:

$('.submit').on('click', function() {
    $(this).hide();
    var preview = $('img');
    preview.show();
    var file = $('input[type=file]').prop('files')[0];
    var reader = new FileReader();
    reader.addEventListener("load", function() {
        preview.attr('src', reader.result);
    }, false);
    if (file) {
        reader.readAsDataURL(file);
    }
});

<input type="file" class="upload"/>

<button class="submit">Submit</button>


text:
Q: Any tool for video card memory scan? Can someone please suggest any tool for scanning memory (RAM) of a video/graphic card? All I can find are some very old programs that do not support modern cards as they, for example do not support more than 512MB RAM (I have 3GB) or demand to change the video mode to 640x480 and my card does not support so small resolution under Windows. It can be for Windows or Linux. Please be aware I have AMD/ATI card so tools using CUDA will not work. Also, I am not interested in video benchmarking but solid memory testing.

A: Did you try this program -- http://mikelab.kiev.ua/index_en.php?page=PROGRAMS/vmt_en ? There are two links, at the top and at the bottom. Use the one at the top, the one at the bottom contains a floppy image, that's not what you need. In the archive there are "windows version" and an iso image in the VMTCE folder. According to the readme file if you boot from the image you won't be able to address more than 512 MB, but "windows version" should work.
I can't recommend this program since I never used it. I just happen to know of its existence.
Also if it won't work please indicate what tools you have already tried.

A: Have you tried either MemtestCL from Stanford University's Folding@home project? If your card supports OpenCL, then you should be covered by MemtestCL. MemtestCL is supported under both Linux and Windows, while MemtestG80 (for CUDA cards) supports Linux, Windows and OS X.
Like @Gelo Mitt says, I can't recommend either one, but hope it helps somewhat.


text:
Q: How to Remove Old NuGet Packages I am using the public NuGet server and when I click at the solution and Manage Nuget Packages I can see a number of packages which are older versions of packages that are also installed. When I click "Manage" I can see the older package is not installed on any project in my solution but I do not get the option of removing it. Meanwhile the latest package is installed on a number of projects and is being referenced and used just fine.

A: The NuGet.org website doesn't provide a way to remove a package that's been posted.  The reason is that we don't want to accidentally break any existing projects that may be using the older version, or force existing users to upgrade their packages.
We do understand that there are special circumstances and reasons to make an exception to this rule, though.  If you need an old package to be removed, you can drop us a line using the "Report Abuse" form on the website with the reason you need the package to be removed, and one of the site's administrators will review it.


text:
Q: Destroying particle systems In my game there is a ball hits a coin then the coin disappeared and a particle system is initialized.
my problem is to destroy the particle system i tried to write
Destroy(effect.gameObject)

but i got an error message tell me that there is no definition for gameObject.
my unity version is 4.6.3
Help will be appreciated.
this is my code
public class CoinDestroyer : MonoBehaviour {
   public Transform coinEffect;
   void OnTriggerEnter (Collider other){
       if (other.tag == "Player"){
           var effect = Instantiate(coinEffect, transform.position, transform.rotation);
           Destroy(effect.gameObject, 3);
           Destroy(gameObject);
       }
   }
}

A: Instantiate returns an object of type Object, the top class in Unity (not the .NET type). Since you use var effect, the compiler is fine making effect an Object. But you need a GameObject since Object has no gameObject member.
var effect = (GameObject)Instantiate(coinEffect, transform.position, transform.rotation);

This is one of the danger of using var instead of strongly type variables. Best would be:
GameObject effect = (GameObject)Instantiate(coinEffect, transform.position, transform.rotation);

In this case, if the cast is missing the compiler will throw an error complaining that Object cannot be GameObject and you need a cast.
I only use var in cases I am 100% sure of the type and it is a long one to write like KeyValuePair<string,List<GameObject>>, else, always the right type.

A: The error you're getting is because the object containing effect is destroyed, I recomiedo you use a script within the system of particles insideof the  script should give a life time with the following script:
lifeTime = 1.0f
void Start() {
    Invoke ("SelfDestruct", lifeTime);
}


text:
Q: What is the best approach for storing persistent information in android app I am a beginner on android development. I want to save user details on android device. my application has a registration facility. I want to restrict only one user per device. If the user uninstalled the application and reinstalled it should take the previous user already registered with this device until the device is formatted. So for this purpose I want to store the user details inside the device and the user should not be able to clear the details until the device is formatted.
I am searching for solution something similar to iOS keychain concept, but it is not mandatory to save as encrypted.
Requesting experts help.

A: The better approach would be not to store that information on the user's device. You can store the details of the user on your server, and make use of the various device identifiers to determine if the user exists.
For example, you can use instanceID (which identifies unique app installations), along with IMEI (burned onto the hardware) to determine if it's the user's first install.
More info:
https://developer.android.com/training/articles/user-data-ids.html


text:
Q: Incomplete JSON string is returned from PostgreSQL The following SQL statement returns a single row (a JSON string)
Select jsonb_build_object(
    'type',     'FeatureCollection',
    'features', jsonb_agg(feature)
)
    FROM (
        SELECT json_build_object(
            'type',       'Feature',
            'properties', json_build_object(
                'cell', cell,
                'value', value
            ),
            'geometry', ST_AsGeoJSON(geom)::json
        ) as feature
            from (
                select dgg.*, trunc(random() * 9 + 1) as value
                    FROM mj_dgg_regions_BB($1, $2, $2, $3, $4) as dgg) row
    ) features

If I put this statement in a function (see below), the resulting JSON string is incomplete
CREATE OR REPLACE FUNCTION mj_dgg_regions_BB_geojson(res int, xmin float, ymin float, xmax float, ymax float)
RETURNS json AS $$
begin
return(
Select jsonb_build_object(
    'type',     'FeatureCollection',
    'features', jsonb_agg(feature)
)
    FROM (
        SELECT json_build_object(
            'type',       'Feature',
            'properties', json_build_object(
                'cell', cell,
                'value', value
            ),
            'geometry', ST_AsGeoJSON(geom)::json
        ) as feature
            from (
                select dgg.*, trunc(random() * 9 + 1) as value
                    FROM mj_dgg_regions_BB($1, $2, $2, $3, $4) as dgg) row
    ) features
);
end;
$$ LANGUAGE plpgsql;

The result is again a single row containing a JSON string. However this string does not contain all the entries that the first statement (no function) contained.
Since there is no error message, I am a bit lost.
EDIT 1:
To rule out problems with psycopg2 and DBeaver I tried it with psql
psql -U USER -d DATABASE -c "copy (select mj_dgg_regions_BB_geojson(4, 10, 10, 60, 60)) to stdout;"

This returns the same truncated result. Calling the statement alone returns the correct (full length) JSON string, calling the function does not. My guess is, therefore, that the function is not correct.
EDIT 2:
mj_dgg_regions_bb() is essentially a spatial query.
CREATE OR REPLACE FUNCTION public.mj_dgg_regions_bb(res integer, xmin double precision, xmax double precision, ymin double precision, ymax double precision)
 RETURNS TABLE(cell bigint, geom geometry)
 LANGUAGE plpgsql
AS $function$
BEGIN
        RETURN QUERY
        SELECT dgg.cell, dgg.geom::geometry FROM regions as dgg
        where dgg.res = $1
        and
        dgg.geom::geometry &&
            -- && -- intersects
            -- @ -- contained by
        ST_MakeEnvelope (
            $2, $3, -- bounding
            $4, $5, -- box limits
            4326);
END;
$function$

Is it possible that there is a timeout for functions? The spatial query may take a couple of seconds (spatial index is set).


text:
Q: iOS project transfer from xcode11 to xcode14 I had project which is working all good in xcode11 but when i open and try to run the project xcode13 or xcode14 it gives be below error
Steps i did to solve it:
1) Clear the build
2) Delete Derived Data
3) Xcode13 -> File -> Workspace settings -> Change to New Build System instead of Legacy Build system (Legacy build system is depricated)
4) Build Phases -> Copy Bundle Resources -> check if there are duplicate files exist.

error build: Multiple commands produce '/Users/Username/Library/Developer/Xcode/DerivedData/Project-ekfgusdfwerwe wercemqfyjckxycw/Build/Products/Debug-iphonesimulator/projectTest.app/Model.cdm'

Please help me


text:
Q: Cron job fails due to sleeping wifi? I wrote a cron job to do backups over wifi to another computer. It works perfectly when I'm using the machine, but I prefer to schedule it at night when I'm not using it. The first step is to ping the backup server once and fail the whole script if that step fails.
It consistently fails. :(
I've got Energy Saver set to never sleep (when plugged in).
Does OS X always put the wifi to sleep after a certain time or something? Does it not wake it up for cron jobs? Or maybe it does, but I just need to wait for it to connect?
Update: @bmike asked about my pmset -g log output. I use terminal-notifier to send a notification.
2015-05-13 16:05:23 -0700 Assertions            PID 56(powerd) TimedOut InternalPreventDisplaySleep "com.apple.powermanagement.delayDisplayOff" 00:09:22  id:0x100000032b [System: DeclUser IntPrevDisp kDisp]
2015-05-14 00:00:01 -0700 Assertions            PID 552(NotificationCen) Created DisplayWake "com.apple.notificationcenter.sleeping-note" 00:00:00  id:0xe00000bc1 [System: DeclUser DispWake kDisp]
2015-05-14 00:00:11 -0700 Assertions            PID 552(NotificationCen) Released DisplayWake "com.apple.notificationcenter.sleeping-note" 00:00:10  id:0xe00000bc1 [System: DeclUser kDisp]

A: I have solved this indirectly in the past several times like this:
One Mac (the one that is supposed to never sleep) has a Energy Saver schedule to wake up or power on every morning at 2:55 AM. It's set to not sleep, but it also has launchd jobs (cron is fine too if you want to maintain that older scheduling method) that SSH in to the client Macs.
The client Macs are set to allow wake for remote access, allow Power Nap (if supported) and set to allow SSH.
We have several AirPort and AppleTV that will proxy the ssh requests and send a wake packet to the client macs if they happen to be sleeping.
The clients then can have their cron tasks scheduled for when they wake.
If you spend too much time making this work, you can instead put a backup hook into the periodic tasks or convert them to launchd and have them run opportunistically even when the ideal scheduled time has passed.


text:
Q: Canvas demo (runwithfriends) always redirects to main page under my own GAE I'm using the runwithfriends example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files:
conf.py:
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ''
FACEBOOK_APP_SECRET = ''

# Canvas Page name.
FACEBOOK_CANVAS_NAME = 'blah'

# A random token for use with the Real-time API.
FACEBOOK_REALTIME_VERIFY_TOKEN = 'RANDOM TOKEN'

# The external URL this application is available at where the Real-time API will
# send it's pings.
EXTERNAL_HREF = 'http://blah.appspot.com'

# Facebook User IDs of admins. The poor mans admin system.
ADMIN_USER_IDS = ['']

app.yaml
application: blah
version: 1
runtime: python
api_version: 1

handlers:
- url: /(.*\.(html|css|js|gif|jpg|png|ico))
  static_files: static/\1
  upload: static/.*
  expiration: "1d"

- url: .*
  script: main.py

- url: /task/.*
  script: main.py
  login: admin

Accessing the demo app on their GAE works just fine. When I take the exact same code, except for the changes I need to run under my own GAE account, the app won't work. I can login to the app using my account and the app shows up under my Apps menu. So, OAuth is good. Every time I go to access the main page, I'm always redirected to the iframe showing I use the app (can't show that image, runwithfriends app is over quota as I type this) but won't go to this iframe:

at all.
I've looked at and understand how url routing works:
def main():
    routes = [
        (r'/', RecentRunsHandler),
        (r'/user/(.*)', UserRunsHandler),
        (r'/run', RunHandler),
        (r'/realtime', RealtimeHandler),

        (r'/task/refresh-user/(.*)', RefreshUserHandler),
    ]
    application = webapp.WSGIApplication(routes,
        debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'))
    util.run_wsgi_app(application)

All the handlers are there with what looks like correct post/get methods. There are no errors logged in my GAE instance either, such as 404 or 405. When I first use http://localhost:8080, I see plenty of 200s and nothing else.
I started out using dev_appengine.py but had to move development to GAE because of my HTTPS security setting. I disabled HTTPS temporarily but still always get redirected to the apps.facebook.com/path no matter what and can't keep all my development within dev_appengine.py. Don't know if that's related to my issue or not.
Since the demo works (when not over quota), I'm sure the problem is with my own GAE instance, or configuration within FB to use my GAE, I just for the life of me can't figure out. I'm using Eclipse with PyDev and GAE plugins.
Update
Adding the app's FB configuration and the window that's displayed after I login to the app.
Sandbox:

Redirects:

Running under my GAE, this is the only page that is returned:

A: Can you post what your error actually looks like?
It sounds like you don't have the FB redirection set up properly.
Or potentially your FB is set up in a sandbox and you're trying to access your app with a non-sandboxed user.

A: I decided to delete my test FB app and recreate it. When I went to enter my key/secret values was when I found my error. My issue was with my FB APP ID and SECRET - both had a space between the single quotes like this:
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = ' xxxxxxxxxxxxxxxxx'
FACEBOOK_APP_SECRET = ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

Having the space was screwing things up, once I went to enter the new values in conf.py I spotted the extra spaces. The correct constant declaration:
# Facebook Application ID and Secret.
FACEBOOK_APP_ID = 'xxxxxxxxxxxxxxxxx'
FACEBOOK_APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

Test FB App works now.


text: Q: Подключение библиотеки Yandex MapKit на C# xamarin Пишу приложение на Android в MS Visual Studio 2017 использую фреймворк Xamarin, и при подключении библиотеки Yandex MapKit возникли проблемы, в документации указана инструкция, как это сделать на Android Studio, про то как это сделать на С#, нашел очень мало зацепок. Есть кто подключал эту библиотеку? Подскажите!


text:
Q: If $g\in{G}$ and G is a group, then the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is a bijection. Right now, I am reading Evan Chen's Napkin to study Abstract Algebra and other various topics. In lemma 1.2.5, he states:

Let $G$ be a group, and pick a $g\in{G}$. Then the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is a
bijection.

to which he asks the reader to prove this lemma. As I am not familiar with this notation, I think the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is the same as a function $f$ such that $f:G\to{G}$ and $f(x)=gx$, though I am not sure (I used Is there any difference between mapping and function? and Different arrows in set theory: $\rightarrow$ and $\mapsto$ as points of reference). Given that my assumption is right, then surjection would be proven by:

Let $y=f(x)$. Then $y=gx$ and $x=\frac{y}{g}$, demonstrating $\forall{y}\in\mathbb{R},\exists{x}\in\mathbb{R}$ such that $y=f(x)$ and proving surjectivity.

Then for injectivity, suppose $f(x_1)=f(x_2)$. Then $gx_1=gx_2$ and thus $x_1=x_2$, proving injectivity.

Thus, since $f$ is both injective and surjective, then $f$ is bijective. Similarly, this implies the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is bijective.
My main question is whether the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is the same as a function $f$ such that $f:G\to{G}$ and $f(x)=gx$. Could you also check my proof to make sure I haven't missed any considerations (such as whether I need to consider the binary operator of G). If my assumption in the main question is correct, this is just the same as proving the function $f(x)=gx$ is bijective (something very easy to do).

A: In the surjectivity part, "$\Bbb R$" is out of place. Group definition entails that every element $g\in G$ has an inverse, namely some $g^{-1}\in G$ such that $gg^{-1}=g^{-1}g=1_G$ (here $1_G$ is the identity element of $G$, whose existence is another group axiom, and the omitted operation sign in between elements is group's operation and has nothing to do with the multiplication in $\Bbb R$). Therefore, for every $y\in G$, there is $x:=g^{-1}y$, such that $f(x)=$ $gx=$ $g(g^{-1}y)=$ $(gg^{-1})y=$ $1_Gy=$ $y$ (note that another axiom of group's definition is used in the chain, namely the associativity of group's operation). The injectivity is okay, though it may worth mentioning that the result holds for the cancellation law, which is among the very first lemmata on groups in general.


text:
Q: pandas exportation to_csv and excel column format misinterpretation My goal is to export a dataframe object into a csv file. I use pandas to do it.
My problem is that when I read my csv file, some columns have different format than what I expected.
Here is an example:
import pandas

results = [('company A','+39 0584 383468','2-10'),('company B','+590690610966','2-10'),('company C','+18093494353','11-50')]

df = pandas.DataFrame(results, columns=['name', 'phone', 'employees'])

When I run:
print(df)

I get:
        name            phone employees
0  company A  +39 0584 383468      2-10
1  company B    +590690610966      2-10
2  company C     +18093494353     11-50

Which is what I want.
But when I export to a csv file:
df.to_csv('./test.csv', sep = ',', index = False)

And go to ./test.csv and check my csv file. I get:

As you can see, phone and employees changed. I wanted them to be kept as strings. But instead it got formatted into weird floating numbers and date format.
Why is that? How can I make my test.csv file exactly the same as the output df in pandas?
Edit: when I run print(df.dtypes)
name         object
phone        object
employees    object
dtype: object

Also weird, when I open back that same test.csv file into pandas, the format is correct:
df = pandas.read_csv("test.csv")
print(df)

I get:
        name            phone employees
0  company A  +39 0584 383468      2-10
1  company B    +590690610966      2-10
2  company C     +18093494353     11-50

A: As other have pointed out, your issue is that your spreadsheet is auto-interpreting your phone numbers as numeric. To hint to other applications that they should treat these as text and not numbers, force quoting when you write the csv.
import csv

df.to_csv('./test.csv', sep = ',', index = False, quoting=csv.QUOTE_ALL)

Understand that this is just a hint. The CSV spec is minimal and apps do whatever they want.

A: What are your dtypes? df.dtypes
You might have to change your dtypes to strings if they are not currently so they save in the correct format. Otherwise something might be happening within excel if you try to open the csv.


text:
Q: Numeros Aleatórios 0,9 Estou elaborando um teclado numérico, porém, ao imprimir a variável num, os números ficam repetidos, estou tentando deixá-los aleatório.
<?php
for($i=0; $i<=9; $i++){
    $num = rand(0,9)
?>
    <button class='btn btn-default' style='margin-top: 5px'><?php echo $num;?></button>
<?php } ?>


text:
Q: Background image on
* becomes background instead of becoming list bullet So I want a picture to become a bullet for my list.
I want to use a background image to become a bullet. But it becomes the background of the item.

ul {
  list-style-type: none;
}

li {
  background-image: url('https://via.placeholder.com/50')
}

test

test

test

It must be done with a background-image and not with a list-style-image
What do I need to change?

A: If you would like to use the background-image property, here is a working example:

ul {
list-style-type: none;
padding: 0;
margin: 0;
}

li {
 background-image: url(https://developer.mozilla.org/static/media/edge.40018f6a.svg);
background-repeat: no-repeat;
background-position: 0 .4em;
padding-left: 20px;
}

test

test

test

Here is an example using the list-style-image CSS property

ul {
  list-style-type: none;
}

li {
  list-style-image: url('https://via.placeholder.com/50')
}

test

test

test

A: Change the list-style-image of the ul

ul {
  list-style-image: url('https://via.placeholder.com/50')
}

test

test

test

A: You need to use list-style-image to use an image instead the regular bullets

https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image
The list-style-image CSS property sets an image to be used as the list item marker.

ul {
  list-style-type: none;
}

li {
  list-style-image: url('https://via.placeholder.com/50')
}

test

test

test

If the idea is to fake a bullet via background, then background-size and background-position will be required. Here below an example using the shorthands syntaxe for background

ul {
  list-style-type: none;
  padding:0;
}

li {
  background: url('https://via.placeholder.com/50') 0 50% / 1em 1em no-repeat;
  padding-left:1.5em;
}

test

test

test


text:
Q: How do I get the elements from list of tuples generated by ib.reqHistoricalData from API Interactive Brokers Interactive Brokers API delivers for this request:
spzValue = ib.reqHistoricalData(spx, endDateTime='', durationStr='7200 S', barSizeSetting='1 hour', whatToShow='TRADES', useRTH =False)

the following output for the variable "spxValue":
[BarData(date=datetime.datetime(2019, 7, 19, 20, 0), open=200.59, high=200.7, low=199.69, close=199.76, volume=97, average=200.045, barCount=87), BarData(date=datetime.datetime(2019, 7, 19, 21, 0), open=199.66, high=199.67, low=198.19, close=198.21, volume=369, average=198.969, barCount=322)]

Somehow I am not succeeding in getting the elements out of this list nor in converting it into a DataFrame via:
df = util.df(spzValue)

Does anyone have any suggestions how I can select specific elements out of the list "BarData"? For example I would like to have the "close" value 199.76 for the first bar.
Thanks in advance.

A: It looks like you're using ib_insync? (not just the native IBKR Python API).
There is an example of receiving historical data at https://github.com/erdewit/ib_insync
from ib_insync import *
# util.startLoop()  # uncomment this line when in a notebook

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

contract = Forex('EURUSD')
bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='30 D',
        barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)

# convert to pandas dataframe:
df = util.df(bars)

Then once you have a dataframe, you can then access the first row using iloc, and then the value using the column name:
df.iloc[0]['close']


text:
Q: Tensorflow: replace an operation with an other I have a graph that looks like that:
 I  W
 \ /
  E
  |
X1...Xn

And I'd like to replace the operation E to have a new graph like that:
 I  Q
 \ /
  L
  |
X1...Xn

But I'm getting lost with the graph_editor interface.
I've tried doing: ge.graph_replace(E, {E: L}), but I get: ValueError: Targets and replacements are not connected!.
EDIT: The code looks like that
with tf.Graph().as_default():
    saver = tf.train.import_meta_graph(FLAGS.load_model + ".meta")
    graph = tf.get_default_graph()
    codebooks, labels = read_qnpy(FLAGS.output_qnpy)
    with tf.variable_scope('Output_qnpy'):
        embeddings = qembs_graph(codebooks, labels)
        all_ids = graph.get_tensor_by_name('Model/Output/nce_loss/concat:0')
        el = graph.get_tensor_by_name('Model/Output/nce_loss/embedding_lookup:0')
        word_lookup = tf.nn.embedding_lookup(embeddings, all_ids, name="word_lookup")
        ge.graph_replace(el, {el: word_lookup})


text:
Q: Detect object with openCV and python I'm trying to detect the white dots in the following image using OpenCV and Python.

I tried using the function cv2.HoughCircles but without any success.
Do I need to use a different method?
This is my code:
import cv2, cv
import numpy as np
import sys

if len(sys.argv)>1:
    filename = sys.argv[1]
else:
    filename = 'p.png'

img_gray = cv2.imread(filename,cv2.CV_LOAD_IMAGE_GRAYSCALE)

if img_gray==None:
    print "cannot open ",filename

else:
    img = cv2.GaussianBlur(img_gray, (0,0), 2)
    cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,4,10,param1=200,param2=100,minRadius=3,maxRadius=100)
if circles:
    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),1)
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

A: If you can reproduce a morphological reconstruction in OpenCV, you can easily build a h-dome transform which simplifies the task significantly. Otherwise, a simple threshold on a gaussian filtering might be enough too.

Binarize[FillingTransform[GaussianFilter[f, 2], 0.4, Padding -> 1]]
The gaussian filtering was done in the code above to effectively suppress the noise around the border of the input, which would remain after the h-dome transform otherwise.
Next there is the result of a simple threshold after a gaussian filtering (Binarize[GaussianFilter[f, 2], 0.5]) as well another result that is given by a direct binarization using Kapur's thresholding method (see the paper "A new method for gray-level picture thresholding using the entropy of the histogram" (which is no longer a new method, it is from 1985)):

The right image above has a lot of small points all over the border (which cannot be seen at this image resolution), but is fully automatic. From these 3 options, only the second one is already present in OpenCV.

A: I think a median filter will improve your image. Try to experiment with some kernels, 3x3 or 7x7. Then after that some (local) thresholding algorithm will get you shapes. You can either you HoughCircles, or just find contours and check them for roundness.

A: Convert the image to binary image using a suitable threshold technique (Otsu might help). Then use morphological operations like erosion to make circles smaller and then you can easily find their centers.


text:
Q: Writing sum over loop using math.factorial within I'm trying to write a function to calculate such a sum:
∑_(k=0)^n 1/k!

So expected result with n = 2:
1/factorial(0) + 1/factorial(1) + 1/factorial(2) = 1 + 1 + 0.5 + 2.5
I have tried this but it isn't working. I can't figure out why. I have thought of trying to save quotients as a list then summing over it but it does not seem an efficient way.
import math
def test_fun(n:int)->int:
    Sn = 0
    k:int
    for k in range(0,n,1):
        Sn += 1/math.factorial(k)
        return(Sn)

test_fun(2)
Out[75]: 1.0

Any help would be great.
Thanks in advance.
EDIT:
unindented return(Sn) as per Carcigenicate's suggestion.
Also figured that range(0,2) returns 0,1 and not 0,1,2. All good now!
def test_fun(x:int)->int:
    n = x+1
    Sn = 0
    for k in range(0,n,1):
        Sn = Sn + 1/math.factorial(k)
    return(Sn)

test_fun(2)


text:
Q: add a new Color scheme to the Rad Studio It's possible modify or change a color scheme (Color SpeedSetting) in the Rad-Studio?
There is an entry in the Windows Registry? or must edit some file?
Thanks in advance.

A: It doesn't look easy at first glance.
I found the following under then HKCU path:
\HKCU\Software\CodeGear\ETM\12.0\Color
with the following sub-keys

*

*List item

*Classic

*Default

*Ocean

*Twilight

Each key has what appear to be color constants but there doesn't appear to be enough constants to make it the right section.
The list of values under each key:

*

*Auto_TranslatedItemColor

*EditBackgroundColor

*EditForegroundColor IsOEM

*Non_editBackgroundColor

*Non_editForegroundColor

*SelectionBackgroundColor

*SelectionForegroundColor

*TranslatedItemColor

*UntranslatedItemColor UnusedItemColor

That's all I've got, with out spending a lot more time from the looks of it.
It's probably stored in a BPL as a Opentools API object.

A: Take a look at OP's https://github.com/rruz/delphi-ide-theme-editor, it supplies thousands of themes. Yes, the OP makes one himself.
Thanks for the OP's awesome project.
Thanks for @Nicholas point out this for me.


text:
Q: Performance effect of include column in index We know that having index on a table, degrades the insert/update/delete (CUD) performance.
I want to know if I use a field as included column, how much affect (CUD) performance.
what I mean is, comparing the performance degradation between following indexes:
CREATE UNIQUE NONCLUSTERED INDEX [Idx1] ON dbo.Table (Col1, Col2)

and
CREATE UNIQUE NONCLUSTERED INDEX [Idx1] ON dbo.Table (Col1, Col2) INCLUDE (Col3)

Notes:

*

*Col3 is a small field (like int/decimal/date)

*The table has about 100 million rows

A: If the INCLUDE column covers a query, that query is likely to be much faster.  The down side is that other queries that use the index may be slightly slower.
Queries that are not covered by this index may perform more I/O when using this index.  Adding an INCLUDE column will widen the size of the rows on the non-clustered index leaf pages.  Wider rows means that fewer rows fit in a single leaf page.  Queries that use this index to find many rows will have to load more pages.
The INCLUDE column will cause the index to take up more disk space.  How much space depends on the data type of the column.
The index may take up more space in memory if many rows are scanned.
The best way to determine the impact of the INCLUDE column is to measure it.  Run queries against the table before hand and measure I/O, disk space, and record the query plan.  Run queries against it afterwards and do the same.


text:
Q: Can I get the ErrorMessage value from DataAnnotation markup? I am working on having a single source for my validation messages. I would like it to be the DataAnnotations. Is there a way I can get the ErrorMessage and use it in code? I am guessing I'd have to use Reflection, but I might be wrong. I also don't know what to do with Reflection.
public class PersonDataModel
{
    [Required(ErrorMessage = "FullName is required.")]
    public string FullName { get; set; }
}

A: You can get this with reflection using GetCustomAttributes:
string mesage = typeof(PersonDataModel)

    // Get the property owning the attribute instance:
    .GetProperty(nameof(PersonDataModel.FullName))

    // Get all attributes for the property:
    .GetCustomAttributes(true)

    // Filter the attributes by the desired DataAnnotation attribute
    .OfType<RequiredAttribute>()

    // If there is at least one instance of the desired annotation, get that
    .FirstOrDefault()

    // Assuming we found the attribute, get the ErrorMessage property.
    ?.ErrorMessage;

If you do this often, you might create a helper method. Here's an example extension method for Type:
public static class ModelExtensions {
    /// <summary>
    /// Get an attribute of type <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T">The attribute type to get.</typeparam>
    /// <param name="type">
    /// The type with a property that owns an instance of <typeparamref name="T"/>.
    /// </param>
    /// <param name="propertyName">
    /// The property that owns an instance of <typeparamref name="T"/>.
    /// </param>
    /// <returns>The attribute, if found.</returns>
    public static T GetAttributeOrDefault<T>(this Type type, string propertyName) => type
        .GetProperty(propertyName)
        .GetCustomAttributes(true)
        .OfType<T>()
        .FirstOrDefault();
}

Use it like:
string message = typeof(PersonDataModel)
    .GetAttributeOrDefault<RequiredAttribute>(nameof(PersonDataModel.FullName))
    ?.ErrorMessage;

A: If you want to display it in UI - you can use  Html.ValidationMessageFor() to show a message for a specific property of the model.
For fetching the errors in controller->

    var errors = ModelState.Select(state => state.Value.Errors)
                           .Where(errors=>errors.Count>0)
                           .ToList();


text:
Q: converting a string stream into pdf and return as a response to the client I am working on a restful service using Web API 2 upon calling the get method, should return a pdf as a response.
I have the below method which returns a string, but I would like to convert the string to pdf and send it as a respose
        [HttpGet]
        [Route("api/PDF/{ac_number}/{year}")]
        public string GetPDF(string ac_number, string year)
        {
            string res=_objService.CallAccountSearch(ac_number, year);
            return res;
        }

In the above, instead of returning string, How would I convert it to PDF response?


text:
Q: Template instantiation error in msvs 2015 I want to create a compile time structure that maps messages to default processors, but my code fails to compile in msvs 2015 update2. I think it's a bug in the compilator as a code is quite legimate and compiles with gcc. Below you can see minimal example reproducing the problem
#include <tuple>

struct About;

struct PluginStub
{
    static void About();
};

template<typename Sink>
class Processor
{
    template<typename Call, typename Stub, Stub Pointer>
    struct Method;

    using Methods = std::tuple<Method<About, decltype(&PluginStub::About), &PluginStub::About>>;
};

This gives such output:
1>  main.cpp(25): error C2440: 'specialization': cannot convert from 'void (__cdecl *)(void)' to 'unknown-type'
1>  main.cpp(25): note: Context does not allow for disambiguation of overloaded function
1>  main.cpp(26): note: see reference to class template instantiation 'Processor<Sink>' being compiled

Questions:

*

*Am I right about bug in msvs?

*How to workaround this problem?

A: A workaround would be to use std::decay:
using Methods = std::tuple<Method<About,
                           typename std::decay<decltype(&PluginStub::About)>::type,
                           &PluginStub::About>>;

A: *

*Indeed this is a bug. I created a ticket https://connect.microsoft.com/VisualStudio/feedback/details/2822978/template-instantiation-error-in-msvs-2015

*Another way to workaround this bug is to move
Methods definition out of class Processor scope.

P.S Everything compiles just fine if Processor isn't a templated class


text:
Q: Eliminar los márgenes del cuerpo de la pagina Estoy tratando de averiguar cómo eliminar los márgenes que aparecen por arriba y por abajo de mi texto en el ejemplo, sin embargo solo con css no encuentro soluciones.

body {
  margin=0;
  padding=0;
}
.paco {
  background: black;
  color: white;
  display: inline-block;
  padding-top: 0px;
  padding-bottom: 0px;
}

AGITA PACO

A: Intente definiendo el margin y padding del body

body {
  margin:0;
  padding:0
}

.paco{
  background:black;
  color:white;
  display:inline-block;
}

AGÜITA PACO

A: Estoy seguro de que si pones esto te servirá.

*{
  margin:0;
  padding:0;
}
.paco {
  background: black;
  color: white;
  display: inline-block;
  padding-top: 0px;
  padding-bottom: 0px;
}

asdasdsd

AGITA PACO

A: Ibas bien, pero hay un error en tu código: Estas utilizando = en lugar de : para asignar el valor de los margenes y el relleno (padding).
la sintaxis correcta seria:
body {
  margin: 0; /* no uses el = aquí, usa los : */
  padding: 0;
}

Ejemplo:

body {
  margin: 0;
  padding: 0;
}
.paco {
  background: black;
  color: white;
  display: inline-block;
  padding-top: 0px;
  padding-bottom: 0px;
}

EL ROCK AGITA LA LOMA

A: La propiedad CSS "line-height" indica el espacio entre líneas de un texto, quizás te sirva usando un número menor de 1.
Luego hay el "padding" y el "margin" del contenedor, pero entendí que ya lo miraste.


text:
Q: angular.js with require.js getting Uncaught Error: [$injector:modulerr] I am trying to use require.js with Main.js and getting following error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.0rc1/$injector/modulerr?p0=MyApp&p1=Error%3…3A8080%2FResults%2Fresources%2Fjs%2Fvendor%2Fangular.min.js%3A31%3A252)
My Main.js
 require.config({

    // alias libraries paths
    paths: {
        'angular': 'vendor/angular.min',
        'jquery': 'vendor/jquery-1.8.0-min',
        'angularroute': 'vendor/angular-route'
    },

    // angular does not support AMD out of the box, put it in a shim
    shim: {
        'angular': {
            deps: ['jquery'],
            exports: 'angular'
        },
        'angularroute':{
            deps:['angular']
        }

    }
});
require([
         'angular',
         'angularroute',
         'app'
         ],
        function(angular, angularroute, app){
    'use strict';
})

My app.js
define(['angular'], function(angular){
    return angular.module('MyApp',['ngRoute']);
});

I got an error that said I need to add angularroute to my app but I still get this error. Can anyone point me to what i might be doing wrong?

A: I found a solution here: https://github.com/tnajdek/angular-requirejs-seed/blob/master/app/js/main.js
from the docs:
http://code.angularjs.org/1.2.1/docs/guide/bootstrap#overview_deferred-bootstrap
window.name = "NG_DEFER_BOOTSTRAP!";
require(['angular', 'angularroute', 'app'], function(angular, angularroute, app){
    'use strict';

    //after you are done defining / augmenting 'MyApp' run this:

    angular.element().ready(function() {
        angular.resumeBootstrap([app['name']]);
    });
})

A: Here is my require config, at require_config.js:
var require = {
    baseUrl: '/js',
    paths: {
        'angular': 'lib/angular.min',
        'angular.route': 'lib/angular-route.min',
        'angular.resource': 'lib/angular-resource.min',
        'angular.animate': 'lib/angular-animate.min',
        'angular.ui.bootstrap': 'lib/ui-bootstrap-tpls-0.6.0.min',
        'angular.upload': 'lib/ng-upload.min',
        'jquery': 'lib/jquery-1.10.2.min'
    },
    shim: {
        'angular': ['jquery'],
        'angular.route': ['angular'],
        'angular.resource': ['angular'],
        'angular.animate': ['angular'],
        'angular.ui.bootstrap': ['angular'],
        'angular.upload': ['angular'],
        'my.angular': ['angular', 'angular.route', 'angular.resource', 'angular.animate', 'angular.ui.bootstrap', 'angular.upload']
    }
};

My script tags at HTML <head>:
<script src="/js/require-config.js"></script>
<script src="/js/lib/require.js"></script>

The pages that come from server-side MAY make usage of Angular, or jQuery, both, or none... so, the HTML markup may contain a single simple tag to eventually activate the whole Angular structure, like this:
<script>require(['myApp']);</script>

Now, at myApp.js, I just depend on my.angular, which takes care of loading everything else... in fact, I have other flavours of "my.angular", with different subsets, which I use in different contexts of the site:
define(['my.angular'], function() {
    var myApp = angular.module('myApp', ['ngRoute', 'ngResource', 'ngAnimate', 'ngUpload', 'ui.bootstrap']);
   // more app module stuff here, including bootstrap
    return myApp;
});

A: angular is defined as a global variable and your declaration is overriding it.  The file angular.js does not return anything so there is nothing to inject at the RequireJS level.  Try the following:
define(['angular'], function(){
    return angular.module('MyApp',['ngRoute']);
});

I was struggling with RequireJS and AngularJS so I created angularAMD to help me:
http://marcoslin.github.io/angularAMD/

A: Your setup looks fine, except you need to add angularroute as a dependency in the define portion of the app.js file. You mentioned this, but didn't reflect this in your sample code.
define(['angular', 'angularroute'], function(angular){
    return angular.module('MyApp',['ngRoute']);
});


text:
Q: Django ORM query or list dictionary Question is how to make query from three models and output as one dictionary. More explanation below with code.
Models
class AdvertCategory(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    name = models.CharField(max_length=255, db_index=True)
    ts = models.DateTimeField(auto_now=True, blank=True)

    def __str__(self):
        return self.name

class AdvertSubcategory(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    name = models.CharField(max_length=255, db_index=True)
    category = models.ForeignKey('AdvertCategory',db_index=True)

    def __str__(self):
        return self.name

class CategoryImage(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    image = models.ImageField(upload_to='category_image', db_index=True, blank=True, null=True)
    category = models.ForeignKey('AdvertCategory',db_index=True)

    def __str__(self):
        return str(self.category)

views
subcategory = AdvertSubcategory.objects.values('id','name','category')

    data = []

    for z in subcategory:
        data.append({
            'subcategory':z['name'],
            'category':AdvertCategory.objects.get(id=z['category']).name
        })

    data2 = []

    category = AdvertCategory.objects.values('id','name')
    for p in category:
        data2.append({
            'image':CategoryImage.objects.get(category=p['id']).image,
            'category':p['name']
        })

    lst = sorted(itertools.chain(data,data2), key=lambda x:x['category'])
    list_c = []
    for k,v in itertools.groupby(lst, key=lambda x:x['category']):
        d = {}
        for dct in v:
            d.update(dct)
        list_c.append(d)
    print list_c

The logic is get all category -> name, and select all subactegory based on category id in AdvertsSubcategory. Then take CategoryPicture based on category id.
And simply ouput would be like:
data = [{   'category':'Auto moto aero i nautika',
            'image':'../images/picture.png',
            'subcategory':'Aero',
            'subcategory':'Autoškola',
            'subcategory':'Najam cestovnih vozila, bicikala i plovila',
            'subcategory':'Nautika i nautička oprema',
            'subcategory':'Oprema, servis, dijelovi i usluge',
            'subcategory':'Predstavništvo i prodaja',
            'subcategory':'Teretna vozila, servis i dijelovi',
            'subcategory':'Vulkanizeri, elektrika i akumulatori'
         }]

Is there easy way to do with ORM or maybe with lists?


text:
Q: Creating Makefiles for VC++ with more than one cpp file I am tasked with adapting a boiler plate make file from a text book to be used with my project. I have 3 source files, Item.cpp Main.cpp and Item.h, and of course makefile.
I am lead to believe the reasoning for my make file not functioning correctly is having more than one source file where as the example had only one (Assignment1.cpp), here's the resulting error message.
Microsoft (R) Program Maintenance Utility Version 11.00.51106.1
Copyright (C) Microsoft Corporation.  All rights reserved.

NMAKE : fatal error U1073: don't know how to make 'Assignment01.obj'
Stop.

I have looked over some information regarding make files but most C++ is g++ related and no one seems to really use make files anymore and just lets their IDE take care of it.
# Assignment01 makefile

!include <"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include\win32.mak">
# !include <win32.mak> for Visual Studio 2010 or earlier
# Visual Studio 2012 may install this file inside C:\Program Files folder

all: Assignment01.exe

.cpp.obj:
  $(cc) $(cdebug) $(cflags) $(cvars) $*.cpp

Assignment01.exe: Assignment01.obj
  $(link) $(ldebug) $(conflags) -out:Assignment01.exe Assignment01.obj $(conlibs)

A: The problem you are facing here is that you don't have source file "Assignment01.cpp" but, the corresponding .obj file is listed in your makefile. It seems like you have two source files. So, just list two corresponding object files (Item.obj Main.obj) in your link statement.
Example is as follows:
Assignment01.exe: Item.obj Main.obj
  $(link) $(ldebug) $(conflags) -out:Assignment01.exe Item.obj Main.obj $(conlibs)

You need to verify this in your environment. I just typed this in.
Good luck.


text:
Q: vbs script upload only the file name without inside data The problem of this script is that it shows an unknown error Message while running the script.
I called the function by echo method in my ftp which is "filezilla".
every thing is working fine as it logs into the server check for the path, open channel for data writing. Still dont know where is the problem
Function FTPUpload(sSite, sUsername, sPassword, sLocalFile, sRemotePath)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  Const OpenAsDefault = -2
  Const FailIfNotExist = 0
  Const ForReading = 1
  Const ForWriting = 2

  Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")
  Set oFTPScriptShell = CreateObject("WScript.Shell")

  sRemotePath = Trim(sRemotePath)
  sLocalFile = Trim(sLocalFile)

  '----------Path Checks---------
  'Here we willcheck the path, if it contains
  'spaces then we need to add quotes to ensure
  'it parses correctly.
  If InStr(sRemotePath, " ") > 0 Then
    If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then
      sRemotePath = """" & sRemotePath & """"
    End If
  End If

  If InStr(sLocalFile, " ") > 0 Then
    If Left(sLocalFile, 1) <> """" And Right(sLocalFile, 1) <> """" Then
      sLocalFile = """" & sLocalFile & """"
    End If
  End If

  'Check to ensure that a remote path was
  'passed. If it's blank then pass a "\"
  If Len(sRemotePath) = 0 Then
    'Please note that no premptive checking of the
    'remote path is done. If it does not exist for some
    'reason. Unexpected results may occur.
    sRemotePath = "\"
  End If

  'Check the local path and file to ensure
  'that either the a file that exists was
  'passed or a wildcard was passed.
  If InStr(sLocalFile, "*") Then
    If InStr(sLocalFile, " ") Then
      FTPUpload = "Error: Wildcard uploads do not work if the path contains a " & _
      "space." & vbCRLF
      FTPUpload = FTPUpload & "This is a limitation of the Microsoft FTP client."
      Exit Function
    End If
  ElseIf Len(sLocalFile) = 0 Or Not oFTPScriptFSO.FileExists(sLocalFile) Then
    'nothing to upload
    FTPUpload = "Error: File Not Found."
    Exit Function
  End If
  '--------END Path Checks---------

  'build input file for ftp command
  sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF
  sFTPScript = sFTPScript & sPassword & vbCRLF
  sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF
  sFTPScript = sFTPScript & "binary" & vbCRLF
  sFTPScript = sFTPScript & "prompt n" & vbCRLF
  sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF
  sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF

  sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
  sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
  sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName

  'Write the input file for the ftp command
  'to a temporary file.
  Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)
  fFTPScript.WriteLine(sFTPScript)
  fFTPScript.Close
  Set fFTPScript = Nothing

  oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _
  " > " & sFTPResults, 0, TRUE

  Wscript.Sleep 1000

  'Check results of transfer.
  Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _
  FailIfNotExist, OpenAsDefault)
  sResults = fFTPResults.ReadAll
  fFTPResults.Close

  oFTPScriptFSO.DeleteFile(sFTPTempFile)
  oFTPScriptFSO.DeleteFile (sFTPResults)

  If InStr(sResults, "226 Transfer complete.") > 0 Then
    FTPUpload = True
  ElseIf InStr(sResults, "File not found") > 0 Then
    FTPUpload = "Error: File Not Found"
  ElseIf InStr(sResults, "cannot log in.") > 0 Then
    FTPUpload = "Error: Login Failed."
  Else
    FTPUpload = "Error: Unknown."
  End If

  Set oFTPScriptFSO = Nothing
  Set oFTPScriptShell = Nothing
  WScript.Echo "Process Completed (" & Now & ")"
End Function


text:
Q: How to pre-warm the cache for all customer groups programatically? By default Magento caches the pages that are accessed by the user. The pages are cached in different versions corresponding to the customer group, if the customer is logged in, which store view and currency is configured.
Based on these attribute values the value for the X-Magento-Vary cookies is being generated and this helps to identify which of the cached versions of the specific page should be used.
We would like to pre-cache all instances for all pages, but do not know how to access all pages for all of the above mentioned combination.
However, to keep things simple, lets assume we only want to pre-cache all pages for all customer groups and if a customer is logged in. Through PHP's file_get_contents() function we are able to pre-cache all pages,but only for never logged in users / users that have no cookies, yet.
Does someone know if it is possible to load the page for a specific combination of customer_group and customer_logged_in attributes?
If it is possible, we assume that we have to provide the data for context parameter of the file_get_contents() function. Has someone an idea what data we have to provide? We already tried to manually set the X-Magento-Vary cookie with a value for a specific combination but this is not the trick.
We appreciate any help! :)

A: We have open sourced our cache priming tool for Magento 2. https://github.com/8WireDigital/magento2-module-primer, I believe it might achieve what you're after.
To build a database of requests to prime we log request information along with contents of the X-Magento-Vary cookie, this is necessary so we can differentiate between customer groups etc. We then use Guzzle to re-request the urls after cache flushes, therefore priming the request in varnish. To handle X-Magento-Vary we parse a cookie with the HTTP request containing the X-Magento-Vary contents.