text:
Q: How to set the target framework to v2.0 or v3.5 instead of 4.0 when compiling a program from a source file? I have a small application which compiles a source file into executable. The problem is that this application require Netframework 4 to work,  and therfore, the compiled one also require the Net Framework 4.0
How can i set to the function below the target framework to be used in the compiled application ?
  public static bool CompileExecutable(String sourceName)
{
//Source file that you are compliling
FileInfo sourceFile = new FileInfo(sourceName);
//Create a C# code provider
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//Create a bool variable for to to use after the complie proccess to see if there are any erros
bool compileOk = false;
 //Make a name for the exe
 String exeName = String.Format(@"{0}\{1}.exe",
 System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
 //Creates a variable, cp, to set the complier parameters
 CompilerParameters cp = new CompilerParameters();
 //You can generate a dll or a exe file, in this case we'll make an exe so we set this to true
 cp.GenerateExecutable = true;
 //Set the name
 cp.OutputAssembly = exeName;
 //Save the exe as a physical file
 cp.GenerateInMemory = false;
 //Set the compliere to not treat warranings as erros
 cp.TreatWarningsAsErrors = false;
 //Make it compile
 CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
 //if there are more then 0 erros...
 if (cr.Errors.Count > 0)
 {
     //A message box shows the erros that occured
     MessageBox.Show("Errors building {0} into {1}" +
         sourceName + cr.PathToAssembly);
     //for each error that occured in the code make a separete message box
     foreach (CompilerError ce in cr.Errors)
     {
         MessageBox.Show("  {0}" + ce.ToString());
     }
 }
 //if there are no erros...
 else
 {
     //a message box shows compliere results and a success message
     MessageBox.Show("Source {0} built into {1} successfully." +
         sourceName + cr.PathToAssembly);
 }
 //if there are erros...
 if (cr.Errors.Count > 0)
 {
     //the bool variable that we made in the beggining is set to flase so the functions returns a false
     compileOk = false;
 }
 //if there are no erros...
 else
 {
     //we are returning a true (success)
     compileOk = true;
 }
 //return the result
 return compileOk;
}

Any help would be appreciated ! Thankyou in advance

A: If your using a CodeDomProvider to compile code yourself programmatically in VS 2008, what version of the Framework is targeted?
By default it is 2.0, irrespective of which VS 2010 target version (2.0, 3.0 or 3.5, 4.0) is specified.
In order to target the 4.0 framework, provide an IDictionary instance in the provider's constructor as shown below
You could pass options to the compiler using the following constructor:
var providerOptions = new Dictionary<string, string>();
providerOptions.Add("CompilerVersion", "v4.0");
var compiler = new CSharpCodeProvider(providerOptions);


text:
Q: Is there a way to disable / disallow someone from using View Creator using Diagram Tool in SQL Server? We have a lot of DB and BI analysts who regularly create views. Some folks create these views using SSMS' view creator which allows someone to drag and drop tables. This creates a lot of problems when we need to review or modify their code as the diagram tool in SSMS messes up the indentations and formatting, making it impossible to review the code. Is there an option or permission that I can revoke/change that disallows everyone from using it?

A: The view designer comes with SSMS and cannot be managed by any database engine. So, you can completely block them from creating views with DENY permission (as long as they are not sysadmin role members), but you cannot restrict them using SSMS features as the features installed in their local PC:
DENY create view to ApplicationUser

redpajama_set_name: RedPajamaStackExchange


text:
Q: Logout Redirect on ASP.NET isn't working I have a testwebsite in which I've made the Loginstatus to be
[ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect"     LogoutText="Log Out" LogoutPageUrl="Account/Logout.aspx"/> ]

However when I click the Log Out on the screen ..
it goes to this url and doesn't actually call the logout page.
"http://localhost/TestWebSite/Account/Login.aspx?ReturnUrl=%2fTestWebSite%2fAccount%2fLogout.aspx"
I was trying to make it call some logic to logout and remove a db row I have for my custom membership Provider.  This logic was placed in the page load of the logout.aspx.cs
Session.RemoveAll();

FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();

but of course it's not being called...
and of course if I login again with the ReturnUrl there, it immediately calls the logout page.
I'm confused since this is not the behavior that I expected nor is documented.
Please help.
Thanks!

A: I'm not sure if this is what your looking for but if you simply want to run some code after the user has logged out then use this method http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginstatus.onloggedout.aspx
It is called when the user presses the logout button and has been logged out. You can put your code there and then redirect to your logout page if you'd like.
Note: Theres also this method which you can use to make sure the user meets certain conditions when logging out and even cancel logging out. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.loginstatus.onloggingout.aspx
Hope this helps.


text:
Q: How should I write this string-prefix check so that it's idiomatic Python? I have a couple of lists of items:
specials = ['apple', 'banana', 'cherry', ...]
smoothies = ['banana-apple', 'mocha mango', ...]

I want to make a new list, special_smoothies, consisting of elements in smoothies that  start with the elements in specials. However, if specials is blank, special_smoothies should be identical to smoothies.
What's the most Pythonic way to do this? Is there a way to do this without a separate conditional check on whether specials is blank?

A: Since you want the behavior for empty specials to be different from the natural limit of the behavior for non-empty, you do need to special-case:
if specials:
    specialsmoothies = [x for x in smoothies
                        if any(x.startswith(y) for y in specials)]
else:
    specialsmoothies = list(smoothies)

In other words, you want the behavior for empty specials to be "all smoothies are specials", while the natural limit behavior would be to say that in that case "no smoothie is special" since none of them starts with one of the prefixes in specials (since there are no such prefixes in that case).  So, one way or another (an if/else or otherwise) you do need to make a special case in your code to match the special, irregular case you want in its semantics.

A: There are a couple of ways to do it without an explicit check on specials. But don't do them.
if specials:
  special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))]
else:
  special_smoothies = smoothies[:]

A: str.startswith() accepts tuple as an argument:
if specials:
    specialsmoothies = [x for x in smoothies if x.startswith(tuple(specials))]
else:
    specialsmoothies = list(smoothies)

A: Why complicate things? I think this is the most readable. Alex and Ignacio both give good reasons for not avoiding the else clause.
special_smoothies = []
if specials:
    for smoothy in smoothies:
        for special in specials:
            if smoothy.startswith(special):
                special_smoothies.append(smoothy)
else:
    special_smoothies = smoothies[:]


text:
Q: Efficiently find the nth number in a series where the numbers are only divisible by 2,3 and 5 I want to find the nth number in a series of numbers only divisible by 2, 3 and 5 and not divisible by any other primes.
Here is the simplest solution that I have for finding the 1500th number. This takes about 16 seconds to execute. I want to know if there is a way to make it any faster like maybe using multi threading.
#include <iostream>
using namespace std;

int main()
{
    int temp, seriesCounter = 1, currentNumber = 2;

    while (seriesCounter < 1500)
    {
        temp = currentNumber;

        //Remove all multiple of 2
        while (temp % 2 == 0)
        {
            temp /= 2;
        }
        //Remove all multiple of 3
        while (temp % 3 == 0)
        {
            temp /= 3;
        }
        //Remove all multiple of 5
        while (temp % 5 == 0)
        {
            temp /= 5;
        }
        // If only 1 remains, the number is valid, else not.
        if (temp == 1)
        {
            seriesCounter++;
        }
        currentNumber++;
    }

    cout << "The 1500th number in the series is : " << --currentNumber << endl << endl;

    return 1;
}

A: Here's one pretty straightforward approach. It finds 1500th element in under a second (I didn't bother to measure more precisely).
#include <set>
#include <iostream>

int main() {
    int n = 1500;

    std::set<long long> s;
    s.insert(2);
    s.insert(3);
    s.insert(5);
    long long num = 0;
    while (n--) {
        num = *s.begin();
        s.erase(s.begin());
        s.insert(num*2);
        s.insert(num*3);
        s.insert(num*5);
    }
    std::cout << num;
}

A: Fast solution done in 0.000031s on a i7 laptop (result: num[1499]=860934420):
Time complexity is O(n) (n=1500 in your case). assume the current sequence is num[]. we want to grow it to 1500 elements. the main idea is to keep a record of three locations in the sequence num[], let's call them idx[0], idx[1] and idx[3]. so that 2num[idx[0]], 3num[idx[1]], and 5*num[idx[2]] becomes just >= the last number in sequence(num.back()). then add the smallest of the three to the end of the sequence (which becomes the new num.back()).
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
using std::vector;
using namespace std::chrono;

int main()
{
    auto start = high_resolution_clock::now();
    const vector<int> p{ 2,3,5 };
    vector<int> idx{ 0,0,0 };
    vector<int> num = { 2,3,4,5 }; num.reserve(1500);
    vector<int> candidate(3);
    while (num.size() < 1500) {
        int candidate = INT_MAX;
        for (int i = 0; i < p.size(); i++) {
            int t;
            while (num.back() >= (t=num[idx[i]] * p[i])) idx[i]++;
            candidate = std::min(candidate, t);
        }
        num.push_back(candidate);
    }
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);

    std::cout << num.back();
    std::cout <<"\ntakes "<< duration.count() << " microseconds";
}

The code can further be improved. The idea is the same, but the number of multiplication performed is reduced, by remembering the multiplication result in array candidate[3]:
const vector<int> p{ 2,3,5 };
vector<int> idx{ 1,0,0 };
vector<int> num = { 2,3,4,5 }; num.reserve(1500);
vector<int> candidate{ 6,6,10 };
while (num.size() < 1500) {
    auto it = std::min_element(candidate.begin(), candidate.end());
    if (num.back() != *it) num.push_back(*it);
    int which_p = it - candidate.begin();
    *it = num[++idx[which_p]] * p[which_p];
}


text:
Q: impossible to create Colab notebooks with a GSuite account I am the admin of Gsuite for my organisation, le lycée Merleau-Ponty in France. It's a college (lycée en français).
I've installed colaboratory in gsuite applications with the market (i'm the admin for the domain lycee-merleauponty.fr), more than 24 hours, my users can't yet create notebooks.
When they access google drive with their gsuite account (for example, pierre@lycee-merleauponty.fr),
they can see the colaboratory link in the left menu but when they click on it and try to create a notebook, they got an error message (Google sign-in required connexion to google requested - you must be connected with a google account to continue). I can't solve the problem and the gsuite support told me to find the answer in this place. Has someone encountered the same problem or has an idea about this issue ?
NB : several broswsers have been tested, private navigation, even tor browser.
I've got a few screen captures if needed.
Thank you !

A: Apps > Additional Google Services > Access to additional services without individual control
Turn Service Status ON for Everyone.

A: Educational OU of Colab users needs to have age access set to "all members are over 18" to allow the app to launch.


text:
Q: How to resize multiple photos (batch) in Apple Photos app on macOS Having 1 TB of photos and videos in Photos.app, one might want to resize some old photos or even videos so that the changes are perfectly (keeping all metadata) updated in the Photos.app and the overall size of it decreases.
We know that touching the originals within the package contents of .photoslibrary might result in corrupted library. I have tried resizing original photos with sips, convert or other programs in bash, and the changes are visible on Photos app. However the metadata is not updated (original is 4000x2000, resized is 640x480 and photos app still shows 4000x2000 while the photo is 640x480).
There are a lot of apps that interact with Photos.app like Photo Sweeper, Power Photos, etc. However I couldn't find any that allows to batch resize by editing.
Couldn't find a way to do that with Automator or applescript although there are scripts interacting with the Photos app.
Seems a very common use case but I couldn't find any answer on the web.
Tried below suggestions:

*

*Shortcuts on MacOS: the shortcut doesn't show up. Anyways it would create another file instead of modifying the original.

*RAW Power. No ability to Resize without cropping. It does multiple enhancement, but no multi resize.

*GraphicConverter 11, is not integrated with Photos.app. No difference with what I could do with sips or convert in bash. But that would change the contents of Photos.app and it would not be reflected in the app itself.

A: E.g. RAW Power does this.

*

*Select the photos/images in Raw Power.

*Choose Export

*adjust format, customize size and wether metadata (and which) should be saved.

*select or create Album within Apple's Photos to export to.


text:
Q: MethodName as typed parameter without method parameters Is it possible to create a method that takes a MethodName as a typed parameter.  I'm after compile time checking for the name of the method.  I know I can do the following -- passing in a string of the method name:
public static DoStuff<TType>(Mock<TType> mockType, string methodName)
{
    var methods = mockType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                          .Where(method => method.Name == methodName && method.ReturnType == typeof(TResult))
                          .ToList();
    // ...
}

And used:
var myType = new Mock<MyType>();
myType.DoStuff("Update");

But is there a way to do something like:
var myType = new myType();
myType.DoStuff(m => m.Update)

Where it is evaluated at compilation and would throw if 'Update' doesn't exist on the Type 'MyType'.
Thanks.

A: No, sorry. You can't get compile-time checking unless you specify an actual generic parameter, which requires knowing the type at compile time.


text:
Q: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel I have a piece of code that works in a VS.C# project, but when this code is part of a webPart in Sharepoint, it throws an error.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
 HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(validateUrl);
 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

Validate url is a HTTPS-uri.
In Sharepoint, when I add the first rule it throws an exception when I go to the page and says

Object reference not set to instance of an object.

I do not exactly know where it throws this exception because this piece of code is being inclosed by a Try { } Catch (Exception e) -block, but that one isn't fired. So that's kind of weird.
If I let out the first rule, it throws an exception (in the right catch-block):

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Which is the same Exception I get if I let out the first rule in the VS.C# project.
Any ideas? Or other solutions? This is obviously not the safest approach.

A: By adding the server certificate in the "Trusted Root Certification Authorities" store (through MMC.exe) the problem was solved without the use of accepting all certificates.


text:
Q: find core file code where import data reading from csv file Hello developers,
I need little help,Magento is providing import/export data for products,customers using csv files.
When I go System > Import/Export > Import ,select products for Entity types and import product *.csv file and it successfully imported.But my question is where is code in core files where read and write data one by one from csv file for products.I tried to find in app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php and in this ImportController.php file I show startAction() method I also show importSource() method in Mage/ImportExport/Model/Import.php file I can not find fetch data from csv file.I effort but I could not success to find code in core files.Please help me.

A: From what I can see it's in the import.php file you where stated earlier.

/**
       * Import source file structure to DB.
       *
       * @return void
       */

The code under these comment is the beginning of checking the file, validating and a few more rows down it's about uploading the checked file.
Good luck.


text:
Q: Derivative n times of $\sqrt x$ Find a 'formula' (bad translation?) of the $n$-timed ($n\in \mathbb N$) derivative of $\sqrt x$, and prove it's correct for all $n$ with induction. What I found: $$({1\over2})^{n-1}|{3\over2}-n|(-1)^{n+1}\over{x^{n-1/2}}$$
Is it correct? If so, how do I show it is by induction?

A: Let $f(x) = x^{1/2}$, then

*

*$f'(x) = \frac{1}{2}x^{-1/2}$

*$f''(x) =\frac{1}{2}\frac{-1}{2}x^{-3/2}$

*$f^{(3)}(x) = \frac{1}{2}\frac{-1}{2}\frac{-3}{2}x^{-5/2}$

*$f^{(4)}(x) = \frac{1}{2}\frac{-1}{2}\frac{-3}{2}\frac{-5}{2}x^{-7/2}$

So maybe
$$\large
f^{(n)}(x) = (-1)^?\frac{?}{2^n}x^{\frac{-2n+1}{2}}.
$$
You can probably find the missing pieces.
As for proving that this formula is true, you could use induction: As shown above the formula is true for $n=1$. So assume that it is true for $n$ and prove it for $n+1$. So you get
$$\large
f^{(n+1)}(x) = \frac{d}{dx}[(-1)^?\frac{?}{2^n}x^{\frac{-2n+1}{2}}] = \dots = (-1)^?\frac{?}{2^{n+1}}x^{\frac{-2(n+1) + 1}{2}}.
$$
Again, you can probably fill in the missing details. And once you have gotten this far you are done.

A: Each time you derive you get the power down, and the powers are:
$$\frac{1}{2}..\frac{-1}{2}..\frac{-3}{2}...$$
The denominator is $2^k$, and the numerator is $\prod_{i=1}^k(2i-3)$, plus a $(-1)^{k+1}$ for the $-$ signs. finally, the powers of $x$ are reduced in $1/2$ every time. the final formula is:
$$(\sqrt{x})^{(k)}=\frac{(-1)^{k+1}(\prod(2i-3))x^{\frac{1-2k}{2}}}{2^k}$$


text:
Q: How to extract Map from collection of objects, with the key as one of the objects same field and value the actual objects I have a structure like this:
data class LocationRSSIEvent(
    val idRSSIEvent: Long = 0,
    val identifier: Identifier,
    val rssi: Int,
    val timestampRSSIEvent: Long) : LocationEvent()

I want to be able to use some function in Kotlin to get result like this:
fun getRSSIMultimap(rssiEvents: Collection<LocationRSSIEvent>): Map<Identifier, List<LocationRSSIEvent>>

So for example i have a list of LocationRSSIEvents, but each LocationRSSIEvent inside of it can contain different Identifier object. I want to be able to extract LocationRSSIEvents that have the same Identifier to the Map that will contain Identifier as a key of this map, and the list of those LocationRSSIEvents that have the same Identifier as a value.
I hope everything is clear, is there a simple way to achive this?

A: Seems like you're just looking for the groupBy method from the standard library:
rssiEvents.groupBy { it.identifier }


text:
Q: infinite loop when selected programmatically a cell I have a tableview with a textfield in every row.
I need to reload the tableview and programmatically select the row the user had selected.
The user can write what he wants. The data will be deleted when the textfield's editing has ended and added when the textfield has begun editing.
But I get a infinite loop. Please cloud you help me?
My code :
import UIKit

class OptionsItemViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var textFiedlDelegate: UITextField? = nil
    var categorySelected: Category?
    var options: [String] = []
    var nameOptions: [String] = []
    var cellSelected: Int = 0
    var viewHeight: CGFloat = 0
    var selectedRow: IndexPath? = nil
    var tableviewNeedToReload: Bool = false

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var keyboardAlwaysShow: UITextField!
    @IBOutlet weak var newFeatureButton: UIBarButtonItem!

    private let db = DataBase()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.dataSource = self
        self.textFiedlDelegate?.delegate = self
        self.title = categorySelected!.name
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        db.getItemOptions(predicateFormat: "id == \(self.categorySelected!.id)", completion: { results in
            self.categorySelected = results.first!
            self.options = self.categorySelected!.options as! [String]
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        })
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(false)
        self.viewHeight = self.view.frame.size.height
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(false)
        var index = 0
        while index < self.options.count {
            if self.options[index] != "" {
                index += 1
            } else {
                self.options.remove(at: index)
            }
            db.setCategoryOptions(category: self.categorySelected!, options: self.options, index: cellSelected)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    @IBAction func newFeature(_ sender: Any) {
        if self.options.last != "" {
            let indexPath: IndexPath = IndexPath(row: self.options.count, section: 0)
            self.options.append("")
            self.tableView.reloadData()

            let cell = tableView(self.tableView, cellForRowAt: indexPath) as! CellItemOptions
            cell.nameOptionsItem.becomeFirstResponder()
        }
    }

    // MARK: - TableView Functions

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return options.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let option = options[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: CellItemOptions.identifier, for: indexPath) as! CellItemOptions
        cell.nameOptionsItem.delegate = self
        cell.configureCell(with: option)
        return cell
}

    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.cellSelected = options.index(of: textField.text!)!
        let indexPath: IndexPath = IndexPath(row: self.cellSelected, section: 0)
        self.tableView.reloadData()
        let cell = self.tableView.cellForRow(at: indexPath) as! CellItemOptions
        cell.nameOptionsItem.becomeFirstResponder()
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.text! == "" {
            if self.options[cellSelected] != "" {
                db.setRemoveDetailsItem(category: self.categorySelected!, index: cellSelected)
            }
            self.options.remove(at: cellSelected)
        } else {
            self.options[cellSelected] = "\(textField.text!)"
            db.setAddDetailsItem(category: self.categorySelected!, index: cellSelected)
        }
        db.setCategoryOptions(category: self.categorySelected!, options: self.options, index: cellSelected)
    }

    // MARK: - Keyboard

    func keyboardWillShow(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.size.height == self.viewHeight {
                self.view.frame.size.height -= keyboardSize.height
            }
        }
    }

    func keyboardWillHide(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != self.viewHeight {
                self.view.frame.size.height += keyboardSize.height
            }
        }
    }
}

class CellItemOptions: UITableViewCell {
    static let identifier = "OptionsItemCell"

    @IBOutlet weak var nameOptionsItem: UITextField!

    private let tableView = OptionsItemViewController()

    func configureCell(with cell: String) {
        nameOptionsItem.text = cell
    }
}

EDIT :
The loop is due to the reload data...
Like I reload data in textFieldDidBeginEditing(), the view is reloaded more and more ... And I need to textFieldDidBeginEditing() to know the row selected by the user.


text:
Q: split the regular expression and loop through I need to loop through inside a join thats what I think I have written.
I am posting the code.
    select listagg(request_num,',') within group (order by request_num) as request_num,segmentation_name from (
select MST.REQUEST_NUM,seg_dtls.SEGMENT_NAME,LAST_UPDATED_date,seg_dtls.segmentation_name from
(select  * from rp_sr_master ) Mst,
(select  SUBSTR(ANSWER,1,INSTR (ANSWER, '~', 1)-1) AS SM_ID,sr_id from rp_sR_details
WHERE Q_ID in (SELECT Q_ID FROM RP_QUESTIONS WHERE field_id='LM_LRE_Q6')
    ) Dtls, (select SM_ID, SQL_STATEMENT, CREATION_DATE, UPDATED_DATE, SEGMENT_NAME,segmentation_name ,TOTAL_COUNT
from rp_sEGMENT_master ) seg_dtls
where Dtls.SM_ID=seg_dtls.SM_ID
and Dtls.sr_id=Mst.sr_id)
group by segmentation_name;

The problem I am facing here is in the following,
(select  SUBSTR(ANSWER,1,INSTR (ANSWER, '~', 1)-1) AS SM_ID,sr_id from rp_sR_details
    WHERE Q_ID in (SELECT Q_ID FROM RP_QUESTIONS WHERE field_id='LM_LRE_Q6')
        )

In the above code, answer will be something like this:
2603~NG non IaaS  IT Professional^2600~NG non IaaS Senior IT^2598~NG data profiling SENIOR IT professional^2595~Nigeria data profiling IT professiona
It only picks the first number that is 2603 and others will be left out.
Is there any way I can loop through all the number in that 'ANSWER'.
I am looking for ideas.
Thanks.

A: One idea is to use a method for splitting a comma delimited string into rows, you can find examples of this method in the following answers:
Splitting comma separated values in Oracle
How can I use regex to split a string, using a string as a delimiter?
The above solutions use regexp_substr function.
If you dig into details of Oracle's REGEXP_SUBSTR function you wil find that there is optional position parameter there.
This parameter can be combined with a sulution shown in this answer:
SQL to generate a list of numbers from 1 to 100
(that is SELECT LEVEL n FROM DUAL CONNECT BY LEVEL <= 100) in the below way:
with xx as (
select '2603~NG non IaaS  IT Professional^2600~NG non IaaS Senior '
       || 'IT^2598~NG data profiling SENIOR IT professional^2595~Nigeria '
       || 'data profiling IT professiona' as answer
from dual
)
select LEVEL AS n, regexp_substr( answer, '\d+',  1, level) as nbr
from xx
connect by level <= 6
;

The above query produces the following result:
N |NBR  |
--|-----|
1 |2603 |
2 |2600 |
3 |2598 |
4 |2595 |
5 |     |
6 |     |

What we need is to eliminate null values from the resultset, it can be done using a simple condition IS NOT NULL
with xx as (
select '2603~NG non IaaS  IT Professional^2600~NG non IaaS Senior '
       || 'IT^2598~NG data profiling SENIOR IT professional^2595~Nigeria '
       || 'data profiling IT professiona' as answer
from dual
)
select LEVEL AS n, regexp_substr( answer, '\d+',  1, level) as nbr
from xx
connect by regexp_substr( answer, '\d+',  1, level) IS NOT NULL
;

N |NBR  |
--|-----|
1 |2603 |
2 |2600 |
3 |2598 |
4 |2595 |

The above query works perfect for a single record, but gets confused when we try to parse 2 or more rows. Luckily there is another answer on SO that helps to solve this issue:
Is there any alternative for OUTER APPLY in Oracle?

--  source data
WITH xx as (
select 1 AS id,
       '2603~NG non IaaS  IT Professional^2600~NG non IaaS Senior '
       || 'IT^2598~NG data profiling SENIOR IT professional^2595~Nigeria '
       || 'data profiling IT professiona' as answer
from dual
UNION ALL
select 2 AS id,
       '11111~NG non IaaS  IT Professional^22222~NG non IaaS Senior '
       || 'IT^2598~NG data 33333 profiling SENIOR IT professional^44~Nigeria '
       || 'data profiling 5 IT professiona 66' as answer
from dual
)
-- end of source data

SELECT t.ID, t1.n, t1.nbr
FROM xx t
CROSS JOIN LATERAL (
        select LEVEL AS n, regexp_substr( t.answer, '\d+',  1, level) as nbr
        from dual
        connect by regexp_substr( t.answer, '\d+',  1, level) IS NOT NULL
) t1;

the above query parses numbers from two records and displays then in the following form:
ID |N |NBR   |
---|--|------|
1  |1 |2603  |
1  |2 |2600  |
1  |3 |2598  |
1  |4 |2595  |
2  |1 |11111 |
2  |2 |22222 |
2  |3 |2598  |
2  |4 |33333 |
2  |5 |44    |
2  |6 |5     |
2  |7 |66    |

I belive you will manage to merge this simple "parsing" query into your main query.


text:
Q: Kubernetes pods occasionally throw "ImagePullBackOff" or "ErrImagePull" I understand that ImagePullBackOff or ErrImagePull happens when K8 cannot pull containers, but I do not think that this is the case here. I say this because this error is randomly thrown by only some of the pods as my service scales, while others come up perfectly fine, with OK status.
For instance, please refer to this replica set here.

I retrieved the events from one such failed pod.
Events:
  Type     Reason     Age                   From                                                          Message
  ----     ------     ----                  ----                                                          -------
  Normal   Scheduled  3m45s                 default-scheduler                                             Successfully assigned default/storefront-jtonline-prod-6dfbbd6bd8-jp5k5 to gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl
  Normal   Pulling    2m8s (x4 over 3m44s)  kubelet, gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl  pulling image "gcr.io/square1-2019/storefront-jtonline-prod:latest"
  Warning  Failed     2m7s (x4 over 3m43s)  kubelet, gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl  Failed to pull image "gcr.io/square1-2019/storefront-jtonline-prod:latest": rpc error: code = Unknown desc = Error response from daemon: unauthorized: You don't have the needed permissions to perform this operation, and you may have invalid credentials. To authenticate your request, follow the steps in: https://cloud.google.com/container-registry/docs/advanced-authentication
  Warning  Failed     2m7s (x4 over 3m43s)  kubelet, gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl  Error: ErrImagePull
  Normal   BackOff    113s (x6 over 3m42s)  kubelet, gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl  Back-off pulling image "gcr.io/square1-2019/storefront-jtonline-prod:latest"
  Warning  Failed     99s (x7 over 3m42s)   kubelet, gke-square1-prod-clu-nap-n1-highcpu-2-82b95c00-p5gl  Error: ImagePullBackOff

The logs tell me it failed to pull the container because of incorrect credentials, which seems... confusing? This pod was created automatically when autoscaling exactly like the others.
I have a feeling this might have to do with resourcing. I have seen a much higher rate of these errors when the cluster spins off new nodes really fast due to a spike in traffic, or when I set lower resource requests in my deployment configurations.
How do I go about debugging this error, and what could be a possible reason this is happening?
Here is my configuation:
apiVersion: "extensions/v1beta1"
kind: "Deployment"
metadata:
  name: "storefront-_STOREFRONT-_ENV"
  namespace: "default"
  labels:
    app: "storefront-_STOREFRONT-_ENV"
spec:
  replicas: 10
  selector:
    matchLabels:
      app: "storefront-_STOREFRONT-_ENV"
  template:
    metadata:
      labels:
        app: "storefront-_STOREFRONT-_ENV"
    spec:
      containers:
      - name: "storefront-_STOREFRONT-_ENV"
        image: "gcr.io/square1-2019/storefront-_STOREFRONT-_ENV"
        ports:
        - containerPort: 8080
        readinessProbe:
          httpGet:
            path: /?healthz
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 1
        imagePullPolicy: Always

apiVersion: "autoscaling/v2beta1"
kind: "HorizontalPodAutoscaler"
metadata:
  name: "storefront-_STOREFRONT-hpa"
  namespace: "default"
  labels:
    app: "storefront-_STOREFRONT-_ENV"
spec:
  scaleTargetRef:
    kind: "Deployment"
    name: "storefront-_STOREFRONT-_ENV"
    apiVersion: "apps/v1beta1"
  minReplicas: 10
  maxReplicas: 1000
  metrics:
  - type: "Resource"
    resource:
      name: "cpu"
      targetAverageUtilization: 75

EDIT: I have been able to verify that this is in fact an auth issue. This only happens for "some" pods, since it only occurs for pods scheduled on nodes created automatically because of vertical scaling. I do not know how to fix this yet, though.

A: As we can read in the Kubernetes docs regarding images there is no need to do anything if You are running cluster on GKE.

Note: If you are running on Google Kubernetes Engine, there will already be a .dockercfg on each node with credentials for Google Container Registry. You cannot use this approach.

But it's also stated that:

Note: This approach is suitable if you can control node configuration. It will not work reliably on GCE, and any other cloud provider that does automatic node replacement.

Also in section Specifying ImagePullSecrets on a Pod.

Note: This approach is currently the recommended approach for Google Kubernetes Engine, GCE, and any cloud-providers  where node creation is automated.

It's recommended to use create a Secret with a Docker Config.
This can be done in a following way:
kubectl create secret docker-registry <name> --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL


text:
Q: multiple top n aggregates query defined as a view (or function)? I couldn't find a past question exactly like this problem.  I have an orders table, containing a customer id, order date, and several numeric columns (how many of a particular item were ordered on that date).  Removing some of the numberics, it looks like this:
customer_id  date      a    b   c   d
0001         07/01/22   0   3   3   5
0001         07/12/22  12   0  50   0
0002         06/30/22   5  65   0  30
0002         07/20/22   1   0  19   2
0003         08/01/22   0   0  99   0

I need to sum each numeric column by customer_id, then return the top n customers for each column.   Obviously that means a single customer may appear multiple times, once for each column.  Assuming top 2, the desired output would look something like this:
column_ranked customer_id  sum rank
'a'           001           12    1
'a'           002            6    2
'b'           002           65    1
'b            001            3    2
'c'           003           99    1
'c'           001           53    2
'd'           002           30    1
'd'           001            5    2

(this assumes no date range filter)
My first thought was a CTE to collapse the table into its per-customer sums, then a union from the CTE, with a limit n clause, once for each summed column.  That works if the date range is hard-coded into the CTE .... but I want to define this as a view, so it can be called by users something like this:
SELECT * from top_customers_view WHERE date_range BETWEEN ( date1 and date2 )

How can I pass the date restriction down to the CTE?  Or am I taking the wrong approach entirely?  If a view isn't possible, can it be done as a function? (without using a costly cursor, that is.)

A: Since the date ranges clearly produce a massive number of combinations you cannot generate a view with them. You can write a query, however, as shown below:
with
p as (select cast ('2022-01-01' as date) as ds,  cast ('2022-12-31' as date) as de),
a as (
select top 10 customer_id, 'a' as col, sum(a) as s
from t cross join p where date between ds and de
group by customer_id order by s desc
),
b as (
select top 10 customer_id, 'b' as col, sum(b) as s
from t cross join p where date between ds and de
group by customer_id order by s desc
),
c as (
select top 10 customer_id, 'c' as col, sum(b) as s
from t cross join p where date between ds and de
group by customer_id order by s desc
),
d as (
select top 10 customer_id, 'd' as col, sum(b) as s
from t cross join p where date between ds and de
group by customer_id order by s desc
)
select * from a
union all select * from b
union all select * from c
union all select * from d
order by customer_id, col, s desc

The date range is in the second line.
See db<>fiddle.
Alternatively, you could create a data warehousing solution, but it would require much more effort to make it work.


text:
Q: Two events in one Sub Private Sub btnBestellen_Enter()
Call bestelling()
End Sub

Private Sub btnBestellen_Click()
Call bestelling()
End Sub

I have two seperate subs here with the same code in it. Is there any possible way to make it into one sub? For example like this, of course this doesn't work.
Thank you in advance
Private Sub btnBestellen_Click,btnBestellen_Enter()
Call bestelling()
End Sub

A: Unfortunately not. VBA has no syntax for grouping Event Subs as you described.
The only work around would be to create a listener function that checks for your events manually. It would be down to you to catch them and handle them correctly. Although I'm guessing that would be out of scope here :)


text:
Q: Microtype: How to disable protrusion for single characters? I want to disable the protrusion for endashes and emdashes. The line filling does not look good there ...
But how to do so? According to the answers here, I tried to manipulate the font packages but it does not have any effect.
Which is the correct font package I have to load while using lmodern – is it lmr? What are the settings to take single characters out from protrusion?
Here is a MWE to see whats going wrong, seen at the beginning of line 2 and the end of line 5, and below the same text with protrusion disabled at all.

Protrusion should remain enabled for other characters, it is only about -- and ---.
Do you have some suggestions? :)
\documentclass[a4paper, 12pt, headsepline]{scrreprt}
\setlength{\parindent}{0pt}
\usepackage{geometry}
  \geometry{left=3.5cm, right=2cm, top=2.5cm, bottom=2cm}
\usepackage{setspace}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{microtype}
  \LoadMicrotypeFile{lmr} % Which file do I need?
  \SetProtrusion
    [ name = lmr-adapted,
      load = lmr-T1 ]
    { encoding = T1,
      family   = {lmr,lmrx,lmrj} }
    {
      \textendash = {0,0},
      \textemdash = {0,0}, % does not have any effect
      -- = {0,0},
      --- = {0,0} % does not have any effect
    }

\begin{document}

Hello world, bli bla blubb, how are you, I'm fine -- well, I need some stupid text. Damn... -- Maybe I should write a really loooooooooooooooooooooooooooooooooooooooooooooo\-ooooooooong line to fill the space. A chemist walks into a pharmacy and asks the pharmacist, "Do you have any acetylsalicylic acid?" "You mean aspirin?" asked the pharmacist. "That's it! I can never remember that word." \dots Well, that's some text ---
But how can I suppress that annoying protrusion for emdashes? 1 2 3 4 5 6 7 8 9 10 11\\

\microtypesetup{protrusion=false}
Hello world, bli bla blubb, how are you, I'm fine -- well, I need some stupid text. Damn... -- Maybe I should write a really looooooooooooooooooooooooooooooooooooooooooooo\-ooooooooong line to fill the space. A chemist walks into a pharmacy and asks the pharmacist, "Do you have any acetylsalicylic acid?" "You mean aspirin?" asked the pharmacist. "That's it! I can never remember that word." \dots Well, that's some text ---
But how can I suppress that annoying protrusion for emdashes? 1 2 3 4 5 6 7 8 9 10 11

\end{document}

A: tl;dr
Change the last l in LoadMicrotypeFile{lmr} to c.

This might seem tricky to find but it's often helpful to consult the log file. Running your example yields two warnings:
Package microtype Warning: Configuration file mt-lmr.cfg
(microtype)                does not exist on input line 11.

This tells us that we are loading the wrong file -- but which would be the right one? A clue is given by the second warning (with a bit of context):
File: mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman
(RS)

Package microtype Warning: protrusion codes list `lmr-T1' will
(microtype)                override list `lmr-adapted' for
(microtype)                font `T1/lmr///' on input line 138.

saying that the adapted settings are overridden by some other settings (the ones shipped with the package), which means that the adapted settings will never come in effect. And the line immediately preceding this warning tells us in which file the settings are defined: mt-cmr.cfg.
So, we change \LoadMicrotypeFile{lmr} to LoadMicrotypeFile{cmr} and see what happens:
First of all, the dashes are no longer protruded, so we're good.
But then, there are two new warnings:
Package microtype Warning: Unknown slot number of character
(microtype)                `--'
(microtype)                in font encoding `T1'.
(microtype)                Make sure it's a single character
(microtype)                (or a number) in protrusion list
(microtype)                `lmr-adapted'.

Package microtype Warning: Unknown slot number of character
(microtype)                `---'
(microtype)                in font encoding `T1'.
(microtype)                Make sure it's a single character
(microtype)                (or a number) in protrusion list
(microtype)                `lmr-adapted'.

which is a good sign in a way, because it means that the right settings are loaded, but of course also bad because it's a warning. To get rid of them, just delete the two corresponding lines in the settings.
It is also often helpful to load microtype with the verbose option, which allows checking which settings are loaded. In the log file we then find:
Package microtype Info: Setting up font `T1/lmr/m/n/12' on input line 24.
Package microtype Info: ... Loading protrusion list `lmr-adapted'.
Package microtype Info: ... : First loading protrusion list `lmr-T1'.
Package microtype Info: ... : First loading protrusion list `cmr-T1'.
Package microtype Info: ... : First loading protrusion list `cmr-default'.

So, to summarise, the following will do what you want:
  \LoadMicrotypeFile{cmr}
  \SetProtrusion
    [ name = lmr-adapted,
      load = lmr-T1 ]
    { encoding = T1,
      family   = {lmr} } % lmrx and lmrj don't exist
    {
      \textendash = {0,0},
      \textemdash = {0,0},
    }


text:
Q: another javascript redirecting My view :

    <form class="form-signin" method="post" action="">

Admin Login

        <input type="text" id="inputUsername" name ="inputUsername"
               class="form-control" placeholder="Admin" required autofocus />
         Password
        <input type="password" id="inputPassword" name="inputPassword"
               class="form-control" placeholder="Password" required />

        <button class="btn btn-lg btn-primary btn-block" name="login"
                type="submit">Login</button>
    </form>

My controller :
    if (isset($_POST['login'])) {
        $username = $_POST['inputUsername'];
        $password = $_POST['inputPassword'];

        echo "";
    }

When I clicked the button,
it doesnt redirect me to collections.php , what I missed here ?

A: use php header to redirect the page ,it's easy and better compaire to what you did here.
       header('Location: http://www.example.com/');

A: you redirect from php
<?php
    if (isset($_POST['login'])) {
        $username = $_POST['inputUsername'];
        $password = $_POST['inputPassword'];
        header('Location: collections.php'); //<------- php redirect to other page
    }
?>

A: this is what you were trying outputting JS in PHP for redirection be careful with url if you use relative
$redirectURL = "../controller/collection.php";
print("");


text:
Q: Get an iteratable JSON from view in template without unicode values I have created a python (2.7) dictionary with the following structure:
cntr_rgns = {'country_1':[region1, region2, region3], 'country_2':[region1, region2] ..}

I pass it to my contextdioctionary as:
ctx['regions'] = cntr_rgns

What I want is to display the values in my template.
In my template view I did that:
{% if regions %}
    {% for region in regions.items %}
        <option value={{ region }}>{{ region }}</option>
    {% endfor %}
{% endif %}

But I again get the unicode values:
(u'Canada',[u'somethong',u'something else',u..])
How can I get back an iteratable JSON or something?

A: If you want JSON, you need to actually create some JSON.
 ctx['regions'] = json.dumps(cntr_rgns)


text:
Q: HIVE: How to Parse / Ignore SLF4J Header in JSON Log Message I am working on a Hive demo, and I want to perform and aggregation query on a file that contains JSON messages, prefaced by a log4j style message at the beginning of each log line:
20:49:07.962 [main] INFO com.example.application - {"DocId":"ABC","User":{"Id":1236,"Username":"larry1234","Name":"Larry","ShippingAddress":{"Address1":"789 Main St.","Address2":"","City":"Durham","State":"NC","PostalCode":"27713"},"Orders":[{"ItemId":1111,"OrderDate":"11/11/2012"},{"ItemId":2222,"OrderDate":"12/12/2012"}]}}

I have a large volume of such records, and am working on a Hive demo.  I am aware of the Hive-JSON-Serde.  But how do I tell Hive to ignore the log4j preamble?

A: You can use get_json_object function to extract json data from the record and build from their on.  This blog can be of help. http://thornydev.blogspot.in/2013/07/querying-json-records-via-hive.html


text:
Q: How to rearrange individual cells in R?          Col1          Col2          Col3
Row1     Pink rose     Red Apple     Blue Cage
Row2     Pink rose     Red Apple     Blue Cage
Row3     Pink rose     Blue Cage     Red Apple
Row4     Pink rose     Red Apple     Blue Cage
Row5     Pink rose     Blue Cage     Red Apple

In R, how would you swap around the positions of "Red Apple" and "Blue Cage" so that they are in their respective columns.
eg. swapping Col2, Row4 'Red Apple' with Col3, Row4 'Blue Cage'
Thank you in advance.

A: This will do it:
# Your original dataframe
df <- data.frame(Col1=c("Pink Rose", "Pink Rose", "Pink Rose", "Pink Rose", "Pink Rose"),
                 Col2=c("Red Apple", "Red Apple", "Blue Cage", "Red Apple", "Blue Cage"),
                 Col3=c("Blue Cage", "Blue Cage", "Red Apple", "Blue Cage", "Red Apple"))
row.names(df) <- c("Row1", "Row2", "Row3", "Row4", "Row5")
df

# Find "Blue Cage" in Col2 and replace them with "Red Apple":
df$Col2[df$Col2 == "Blue Cage"] <- "Red Apple"

# and find "Red Apple" in Col3 and replace them with "Blue Cage"
df$Col3[df$Col3 == "Red Apple"] <- "Blue Cage"
df


text:
Q: Почему не возникает 404-ая ошибка при обращении к несуществующей странице в постраничной навигации? К примеру есть 5 записей, по одной на странице. Почему при обращении к 6-ой странице yii спокойно ее обрабатывает? Разве не должно вернуть ошибку хотя бы о том, что нет такой страницы?

A: Может быть это по вашей теме учитывая что я слышал о таком баге.
http://yiiframework.ru/forum/viewtopic.php?t=31874


text:
Q: WPF effect differences I am running the same application on two different PCs, both computers are relatively new.
One of the PCs displays the controls with effects and the other displays it very primitively.
The difference is shown below:
PC1:

PC2:

Any clue why?
When building the program I get this warning:

There was a mismatch between the processor architecture of the project being built "MSIL"

But I don't think that this has anything to do with the issue.

A: I had the same problem : the display depends on the display configuration of the computer which runs the programs.
Example : on my laptop, I use all the effects from windows 7 (in advanced configuration, you enable everything), and on my desktop, I uncheck all of them, for better performances.
The results will greatly be differents between the two pcs.
(one look like an old windows 98 and it affect what it can display)


text:
Q: The intersection of zero loci of a family of real analytic functions If $(f_i)_{i \in I}$ is a family of holomorphic functions on some open set $U \subset \mathbb C^n$ with zero loci $V_i$, then the intersection $\bigcap_{i \in I} V_i$ is complex analytic. Moreover, for every compact $K \subset U$ there exists a finite subset $J \subset I$ such that
$$K \cap \bigcap_{i \in I} V_i = K \cap \bigcap_{i \in J} V_i \,.$$
See Is intersection of zero set of any family of holomorphic functions an analytic set?

Now take the same setup but replace "holomorphic" by "real analytic" and $\mathbb C$ by $\mathbb R$.
The first statement is then trivially true, or at least if $I$ is countable: define $f = \sum_{i \in I} c_i f_i^2$ for very rapidly decreasing $c_i>0$, then the zero locus of $f$ (where it converges) is $\bigcap_{i \in I} V_i$.
Is the second statement also true? That is:

Does there exist for every compact $K \subset U$ a finite subset $J \subset I$ such that
$$K \cap \bigcap_{i \in I} V_i = K \cap \bigcap_{i \in J} V_i \,?$$


text:
Q: Value of dropdownlist in asp.net disappears after changing the value of dropdownlist by javascript In my application, I have created an ajax autocompelete extender text box.Once the user chooses the value, I want to insert that value in my dropdownlist.
The code for that purpose is:
function GetCode(source, eventArgs) {
         var hfield = $get('<%=this.HiddenID.ClientID%>');
         hfield.value = eventArgs.get_value();

       //hfield has the value selected in the autocomplete text box

        var abc = document.getElementById('<% =DropDownList2.ClientID %>');

         for (var i = 0; i < abc.length ; i++) {
             alert(abc.options[i].value);
             if (abc.options[i].value == hfield.value) {
                 abc.options[i].selected = true;
                 break;
             }
         }
     }

The problem here is: My value is not showing in the dropdownlist.
When I tried to debug the code, I realized that the value does come in the dropdownlist but when this code exits, the value disappears from the dropdownlist.
I have no idea why the values are disappearing! Please help! Thank you!

A: It's dissapearing because you are binding the data on the server-side initially and when you make the ajax request to insert the new record into the dropdownlist, the ViewState for the DropDownList had no knowledge of this new value and therefore renders what it had before.

A: If you want to modify a server side dropdownlist's element collection on client-side by javascript, you can get eventvalidation error on next postback. It would be dangerous if this behaviour wouldn't be because you could modify these controls collection by xss attack, and submit your extra added value to the server.


text:
Q: ASP.NET MVC2 Windows Authentication on Specific Controllers In ASP.NET MVC2 how do I configure a site such that by default no authentication is required, but on one particular controller I do want Windows Authentication.
Edit: I don't think this is possible based on my testing.

A: [Authorize]
public class MyController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
}

will require authorization for all actions on MyController, but anything that doesn't have the [Authorize] attribute should then be publically accessible.
You'll also need to set the Windows authentication in web.config.
<authentication mode="Windows"/>

This link may be helpful.
Edit
The only time it should be necessary to create a separate application is if you need to use both Windows and forms authentication within the same site - for instance, if you needed forms authentication for users to hit, say, a discussion forum, but windows authentication for an admin area. Since the authentication method is set at the application level and can't be overridden, in this case the parts of the app that require windows authentication would have to be split into a separate web app and virtual directory in IIS.

A: I do not think this is possible since you need to set windows auth at the site level in IIS. You will need two separate web apps for this functionality.


text:
Q: Как добавить id формы jquery Как скрыть 4 поля на странице, но при этом получать их значения в 1 поле, которое внизу?
пять форм:
<select class="browsers" id="br1" list="browsers" name="browser1" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>
<select id="br2" list="browsers" name="browser2" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>
<select id="br3" list="browsers" name="browser3" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>
<select id="br4" list="browsers" name="browser4" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>
<select id="br5" list="browsers" name="browser5" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>

Сменил эти 5 форм на одну нижнюю и нужно получать остальные 4 значения в эту форму. Я их получаю, но результат некорректный выходит, поэтому как явно их добавлять с помощью jquery?
одна форма:
<select class="browsers" list="browsers" name="browser1" multiple="multiple">
      <option value="Internet Explorer">Internet Explorer</option>
      <option value="Firefox">Firefox</option>
      <option value="Chrome">Chrome</option>
      <option value="Opera">Opera</option>
      <option value="Safari">Safari</option>
  </select>

js:
<script>
$(document).ready(function() {
    $('.browsers').select2();
});
$(document).ready(function() {
    $('#br2').hide();
});
$(document).ready(function() {
    $('#br3').hide();
});
$(document).ready(function() {
    $('#br4').hide();
});
$(document).ready(function() {
    $('#br5').hide();
});

</script>


text:
Q: UICollectionViewCell issues with registerClass I am trying to create a collection view cell programmatically without the use of storyboards or nibs.
This is my cell .h file
#import <UIKit/UIKit.h>

@interface TestCVCell : UICollectionViewCell {
    UILabel *label;
}

@property (nonatomic, retain) UILabel *label;

@end

and this is the .m file
#import "TestCVCell.h"

@implementation TestCVCell

@synthesize label;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        if (!self.label) {
            label = [[UILabel alloc] initWithFrame:self.frame];
            label.textColor = [UIColor whiteColor];

            self.contentView.backgroundColor = [UIColor orangeColor];
            [self.contentView addSubview:label];
        }
    }

    return self;
}

- (void)prepareForReuse
{
    self.label.text = @"";
}

@end

The issue I am having is that when I register class, it sporadically shows the cells and it doesn't show them at the correct locations. The cells will also randomly disappear/appear while scrolling (often not in the same location).
The weird thing is, if I create a nib and register the nib as opposed to the class, everything works perfectly fine.
The only difference I can think of between the nib and the class is with the nib, I use -(id)initWithCoder:(NSCoder *)aDecoder instead of -(instancetype)initWithFrame:(CGRect)frame.
Here is the collection view files for reference
.h
#import <UIKit/UIKit.h>

@interface TestCollectionView : UICollectionView

@end

.m
#import "TestCollectionView.h"
#import "TestCVCell.h"

@interface TestCollectionView () <UICollectionViewDataSource>

@property (nonatomic, strong) NSMutableArray *itemArray;

@end

@implementation TestCollectionView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame collectionViewLayout:[self collectionViewLayout]];

    if (self) {
        [self registerClass:[TestCVCell class] forCellWithReuseIdentifier:@"cell"];

        self.itemArray = [[NSMutableArray alloc] init];

        self.dataSource = self;

        for (int idx = 0; idx < 50; idx++) {
            [self.itemArray addObject:[NSNumber numberWithInt:idx]];
        }
    }

    return self;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TestCVCell *cell = (TestCVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    cell.label.text = [NSString stringWithFormat:@"%@", [self.itemArray objectAtIndex:indexPath.item]];

    return cell;
}

- (UICollectionViewLayout *)collectionViewLayout
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(50, 50);

    return layout;
}

@end

Has anyone ever encountered this issue or something similar?
Thanks in advanced for the help.

A: Here is your problem, Your TestCVCell Class is initializing the label during init, then the collectionView is reusing the same cell, remember during reuse we don't initialize a new object, we just recycle an existing one, therefore your label is never set up on subsequent reuse. Make the following changes to your TestCVCell class.
TestCVCell.h
@interface TestCVCell : UICollectionViewCell

@property (nonatomic) UILabel *label;

@end

You don't need the iVar label anymore. We'll use the automatically synthesized _label iVar if need be.
Use lazy loading to initialize the label, its not only clever but a cleaner alternative, customize the getter to look like below, also remember to call super on prepareForReuse
#import "TestCVCell.h"

@implementation TestCVCell

- (UILabel *)label {

    if (!_label) {

        _label = [[UILabel alloc] initWithFrame:self.bounds];
        _label.textColor = [UIColor whiteColor];
        _label.textAlignment = NSTextAlignmentCenter;
        self.contentView.backgroundColor = [UIColor orangeColor];
        [self.contentView addSubview:_label];

    }

    return _label;
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    self.label.text = @"";
}

@end

The above code only adds the label to the contentView if its not been initialized before, it will only initialize a new one when needed, thus lazy loading. Delete your entire init method, it's not needed. The above is your entire implementation of TestCVCell. Clean and easy to understand.


text:
Q: Problema al crear NavigationView En una actividad, intento crear un menú lateral.
Para esto estoy utilizando el objeto NavigationView siguiendo este tutorial:
Interfaz de Usuario en Android: Navigation Drawer (NavigationView)
El problema que tengo es que no me reconoce este objeto, el mensaje que me muestra en el Preview es el siguiente:

The following classes could not be found:
  - android.support.design.widget.NavigationView (Fix Build Path, Create Class)

He probado a añadir otras librerías pero me sigue dando error.
Mi fichero gradle es el siguiente:
apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "net.pablo.android.app"
    minSdkVersion 15
    targetSdkVersion 21
    versionCode 20
    versionName "1.18"
}
buildTypes {
    debug {
        debuggable true
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

allprojects {
repositories {
    maven { url "https://jitpack.io" }
}
}

dependencies {

compile fileTree(dir: 'libs', include: ['*.jar'])
compile('org.simpleframework:simple-xml:2.7.1') {
    exclude module: 'stax'
    exclude group: 'stax', module: 'stax-api'
    exclude group: 'xpp3', module: 'xpp3'
}
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:21.0.3'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.androidplot:androidplot-core:0.9.8'
compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1'
compile 'joda-time:joda-time:2.9.4'
compile 'com.google.maps.android:android-maps-utils:0.4+'
}

A raíz del comentario de @A.Cedano, he probado a poner el el fichero gradle la siguiente línea:
compile 'com.android.support:design:21.0.3'

pero me sigue dando error, el siguiente:

Failed to resolve: com.android.support:design:21.0.3

Me da la opción de Install Repository and sync project pero al pulsarlo para instalar este repositorio no hace nada, no instala nada.


text:
Q: How to get number from url which is stored in a string in JavaScript I have string as page url like this: - artist.php?id=6 or album.php?id=23
I want to get that value of id how to get that in javascript.

A: You should try this
In JavaScript you can get values from URL of any param using a function that in below.
$(document).ready(function () {
    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;
        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
    };

    var id = getUrlParameter('id');
});

I know it was long code but using this method you can get values of any param.

var id = getUrlParameter('id');
var anyparam = getUrlParameter('param_name');


text:
Q: prevent phpbb bruteforcing with mod_security Update: I edited this and added a fail2ban tag. Perhaps that might be another way to handle this issue.
I'm running phpbb 3.0.13-PL1 and I would like to protect the login page from bruteforcing. I'm wondering if anyone can tell me what php page to place under LocationMatch. It appears that ucp.php?mode=login is the login page, but that's also the user control panel and I don't want to accidentally lock people out of a core function of the forum. Does anyone know the correct php page to use for LocationMatch? Also is the RESPONSE_STATUS correct for PHPBB? The code below should ban users if there are 10 PHPBB failed login attempts in 3 minutes.
/etc/modsecurity/modsecurity_custom_rules.conf:
# PHPBB Bruteforce Protection

SecDataDir /tmp

SecAuditLogType Concurrent

SecAction phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR},initcol:user=%    {REMOTE_ADDR},id:500 0134

<LocationMatch "ucp.php?mode=login">

# Setup brute force detection.

# React if block flag has been set.

SecRule user:bf_block "@gt 0" "deny,status:401,log,auditlog,msg:'10 PHPBB failed login attempts in 3 minutes.',severity:'2',id:5000135,tag:'PHPBB/BRUTEFORCE'"

# Setup Tracking.  On a successful login, a 302 redirect is performed, a 200 indicates login failed.

SecRule RESPONSE_STATUS "^302" "phase:5,t:none,nolog,pass,setvar:ip.bf_counter=0,id:5000136"

SecRule RESPONSE_STATUS "^200" "phase:5,chain,t:none,nolog,pass,setvar:ip.bf_counter=+1,deprecatevar:ip.bf_cou nter=1/180,id:5000137"

SecRule ip:bf_counter "@gt 10" "t:none,setvar:user.bf_block=1,expirevar:user.bf_block=300,setvar:ip.bf_counter =0"

If this helps here is my mod_security version information:
[notice] ModSecurity for Apache/2.6.6 (http://www.modsecurity.org/) configured.
[notice] ModSecurity: APR compiled version="1.4.6"; loaded version="1.4.6"
[notice] ModSecurity: PCRE compiled version="8.30"; loaded version="8.30 2012-02-04"
[notice] ModSecurity: LUA compiled version="Lua 5.1"
[notice] ModSecurity: LIBXML compiled version="2.8.0"


text:
Q: arrange numbers to form largest number - proof of algorithm There is well known algorithmic problem, given array of numbers e.g. [1, 20, 3, 14] arrange numbers in such a way that they form biggest number possible, in this case 320141.
There is plenty of solutions on SO and other sites, using the following algorithm:
String[] strs = new String[nums.length];
for(int i=0; i<nums.length; i++){
    strs[i] = String.valueOf(nums[i]);
}

Arrays.sort(strs, new Comparator<String>(){
    public int compare(String s1, String s2){
        String leftRight = s1+s2;
        String rightLeft = s2+s1;
        return -leftRight.compareTo(rightLeft);

    }
});

StringBuilder sb = new StringBuilder();
for(String s: strs){
    sb.append(s);
}

return sb.toString();

It certainly works, but I cannot find a formal proof of this algorithm. There is one answer on quora, but I wouldn't call it a formal proof.
Does anyone can give me a sketch of proof or reference some book or article? How one can get on this solution from the original problem?
PS I tried to solve original problem but my solution was wrong, I couldn't get it right, and now I could not fully understand solution.

A: Regarding notation: I will use pipes to separate the numbers so it's
easier to see the sequence of numbers and the resulting number at the
same time:  3|20|14|1
Let us assume for the moment that the relation -- let's call it R
represented by the <= operator -- that is defined by the compare
function is a total order. It is determined by the expression
-(a+b).compareTo(b+a)

Intuitively it says that if we have two numbers a and b and b|a is
larger than a|b, b should get a higher rank than a, i.e. it should
occur left of a in the solution. If a|b is larger than b|a, it's the other way
round. If a|b = b|a, the order does not matter.
One important thing to note is that this relation not only affects two
numbers a and b considered in isolation but also tells us something
about the resulting number the two numbers are embedded in:
If a<=b, then x|a|b|y <= x|b|a|y
with x and y being numbers of
arbitrary lengths. In other words: If we have a sequence of numbers
and we swap two adjacent numbers a and b with a<=b, the resulting
number will be greater or equal afterwards.
Example: 3|14|20|1 <= 3|20|14|1 because 14 <= 20
We can now lead the assumption that the solution is not the one
implied by our relation R to a contradiction: Let's assume the
solution is some specific sequence not conforming to R. Since R is a
total order, we can rearrange the numbers to match R by swapping
adjacent elements until the order conforms to R. This reordering can
be compared to a bubble sort. However, in each swap operation that
leads us to the new order, the resulting number increases! This is
clearly a contradiction, so the original order cannot be the the
solution.
All that is left to show is that R is a total order, i.e. it is
transitive, antisymmetric and total. Since you asked for a sketch of
the proof, I'll omit this part. The essential part is proving
transitivity, i.e. that
a <= b and b <= c implies a <= c.

A: Here's a sketch of the algorithm. For your given list:
[1, 20, 3, 14]

think about how you would find the largest concatenated number.
For the most significant digit, pick the number with the largest initial digit. (In the example, pick the 3 and then the 20. Thus the answer starts with 320.)
The remaining numbers, 1 and 14, start with the same initial digit (namely 1). Which to pick next? This is where the heart of the algorithm, the compare function, comes into play. It will build the numbers and compare which one is lexically larger, that is, 114 versus 141. The negative sign on the return statement will make sure that the bigger number goes first. So the answer would be 320141.
(The algorithm doesn't actually compare the initial digits, but rather, sorts the strings from lexically largest to smallest.)


text:
Q: shared_ptr destructor, copy and incomplete type I have a header file foo.h like this (unrelated stuff omitted):
#pragma once
#include <memory>

class Bar;

struct Foo
{
  std::shared_ptr<Bar> getBar();

  std::shared_ptr<const Bar> getBar() const
  {
    return const_cast<Foo*>(this)->getBar();
  }
};

The non-const overload of getBar() is implemented in a .cpp file, which also sees the full definition of Bar.
When foo.h is included from another file (which does not see the definition of Bar), VS 2010 is giving me a warning like this:
warning C4150: deletion of pointer to incomplete type 'Bar'; no destructor called

on the const overload of getBar() (or actually on something deep in the standard library instantiated from that overload).
My question is whether that warning can safely be ignored.
The way I look at it, there are two member functions of std::shared_ptr<Bar> being called in getBar() const: the converting constructor and the destructor.
// converting constructor
template <class Y>
std::shared_ptr<const Bar>::shared_ptr(std::shared_ptr<Y> &&r)

This is used to initialise the return value of getBar() const from the return value of getBar(). This does not list any prerequisites (C++11 27.2.2.1 §20-22) which would require Y (Bar in my case) to be complete.
// destructor
std::shared_ptr<const Bar>::~shared_ptr()

27.2.2.2 §1 states that when the shared pointer being destroyed is empty, there are no side effects.
I understand why I'm getting the warning - the destructor code also has to care for the situation when delete has to be called on the stored pointer, and this code would indeed delete an incomplete type. But the way I see it, it can never be reached in my situation, so getBar() const is safe.
Am I correct, or have I overlooked a call or something which could make getBar() const actually delete an incomplete type?

A: I can find no rationale for the warning.  Nor can I replicate the warning with clang/libc++.
In general, given a shared_ptr<Bar>, without seeing the construction of shared_ptr<Bar> that takes a Bar*, and optionally a deleter, there is no way to know for sure if ~Bar() is ever called.  There is no way to know what deleter was stored in the shared_ptr<Bar>, and given some unknown deleter d that is stored in the shared_ptr<Bar>, along side of the Bar* (say p), there is no requirement that d(p) call ~Bar().
For example, your Bar may have no accessible destructor:
class Bar
{
    ~Bar();
};

And your Foo::getBar() could be implemented like this:
std::shared_ptr<Bar>
Foo::getBar()
{
    // purposefully leak the Bar because you can't call ~Bar()
    return std::shared_ptr<Bar>(new Bar, [](Bar*){});
}

There is no way for the compiler to know without seeing foo.cpp.
This warning looks like a compiler bug to me, or possibly a bug in the implementation of std::shared_ptr.
Can you ignore the warning?  I don't know.  It looks to me like you are dealing with a bug in the implementation, and so that bug could well mean that the warning is real.  But assuming a fully conforming implementation, I see no requirement for Bar to be a complete type in the code you have shown.

A: No; the warning cannot safely be ignored.  Your code creates a shared_ptr object.  The shared_ptr constructor is a template that creates and stores the deleter.  By adding code to create a shared_ptr in your header, you wound up prematurely instantiating the template constructor.
The deleter trick used by shared_ptr allows you to declare them before defining the class, but they still need to see the complete type before you first use them.  Your code has no guarantee to call Bar's destructor, ever.   What's worse is that,  today,  it could even work, but might be a time bomb,  making a very difficult to debug bug appear in your code.
The problem has nothing to do with the contents of the pointer in your code.  Just the fact that you have code that creates a shared pointer, which does not see the complete definition of Bar, is enough.
The fix is easy.  Just put that code in your implementation file,  after the complete declaration of Bar.
Edit: The warning given by g++ fits this situation, but the code does not.  For now I'm going to leave this answer up until I have time to investigate (or someone else figures out why g++ gives this warning).


text:
Q: Google OAuth: Invalid_client the oauth client was not found I'm reposting because the other cases where this issue was reported have not solved my problem.  Right now I'm just trying to get a refresh_token that can later be used in a gcp cloud function to call the directory API.  However the following curl command fails:
$ curl -d "my_client_id&scope=https://www.googleapis.com/auth/admin.directory.user" https://accounts.google.com/o/oauth2/device/code

With the following error:
{
  "error" : "invalid_client",
  "error_description" : "The OAuth client was not found."
}

Things I have tried:

*

*Made sure my OAuth Client ID is "other" and not web application.

*Changed the product name under consent screen to see if it can find the client ID

*Reset the client secret

*Renamed the Oauth Client Name

*Waited an hour

*Opened a ticket with Google under our G Suite contract (where they said they don't support their own APIs haha).

Anyone here have any good ideas?

A: Turns out there was a typo in my client id from using the up arrow (command history) on mac which wasn't visible until pressing enter and reviewing the command after execution.
Also found out that this scope (admin.directory) cannot be used with https://accounts.google.com/o/oauth2/device/code since devices are considered insecure, so only a limited set of scopes are allowed.


text:
Q: .htaccess - how to avoid a subdomain to be seen on google or similar? I have the following htaccess file for your consideration:
Options +FollowSymlinks
#+FollowSymLinks must be enabled for any rules to work, this is a security #requirement of the rewrite engine. Normally it's enabled in the root and we #shouldn't have to add it, but it doesn't hurt to do so.

RewriteEngine on
#Apache scans all incoming URL requests, checks for matches in our #.htaccess file
#and rewrites those matching URLs to whatever we specify.

#allow blank referrers.
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?site.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?site.dev [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?dev.site.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

# request is for http://dev.site.com
RewriteCond %{HTTP_HOST} ^dev.site.com$ [NC]

# user-agent is a search engine bot
RewriteCond %{HTTP_USER_AGENT} (Googlebot|yahoo|msnbot) [NC]

# return forbidden
RewriteRule ^ - [L,F]

I wish not to make dev.site.com public via google search or similar.
I've place this. Should I wait ? Or is there something else that I should do ?

A: .htaccess isn't really the place to block websites from showing up in Google search indexes.  robots.txt is one of the methods designed for this purpose.
Placing this:
User-agent: *
Disallow: /

In a file named "robots.txt" in your root directory of dev.site.com should stop it from appearing.
Alternatively you could include a meta tag in the pages you don't want to appear, such as:
<meta name="robots" content="noindex">

Or if it's only Google that you want to not index your page, but allow others robots you can use:
<meta name="googlebot" content="noindex">

The downside to this in a development/production type scenario is you'll have to do something to make sure those tags don't appear in your production code (assuming you do want Google to index you production server).


text:
Q: How can I display YouTube and Vimeo videos in my ReactJS app? I use ReactPlayer. It works with YouTube video but with Vimeo it's not working.
I fetch the URL for the videos from Firestore. With the YouTube videos I got CORS erros because of external URLs.
Have you any idea to deal with it? Thanks a lot.
<div className=" w-full overflow-hidden rounded-lg shadow-lg">
     <ReactPlayer width='100%'
                  height='100%'
                  url={selected?.video} />
</div>


text:
Q: How to remove non-printable characters I'm trying to remove non-printable characters from a string in Golang.
https://play.golang.org/p/Touihf5-hGH
invisibleChars := "Douglas"
fmt.Println(invisibleChars)
fmt.Println(len(invisibleChars))

normal := "Douglas"
fmt.Println(normal)
fmt.Println(len(normal))

Output:
Douglas
10
Douglas
7

The first string has an invisible char at the end.
I've tried to replace non-ASCII characters, but it removes accents too.
How can I remove non-printable characters only?

A: Foreword: I released this utility in my github.com/icza/gox library, see stringsx.Clean().

You could remove runes where unicode.IsGraphic() or unicode.IsPrint() reports false. To remove certain runes from a string, you may use strings.Map().
For example:
invisibleChars := "Douglas"
fmt.Printf("%q\n", invisibleChars)
fmt.Println(len(invisibleChars))

clean := strings.Map(func(r rune) rune {
    if unicode.IsGraphic(r) {
        return r
    }
    return -1
}, invisibleChars)

fmt.Printf("%q\n", clean)
fmt.Println(len(clean))

clean = strings.Map(func(r rune) rune {
    if unicode.IsPrint(r) {
        return r
    }
    return -1
}, invisibleChars)

fmt.Printf("%q\n", clean)
fmt.Println(len(clean))

This outputs (try it on the Go Playground):
"Douglas\u200b"
10
"Douglas"
7
"Douglas"
7

A: Just F.Y.I.,
I often use strings.TrimFunc, but I have found that strings.Map() detects invisible chars better than strings.TrimFunc.
strings.TrimFunc can not detect if the input chars are "Douglas\u200b" + "bar". The following example fails if followed by "bar". The result becomes 13 rather than 10.
func ExampleTrimFunc() {
    invisibleChars := "Douglas\u200b" + "bar"
    invisibleChars = strings.TrimFunc(invisibleChars, func(r rune) bool {
        return !unicode.IsGraphic(r)
    })

    fmt.Println(invisibleChars)
    fmt.Println(len(invisibleChars))

    normal := "Douglasbar"
    fmt.Println(normal)
    fmt.Println(len(normal))

    // Output:
    // Douglasbar
    // 10
    // Douglasbar
    // 10
}

*

*https://go.dev/play/p/TB-98P081U4 @ Go Playground

However, using strings.Map() as follows is successful.
 func ExampleTrimFunc() {
    invisibleChars := "Douglas\u200b" + "bar"
-   invisibleChars = strings.TrimFunc(invisibleChars, func(r rune) bool {
-       return !unicode.IsGraphic(r)
-   })
+   invisibleChars = strings.Map(func(r rune) rune {
+       if unicode.IsGraphic(r) {
+           return r
+       }
+       return -1
+   }, invisibleChars)

    fmt.Println(invisibleChars)
    fmt.Println(len(invisibleChars))

    normal := "Douglasbar"
    fmt.Println(normal)
    fmt.Println(len(normal))

    // Output:
    // Douglasbar
    // 10
    // Douglasbar
    // 10
 }

*

*https://go.dev/play/p/4ybnKVh2NDZ @ Go Playground

A: invisibleChars = strings.TrimFunc(invisibleChars, func(r rune) bool {
        return !unicode.IsGraphic(r)
    })

Go Playground: https://play.golang.org/p/39yWgnnRPXr


text:
Q: How to call a function on a class variable? In my PHP class, I'd like to declare a private static variable $filePath and assign it to the value returned by dirname(__FILE__). Here's my code:
class MyClass {
   private static $filePath = dirname(__FILE__);
}

PHP returns an error: Parse error: syntax error, unexpected '(', expecting ',' or ';'. What can be the issue and how can I fix it? Thanks


text:
Q: Legacy code: Code First one to one or zero relationship I have following legacy code fragment that I can't change:
public class EntityA
{
  int SeqId { get; set; }  //Not part of the key

  [Association("EntityB", "Seq_ID", "Seq_ID")]
  public EntityB EntityB { get; set; }
}

public class EntityB
{
  [Key]
  int SeqId { get; set; }
}

Database was created via SQL and not with Entity Framework. There are no foreign
keys and the relation is handled as one to one/zero.
Now, we must use the model for code first and Entity Framework adds a foreign key relation.
Since I can't change the model, but I can override the OnModelCreating event, I want to
rewrite the relationship from required to optional. I was trying to add
modelBuilder.Entity<EntityA>().Property(i => i.EntityB).IsOptional();

and
modelBuilder.Entity<EntityA>().HasOptional(i => i.EntityB).WithOptionalDependent()

but in both cases Entity Framework complains.

A: We used following workaround:
delete the foreign key directly after creating the model. Not beautiful but effective.


text:
Q: Best practices for lock (or Enter/Exit) in C# I have a measuring instrument object:
public class Instrument
{
  public double Measure()
  {
    return 0;
  }
}

I have a device that needs to do some measuring:
public class Device
{
  public Instrument MeasuringInstrument { get; set; }
  public void DoMeasuring()
  {
    var result = this.MeasuringInstrument.Measure();
  }
}

The measuring instrument can only operate on one device at a time, yet many devices may use the same instrument. I'm new to threading, and from what I understand, both of the following solutions have caveats.
public class Instrument
{
  public double Measure()
  {
    lock(this)
    {
      return 0;
    }
  }
}

public class Device
{
  public Instrument MeasuringInstrument { get; set; }
  public void DoMeasuring()
  {
    lock(this.MeasurementInstrument)
    {
      var result = this.MeasuringInstrument.Measure();
    }
  }
}

I've read it's best to lock on private objects, but I don't know how to do that while still allowing the MeasuringInstrument to be get/set on the Device. Any suggestions?
Thanks much,
Ken

A: if your instrument is used by multiple devices the best practice is to set lock in your instrument class. so the fist solution works better.
but its better to create a new lock object and use it in instrument class.
public class Instrument
{
  Object lockKey = new Object();
  public double Measure()
  {
    lock(lockKey)
    {
      return 0;
    }
  }
}

A: the usual pattern is to create your own private object just for locking in the case where the obvious choice might be exposed outside of the class, for example:
public class Instrument
{
    private object thisLock = new object();

    public double Measure()
    {
        lock(this.thisLock)
        {
            return 0;
        }
    }
}

public class Device
{
    public Instrument MeasuringInstrument { get; set; }
    private object measuringInstrumentLock = new object();

    public void DoMeasuring()
    {
        lock(this.measuringInstrumentLock)
        {
            var result = this.MeasuringInstrument.Measure();
        }
    }
}

Also, I suspect that you only need one of those two locks (either the one in DoMeasuring or the one in Measure) although that does depend on the missing bits.


text:
Q: VS2012 / Windows Phone emulator can't start I can't start the Windows Phone emulator in VS2012 ... I have downloaded the Windows Phone 8 SDK.
It launches, but gives me an error whilte booting:
"The Windows Phone Emulator wasn't able to ensure the virtual machine was running" ...
blalbla ... "... Element not found (0x80070490)
and something about not being able to find a useable certificate?!
Any ideas on how to get it up and running?

A: Obviously this was caused by a permission issue.
My user account hadn't any permissions to the folder:  "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys". Giving my user account full access rights to this folder, seems to have solved the problem!


text:
Q: What is the fastest way to execute an INSERT INTO SELECT FROM statement? The following code is performing very poorly when there are merely tens of millions of records present in a view:
INSERT INTO dbo.SomeTable
SELECT Field1, Field2, Field3
FROM dbo.SomeView

How could the code be modified so that inserting a lot of data works faster (ignoring the performance of the view)? IE: Are there any hints I could be using such as NOLOCK? Should I perform some other work prior to executing this command?

A: You might show us a copy of the execution plan, however in the absence of that you may consider any of the following:

*

*Could you include a where clause to limit the select?

*Are there other queries running in the background that could be causing some blocking?

*Are there index's on the gaining table you could remove prior to adding all the records, then add back.  That way you aren't writing the record and the index at the same time.


text:
Q: Code working perfectly but sending multiple times I have this code with I use in inserting into the database and it is working perfectly fine except it sends the data 3 times instead of once and I don't understand the reason it does that. I have read through the code.

// Form validation
$('.ui.form')
    .form({
        fields: {
            title: ['empty'],
            description: ['empty'],
            status: ['empty'],

        },
        onSuccess: function () {
            $("#titlediv").addClass("disabled");
            $("#descriptiondiv").addClass("disabled");
            $("#statusdiv").addClass("disabled");
            $("#contentdiv").addClass("disabled");
            $("#guideindi").fadeIn("slow");

            // Getting textbox value
            var title = $('#title').val();
            var description = $('#description').val();
            var status = $('#statusdiv').dropdown('get value');
            var content = CKEDITOR.instances['content'].getData();
            var date_added = new Date().toISOString().slice(0, 19).replace('T', ' ');
            var date_update = "";
            var added_by = localStorage.getItem("user");

            // Form append
            var data = new FormData();
            data.append('title', title);
            data.append('description', description);
            data.append('status', status);
            data.append('content', content);
            data.append('date_added', date_added);
            data.append('date_update', date_update);
            data.append('added_by', added_by);

            var admin = new XMLHttpRequest();

            admin.open("POST", "http://localhost/Hajjapi/public/api/hajj/add", false);
            admin.send(data);

            if (admin.readyState === 4) {
                if (admin.status === 200) {

                } else {

                }
            } else {
                $('#guidemsg').html(admin.statusText);
            }
        }
    });


text:
Q: Go Test delete logger.SetLogging log file I have a TestCase for a function that defines a log file path, then sets logger, so that log.* statements are written to standard out and the log file:
lf, err := os.Create(logFile)
mw := io.MultiWriter(os.Stdout, lf)
log.SetOutput(mw)

In my Test case I'm attempting to cleanup at the end, but it appears there is a lock on the file still, which means the Os.Remove() call is not working (or even returning an error)
I've tried to SetOutput to nil as well as using a defer statement.
func TestSetLogging(t *testing.T) {
// do stuff
...
log.Println("this should be in logger file")

// cleanup
log.SetOutput(nil)
defer os.Remove(logFile)
}

Yet, the logFile still appears on disk. How can I delete this file?

A: Try calling:
lf.Close()

before
os.Remove(logFile)

or you can replace
defer os.Remove(logFile)

with:
defer func() {
  lf.Close()
  os.Remove(logFile)
}()


text:
Q: Using .htaccess to redirect traffic cause redirect loop I am trying to redirect users to an a different url when they access my webapp from a particular url. For example, if they use 192.0.2.4:80 to visit the web app, I want to redirect them to 192.0.2.5:8989.
This is my .htaccess file:
RewriteEngine On
    RewriteCond %{HTTP_HOST} !http://192.0.2.4:80$ [NC]
    RewriteRule ^(.*)$ http://192.0.2.5:8989$1 [L,R=301]

When I access the site using 192.0.2.4:80 it redirect to 192.0.2.5:8989 but it repeatedly concatenates it in the URL bar. For example:
192.0.2.5:8989/192.0.2.5:8989/192.0.2.5:8989/192.0.2.5:8989 etc.
I also get the error ERR_TOO_MANY_REDIRECTS.

A: The following work for me:
RewriteCond %{HTTP_HOST} ^192.0.2.4:80$
RewriteRule ^/?$ http://192.0.2.5:8989 [R=301,L]

EDIT
As suggested below by MrWhite, the above redirect only redirects the root. The below redirect will redirect all sub directories.
RewriteCond %{HTTP_HOST} ^13.210.137.143$
RewriteRule ^(.*)$ http://192.0.2.5:8989/$1 [L,R=301]


text:
Q: React redux redirect after success post I normally work as a Java programmer and I love the fact that with Java alot of the code design is standardized. For example you read Java example about Spring or Hibernate the code structurally looks the same for the whole world.
I am now working on ReactJS with redux and I just can't seem to understand it. Every example I have seen does everything completely different and it seams as if the entire JavaScript community just can't make up there minds on how to do something the same so I am hoping someone here can explain how ReactJS / redux works.
I have a login page and when I click on a button a http post must be done to a oauth2 auth server and on success a redirect must be done.
My Component works. It is LoginPage and I can confirm that when I click on the login button an action is called.
class LoginPage extends React.Component {
  render() {
    return (
      <div id="login-container">
        <LoginForm {...this.props} />
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleSubmit: (evt) => {
      evt.preventDefault();

      performLogin(dispatch, evt.target.username.value, evt.target.password.value );
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);

The performLogin method is an action and my actions.js looks like this:
export function performLogin( dispatch, username, password ) {
    login(username, password).then(function (response) {
        dispatch({
            type: LOGIN_SUCCESS
        });
    })
    .catch(function (error) {
        dispatch({
            type: LOGIN_FAILURE
        });
    });
}

The reducer looks like this:
const loginReducer = (state = initialState, action) => {
    switch (action.type) {
        case LOGIN_SUCCESS:
            return [
                ...state, {
                    auth: {
                        'login': true
                    }
                }
            ]
        case LOGIN_FAILURE:
            return [
                ...state, {
                    auth: {
                        'login': false
                    }
                }
            ]
        default:
            return state;
    }
};

I have tried doing a axios post in the action but I got the error something like the action needs to be a plain object or something like that.
My question is where do you perform ajax calls and redirects in ReactJS/redux? In the action or the reducer?
This is a part of my packages.json:
"react": "^15.1.0",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^5.0.4",
"react-router": "^3.0.2",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.5.2",
"redux-form": "^6.8.0",
"redux-logger": "^2.6.1",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",

A: Just use browserHistory.push("page-url"); method to change your route, after success promise

A: For the error "action needs to be a plain object or something like that" I believe your Redux-thunk is set up incorrectly. dispatch(performLogin(username, password))
export function performLogin( username, password ) {
   return function (dispatch) {
     return login(username, password)
       .then(function (response) {
         dispatch({
           type: LOGIN_SUCCESS
         });
       })
   }
 }
See example makeASandwichWithSecretSauce https://github.com/gaearon/redux-thunk


text:
Q: Python3 deltatime as string for file search I'm trying to search a file for yesterdays date, and save the line to another file. When I put the date in to search "8/25/2020" everything works fine.  When I pull the current date, then subtract 1 day it doesn't work when adding it to line.startswith(). What am I doing wrong? Also I had to format the year as %y%y because the dates in the file are the full year not the last 2 digits. Thankfully its 2020.
from datetime import date, timedelta, datetime

yesterday = (datetime.now()-timedelta(days=1)).strftime("%m/%d/%y%y")
print(yesterday)

def check():
    with open("1.txt", "r") as f, open("2.txt", "w") as e:
        for line in f:
            if line.startswith(yesterday):
                e.write(line)
                print(line)

check()

A: After attempting multiple ways to get the code to work I finally figured out the issue.
from datetime import date, timedelta, datetime

yesterday = (datetime.now()-timedelta(days=1)).strftime("%-m/%d/%Y" + ":")
print(yesterday)

def check_data():
    with open("1.txt", "r") as f, open("2.txt", "w") as e:
        for line in f:
            if line.startswith(yesterday):
                e.write(line)
                print(line)
check_data()

I needed to remove the 0 padding in the date.  %-m/%d/%Y  -m in the date format fixed the issue.


text:
Q: About get event log use EvtOpenSession (Why filling the domain parameter with any text can be success?) I need to connect to the remote server to read the event log. I use EvtOpenSession function to connect and connect successfully.
My question is: why setting the parameter of Domain to any string will connect successfully?(The actual domain is "testad.com" ex:Set Credentials.Domain = L"123"; or Credentials.Domain = NULL;)
void main()
{
    const wchar_t *channelPath = L"Security";
    const wchar_t *query = L"Event/System[((EventID=4728) or (EventID = 4729))]";
    //Remote handle
    EVT_HANDLE hRemoteHandle;
    EVT_RPC_LOGIN Credentials;
    RtlZeroMemory(&Credentials, sizeof(EVT_RPC_LOGIN));

    wstring comp_name = L"TEST-AD";  //server name
    wstring user_name = L"<username>";
    wstring password = L"<password>";

    Credentials.Server = &comp_name[0];
    Credentials.Domain = L"testad.com"; //NULL; //L"123";  //Will be connected successfully, No matter what string is

    Credentials.User = &user_name[0];
    Credentials.Password = &password[0];
    Credentials.Flags = EvtRpcLoginAuthNTLM;
    hRemoteHandle = EvtOpenSession(EvtRpcLogin, &Credentials, 0, 0);
    hResults = EvtQuery(hRemoteHandle , channelPath, query, EvtQueryChannelPath|
                        EvtQueryForwardDirection);
}


text:
Q: Different redirection styles with netcat and tee giving different results In trying to trace a simple HTTP GET request and its response with nc, I'm running into something strange.
This, for example, works fine: the in file ends up containing the HTTP GET request and the out file the response.
$ mkfifo p
$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out p)&
[1] 8299
$ echo "GET /sample" | nc localhost 4000
This is contents of /sample...
$ cat out
This is contents of /sample...
$

However, if I replace the tee out p above with tee out >p, then the out file turns out to be empty.
$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out > p)&
[1] 8312
$ echo "GET /sample" | nc localhost 4000
$ cat out
$

Why should this be so?
EDIT: I'm on RHEL 5.3 (Tikanga).

A: The problem is that you're using shell redirects to read from and write to the same file. Check p afterwards, it will be empty as well.  The shell opens it in read mode, truncating the file, while it's setting up the pipeline before it runs the commands.  However, using tee, since it opens the file itself, means that the file isn't truncated until after the contents have been read for the input.  This is a well known and documented behavior and the reason you can't simply use redirects to make inline changes to files.

A: From FreeBSD's tee manpage:
DESCRIPTION
 The tee utility copies standard input to standard output, making a copy
 in zero or more files.  The output is unbuffered.

unbuffered  is the cue, Bash (or your shell's) output redirection (> p) is probably buffered, thus causing the different behavior.
(I'm sorry I can't be more certain with this, but I take the +1's on the comment as indicators for this being the right track...)