text:
Q: Validacao de Erro após disparar Tenho a seguinte funcao que dispara um formulario
Gostaria de caso desse erro mostrasse o showValidationError no sweetalert2.
Pelo menos para dizer que o campo é obrigatório ou erro ao salvar

$('.btn-ok').on('click', function(){
forumalario()
})

async function forumalario(){

  const {value: formValues} = await Swal.fire({
    title: 'Multiple inputs',
    html:
      '<input id="swal-input1" class="swal2-input">' +
      '<input id="swal-input2" class="swal2-input">',
    focusConfirm: false,
    preConfirm: () => {
      return [
        document.getElementById('swal-input1').value,
        document.getElementById('swal-input2').value
      ]
    }
  })

  if (formValues) {
    console.log('campos', JSON.stringify(formValues))
    Swal.fire(json.stringify(formValues))

  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet"/>

  OK

Assim como esse exemplo de email que eles têm

$('.btn-click').on('click', function(){
  click()
})

async function click(){
    const {value: email} = await Swal.fire({
    title: 'Input email address',
    input: 'email',
    inputPlaceholder: 'Enter your email address'
  })

  if (email) {
    Swal.fire('Entered email: ' + email)
  }
}
 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet"/>

     click

Gostaria implementar essa validação de erro

A: opa tenta assim, acho que é algo assim que você quer

$('.btn-ok').on('click', function(){
forumalario()
})

async function forumalario(){

  const {value: formValues} = await Swal.fire({
    title: 'Multiple inputs',
    html:
      '<input id="swal-input1" class="swal2-input">' +
      '<input id="swal-input2" class="swal2-input">',
    focusConfirm: false,
preConfirm: () => {

        if((document.getElementById('swal-input1').value == "") || (document.getElementById('swal-input2').value == '') || ((document.getElementById('swal-input2').value == null)) ){
          Swal.showValidationMessage(
            `Esse campo não pode estar em branco`
          )
        }
      }
  })

  if (formValues) {
    console.log('campos', JSON.stringify(formValues))
    Swal.fire(json.stringify(formValues))

  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet"/>

  OK


text:
Q: Swift 3 - Passing data between a View Controller and after that to another 2 I'm trying to perform a segue which it doesn't work.
 What i'm trying to do is send the data which i have in a textfield in my View Controller(Main), after that i want to send it to a ViewController called OperationsController and after that send it to another Views (CreateController & ListController) so i can use that same data and send it to a php file and get data to populate a table view in ListController. And for CreateController to get the email (which is in short words the data) and perform a query based on the email and insert into the database.
Anyways i tried sending the data to Operations into a label and doesn't work.
This is my code
ViewController: .
import UIKit

class ViewController: UIViewController {

   var datas:[Usuario]?

    struct Usuario : Codable {
        let correo: String?
        let contrasena: String?

    }

    @IBOutlet weak var txtError: UILabel!
    @IBOutlet weak var txtCorreo: UITextField!

    @IBOutlet weak var txtContra: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnLogear(_ sender: Any) {

        let urlString = "http://localhost:8080/swiftdb/logear.php"
        guard let url = URL(string: urlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            }

            guard let data = data else { return }
            //Implement JSON decoding and parsing
            do {
                //Decode retrived data with JSONDecoder and assing type of Article object
                let articlesData = try JSONDecoder().decode([Usuario].self, from: data)
                //Get back to the main queue
                DispatchQueue.main.async {
                 self.datas = articlesData

                    let aarti = self.datas

                    for item in aarti! {
                        let correos = item.correo
                        let contras = item.contrasena

                        if(item.correo == self.txtCorreo.text && item.contrasena == self.txtContra.text){

                            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

                            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "OP") as! OpcionesController
                            self.present(nextViewController, animated:true, completion:nil)

                           self.performSegue(withIdentifier: "segue", sender: self)

                            self.txtError.text = " "
                        } else {
                            self.txtError.text = "Datos Incorrectos"
                        }
                    }

                }

            } catch let jsonError {
                print(jsonError)
            }

            }.resume()

}

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? OpcionesController{
            destination.name = txtCorreo.text
        }
    }

}

OperationsController: .
import UIKit

class OpcionesController: UIViewController {

    var name: String?

    @IBOutlet weak var displayLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        if let nametoDisplay = name {
            displayLbl.text = name
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

A: Before calling presentViewController add :
nextViewController.name = yourTextField.text
You could also delete the segue call. That is redundant.
Here is an example that I've used in the past :
    @IBAction func doSegue(_ sender: UIButton) {
        buttonTag = sender.tag

        let storyboard = UIStoryboard (name: "Main", bundle: nil)
        let resultVC = storyboard.instantiateViewController(withIdentifier: "ResultViewController")as! ResultViewController

        // Communicate with new VC - These values are stored in the destination
        // you can set any value stored in the destination VC here
        resultVC.firstValue = buttonTag
        resultVC.secondValue = randomOpponentValue()
        self.navigationController?.pushViewController(resultVC, animated: true)
    }

A: 1.So  get rid of this code, because if you are calling performSegue you don't need that one.
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "OP") as! OpcionesController
self.present(nextViewController, animated:true, completion:nil)

2.Then in the prepareForSegue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if segue.identifier == "YourSegueIdentifier" {
    let destination: OpcionesController = segue.destination as! OpcionesController
    destination.name = txtCorreo.text
  }
}

3.Replace this code:
if let nametoDisplay = name {
    displayLbl.text = name
}

with:
displayLbl.text = name

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I pass an image to a template in Django? Suppose that the corresponding function in views.py looks like
from PIL import Image
def get_img(request, img_source)
    base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png")
    #Some editing of base_image done with PIL that prevents image from being directly loaded in html
    return render_to_response('get_img.html', {
        'base_image': base_image},
        context_instance=RequestContext(request))

How can I then display base_image in the get_img.html template?

A: You should process the image, save it on local disk and then send a path to it or more like the media url which will correspond to that image as context to html template. You need to configure your django server to serve static and media files to do that and configure serving those files in production environment as well. Read more here https://docs.djangoproject.com/en/1.9/howto/static-files/
However it should be possible to create dynamic image and serve with django in the fly with PIL if you can't or really do not want to save it locally. It will be sth like at the and of you code you should add.
response = HttpResponse(mimetype="image/png")
base_image.save(response, "PNG")
return response

Check also more info http://effbot.org/zone/django-pil.htm, it may work, although I didn't test it.

A: settings.py
   'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this line in TEMPLATES
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images')
    MEDIA_URL = '/media/images/'

add templates and media/images directory where manage.py is stored.

urls.py
urlpatterns = [

                  url('polls/', views.get_img, name="polls"),

              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py
from django.conf import settings

def get_img(request):
    path = settings.MEDIA_ROOT
    img_list = os.listdir(path + "/")
    print(img_list[0])
    base_image = "http://127.0.0.1:8000/media/images/" + img_list[0]
    content = {"base_image": base_image}
    return render(request, 'get_img.html', content)

get_img.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>drop_down</title>

  {{base_image}}

A: You can pass image as base64 bytes to Django template, and then use it in html:
view.py
from PIL import Image
from io import BytesIO
import base64

# Convert Image to Base64
def image_to_base64(image):
    buff = BytesIO()
    image.save(buff, format="PNG")
    img_str = base64.b64encode(buff.getvalue())
    img_str = img_str.decode("utf-8")  # convert to str and cut b'' chars
    return img_str

def home(request):
    image = Image.open('some_image.png')
    image64 = image_to_base64(image)
    return render(request, 'index.html', {'image64': image64})

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

It will works for JPG too - need to change all PNG mentions to JPG in .py/.html

A: I think you must save image (write it to temp file) in static directory of project and in template use static command and image file name to display it.


text:
Q: SwiftUI view won't expand to full height - iOS 15 Xcode 13 beta 5 I'm trying to create my own keyboard view (I need a decimal keyboard, with a guaranteed . and not , which is shown in Europe).
I have it working great except in landscape one of the keys is not the correct size.
(Colours to show frame sizes)

The problem seems to happen on iOS 15 when the height of the full view shrinks to around 200px. On iOS 14 you can see it's causing issue as it has padding on the bottom row. Removing the .resizable() form the Image seems to fix that so not sure if it's related.
I've simplified the code here to a view that shows the issue.
Here is the code that builds each key:
enum KeyboardKey: String, CaseIterable {

    case one = "1"
    case two = "2"
    case three = "3"
    case four = "4"
    case five = "5"
    case six = "6"
    case seven = "7"
    case eight = "8"
    case nine = "9"
    case zero = "0"
    case dot = "."
    case backspace = "backspace"

    @ViewBuilder
    func view() -> some View {
        switch self {
        case .one, .two, .three, .four, .five, .six, .seven,
                .eight, .nine, .zero:
            Text(self.rawValue)
                .font(.title)
                .foregroundColor(.black)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.white)
                .cornerRadius(6)
                .shadow(color: Color.black.opacity(0.5), radius: 1, x: 0, y: 1)
        case .dot:
            Text(self.rawValue)
                .font(.title)
                .foregroundColor(.black)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .cornerRadius(6)
        case .backspace:
            HStack(alignment: .center, spacing: 0) {
                Image(systemName: "delete.left")
                    .resizable()
                    .frame(width: 20, height: 20)
                    .background(Color.green)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.red)
            .cornerRadius(6)
        }
    }
}

and the keyboard view is built up with this:
struct IPKeyboardButtons: View {

    let rows: [[KeyboardKey]] = [
        [.one, .two, .three],
        [.four, .five, .six],
        [.seven, .eight, .nine],
        [.dot, .zero, .backspace]
    ]

    var body: some View {
        VStack {
            ForEach(0..<rows.count, id: \.self) { rowIndex in

                let row = rows[rowIndex]
                HStack(spacing: 5) {
                    ForEach(row, id: \.self) { key in
                        Button(action: {
                            print("Tapped: \(key)")
                        }) {
                            key.view()
                        }
                    }
                }
            }
        }
        .padding(5)
        .padding(.bottom, 40)
        .background(Color.keyboardBackground)
    }
}

You can view it in a SwiftUI preview with this:
struct App_Previews: PreviewProvider {
    static var previews: some View {
        IPKeyboardButtons()
            .frame(height: 200)
    }
}

Removing the .frame(height: 200) make it look perfect.
I've tried using a ZStack, VStack, AnyView() you name it, to wrap the key, but they all have the same effect.
I want the image to be smaller than the button, so I set it to be 20x20 then set the container view to .infinity but it seems to be ignored.

A: I would use a LazyVGrid to handle this. The solution you are trying to use was really an iOS 13 workaround for making grids. LazyVGrid handles this elegantly.
struct IPKeyboardButtons: View {

    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

    var body: some View {
        LazyVGrid(columns: columns, alignment: .center, spacing: 20) {
            ForEach(KeyboardKey.allCases, id: \.self) { key in
                Button(action: {
                    print("Tapped: \(key)")
                }) {
                    key.view()
                }
            }
        }
        .padding(5)
        .padding()
        .background(Color.gray)
    }
}

I changed the enums view() function slightly to add some padding around the symbols(number or SF Font). Also, you can treat an SF Font like text. They are designed to be used right along with text and using text modifiers like .font:
enum KeyboardKey: String, CaseIterable {

    case one = "1"
    case two = "2"
    case three = "3"
    case four = "4"
    case five = "5"
    case six = "6"
    case seven = "7"
    case eight = "8"
    case nine = "9"
    case zero = "0"
    case dot = "."
    case backspace = "backspace"

    @ViewBuilder
    func view() -> some View {
        switch self {
        case .one, .two, .three, .four, .five, .six, .seven,
                .eight, .nine, .zero:
            Text(self.rawValue)
                .font(.title)
                .foregroundColor(Color.black)
                .padding() // optional, but this will increase the size of the button itself
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.white)
                .cornerRadius(6)
                .shadow(color: Color.black.opacity(0.5), radius: 1, x: 0, y: 1)
        case .dot:
            Text(self.rawValue)
                .font(.title)
                .foregroundColor(Color.black)
                .padding() // optional, but this will increase the size of the button itself
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .cornerRadius(6)
        case .backspace:
            Image(systemName: "delete.left")
                .font(.title)
                .background(Color.green)
                .padding() // optional, but this will increase the size of the button itself
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .cornerRadius(6)
        }
    }
}

This is the view I put it in so it would behave in a real world test case. I would stay away from forcing frames in the preview as that will give artificial constraints and does not respect safe areas:
struct KeyboardView: View {

    @State var textBinding = ""

    var body: some View {
        VStack {
            TextField("TextField", text: $textBinding)
            Spacer()
            IPKeyboardButtons()
        }
    }
}

This code is much simpler and easier to maintain.


text:
Q: Theme + dynamic control creation + Invisible UserControl = view state error? default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" Theme="Blue" %>

<%@ Register TagPrefix="uc1" TagName="favicon" Src="~/FavIcon.ascx" %>

<!DOCTYPE html>

<script runat="server">

    private void Page_PreRender(object sender, System.EventArgs e)
    {
        HtmlGenericControl scriptControl = new HtmlGenericControl("script");
        Page.Header.Controls.AddAt(0, scriptControl);//If this line is commented out, no exception will occur.
    }

    private void Page_Init(object sender, System.EventArgs e)
    {
        ScriptManager oSM = new ScriptManager();
        Page.Form.Controls.Add(oSM);//If this line is commented out, no exception will occur.
    }

</script>

<html>
<head runat="server">
    <title></title>
    <uc1:favicon runat="server"></uc1:favicon>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </form>
</body>
</html>

FavIcon.ascx
<%@ Control Language="C#" ClassName="FavIcon" AutoEventWireup="true" %>

<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        this.Visible = false;//If this line is commented out, no exception will occur.
    }

</script>

Also add a stylesheet to the Blue theme.

The page opens successfully, but once I click the button, it throws exception

Failed to load viewstate.  The control tree into which viewstate is
  being loaded must match the control tree that was used to save
  viewstate during the previous request.  For example, when adding
  controls dynamically, the controls added during a post-back must match
  the type and position of the controls added during the initial
  request.

Can anyone explain why this error happens?

A: It happens due to the nature of ViewState. Briefly, when your page is being posted back a control into which ViewState is restored is matched by the control index, so when the index changes it causes this problem.
In this case, setting the property this way ViewStateMode="Disabled" for your page or changing the order you add your dynamic elements Page.Header.Controls.AddAt(Page.Header.Controls.Count, scriptControl), which lets you not interfere with the order of restored elements, can help you cope with the trouble. At least, it works out for me.

A: To debug these errors, I strongly recommend to enable traces (Trace="true" in the @page directive, or use a global setting in web.config) so you can see the server's control tree.
On a GET, the control tree is this (note the unique IDs that were generated automatically):
  HtmlHead
    + ctl05 : HtmlGenericControl (from your PreRender code)
    + ctl01 : Title (the <title> tag)
    + ctl02 : FavIcon (your favicon.ascx)
    + ctl04 : HtmlLink (from the 'Blue' theme)

  HtmlForm
    + ctl03 : ScriptManager

The root causes of the 'Failed To Load ViewState' error are:

*

*you use the ViewState. This is an option that in many cases can be disabled.

*you don't use fixed IDs (that's why the Visual Studio's IDE adds automatic but fixed IDs to controls all the time).

*you add controls dynamically, late, in the tree, as it changes the head's control tree. Plus, you add it before others (AddAt).

The generated IDs follow ASP.NET's lifecycle order:

*

*Title (static)

*FavIcon (static)

*ScriptManager (Init)

*Theme (Init, after overrides)

*Dynamic controls (After Init in this case)

The ASP.NET ViewState engine is a tree serializer/deserializer. Each node in the tree has it's IDs, plus a "full ID" composed of its parent's IDs and its own ID. Of course, as soon as you change IDs between serialization and deserialization, all bets are off, the engine will detect it and raise the 'Failed to Load ViewState' error.
So, if you put Visible=false, you'll use the ViewState. If you remove it, you won't. When you don't use the ViewState yourself, there are less chances to get the 'Failed to load viewstate' error, but ASP.NET can use some ViewState on your behalf when you use all its features (Theme, etc.). In the case of Visible, it just means the control is there (and uses ViewState), but not rendered (it's Render Size is 0). But you'll see the problem with any other property that use the ViewState, it's not specific to the Visible property (you could also try this.ViewState["test"] = "whatever" ).
If you put <uc1:favicon runat="server"></uc1:favicon> elsewhere in the page, it will also work because it won't be in the Head control tree anymore, and won't interfere with Theme's link or your dynamic control.
For Theme and ScriptManager, it's just that when you play with them, it changes, or not, the IDs, and the system may detect it or not.
There is an infinite number of ways to break the ViewState. What's really difficult is it may seem to work when it shouldn't (for example as long as you don't use FavIcon's ViewState, you don't notice there is an issue with your code).


text:
Q: Why does the location of the north magnetic pole vary faster than that of the south magnetic pole? Noticing what Wikipedia asserts about the variation of the locations of the magnetic poles over time, e.g., 1998 $\sim$ 2000 to 2015, one would notice that the location of the north magnetic pole varies much faster than that of the south magnetic pole.
What logic would justify this dissimilar variation?

A: Have a look on how the earth's magnetic field is modeled presently:

he Earth's magnetic field is attributed to a dynamo effect of circulating electric current, but it is not constant in direction.

So the question becomes why the circulating currents have a higher effect on the northern hemisphere than the southern one. It evidently depends on how the magma in the center of the earth is oriented and the dynamo effect appears.

Convection drives the outer-core fluid and it circulates relative to the earth. This means the electrically conducting material moves relative to the earth's magnetic field. If it can obtain a charge by some interaction like friction between layers, an effective current loop could be produced. The magnetic field of a current loop could sustain the magnetic dipole type magnetic field of the earth. Large-scale computer models are approaching a realistic simulation of such a geodynamo.

So the details are not known, but the difference will be due to the geological topology of the earth.
For an intuitive understanding, take a bar of magnet. The north  and south are joined rigidly. Turn the middle portion to a fluid, with a different density from north to south, you could then in a rotation have the north turning in much larger circles than the south.
In a sense , if the dynamo is fitted successfully we will learn something about the composition of the earth, solid-fluid.


text:
Q: Intellisense C++ file with alternative extension Hi fellow programmers,
I have a C++ file with the extension .inc that is getting included from another C++ header. My problem is that the intellisense is inactive for this file, all the text just showing up black. I am using visual studio 2015. I have looked everywhere inside visual studio with no luck.
Is there any way to activate intellisense for this file?
Thanks in advance,
Jakob.

A: You need to tell VS that those .inc files are in fact C++.
Go to Tools -> Options -> Text Editor -> File Extension and add your .inc:

You need to restart Studio, at least for version 2013.


text:
Q: Getting print calls in LuaJ I'm writing a Java program which uses Lua scripts to determine what to output to certain areas of the program. Currently, my code looks as such:
Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile(dir.getAbsolutePath() + "/" + name);
chunk.call();
String output = chunk.tojstring();

The problem is that calling tojstring() appears to return return values from the Lua script. This is fine, but I need to get print calls, as that's what will be displayed on the screen. As of now, the print calls get sent directly to the Console (printed to console), and I cannot figure out a way to retrieve these print calls.
I've tried digging through the documentation but have had little success. Will change from LuaJ if needed.

A: Expanding on Joseph Boyle's answer (a few years later): You can also set up a printStream to a ByteArrayOutputStream (no need to do it to a file on disk) if that's your poison. I did this in a JUnit test with LuaJ and it works:
  @Test
  public void testPrintToStringFromLuaj() throws IOException {
    String PRINT_HELLO = "print (\"hello world\")";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos, true, "utf-8");
    Globals globals = JsePlatform.standardGlobals();
    globals.STDOUT = printStream;
    LuaValue load = globals.load(PRINT_HELLO);
    load.call();
    String content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    printStream.close();
    assertThat(content, is("hello world\n"));
  }

A: I actually was able to solve the problem by changing the STDOUT variable in the globals object to a temporary file, and then reading the data from the temporary file.
Probably not the best solution, but works perfectly fine.


text:
Q: NLog rule ordering I've seen a few examples of suppressing logs from a particular namespace but they all seem to suppress everything except for that namespace and not the other way around (that's to say, "give me enhanced logging for this namespace and suppress everything else" etc).
Would someone please explain why the following configuration doesn't suppress loggers in the My.Namespace namespace?  The goal is to ensure that any logger in the My.Namespace namespace is logged only for errors, while everything else is unaffected.
<configSections>
  <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets async="true">
    <target name="console" xsi:type="Console" layout="${level} ${message}" />
  </targets>

  <rules>
    <logger name="My.Namespace.*" minlevel="Error" writeTo="console" final="true" />
    <logger name="*" minlevel="Debug" writeTo="console" />
  </rules>
</nlog>

A: While I think it'd be clearer to be able to set a blanket rule for namespace suppression, I've managed to get this working with the following configuration:
<targets async="true">
  <target xsi:type="Console" name="console" layout="${longdate} ${level} ${message}" />
</targets>

<rules>
  <!-- Anything less or equal to DEBUG, don't write to anything (no target) -->
  <logger name="My.Namespace.*" maxlevel="Debug" final="true" />

  <!-- Anything greater or equal to INFO, write to the console target -->
  <logger name="My.Namespace.*" minlevel="Info" writeTo="console" final="true" />
  <logger name="*" minlevel="Debug" writeTo="console" />
</rules>


text:
Q: Finding exact number of characters in word I'm looking for a way to find words with the exact number of the given character.
For example:
If we have this input: ['teststring1','strringrr','wow','strarirngr'] and we are looking for 4 r characters
It will return only ['strringrr','strarirngr'] because they are the words with 4 letters r in it.
I decided to use regex and read the documentation and I can't find a function that satisfies my needs.
I tried with [r{4}] but it apparently returns any word with letters r in it.
Please help

A: something like this:
import collections

def map_characters(string):
    characters = collections.defaultdict(lambda: 0)
    for char in string:
        characters[char] += 1
    return characters

items = ['teststring1','strringrr','wow','strarirngr']

for item in items:
    characters_map = map_characters(item)
    # if any of string has 4 identical letters
    # we print it
    if max(characters_map.values()) >= 4:
        print(item)

# in the result it outputs strringrr and strarirngr
# because these words have 4 r letters

A: You can use str.count() to count the occurrences of a character, combined with list comprehensions to create a new list:
myArray =  ['teststring1','strringrr','wow','strarirngr']

letter = "r"
amount = 4

filtered = [item for item in myArray if item.count(letter) == amount]
print(filtered) # ['strringrr', 'strarirngr']

If you wanted to make this reusable (to look for different letters or different amounts), you could pack it into a function:
def filterList(stringList, pattern, occurrences):
    return [item for item in stringList if item.count(pattern)==occurrences]

myArray =  ['teststring1','strringrr','wow','strarirngr']
letter = "r"
amount = 4

print(filterList(myArray, letter, amount)) # ['strringrr', 'strarirngr']

A: The square brackets are for matching any items in the set, e.g. [abc] matches any words with a,b or c. In your case, it evaluates to [rrrr], so any one r is a match. Try it without the brackets: r{4}

A: Since you asked about using regex, you could use the following:
import re
l = ['teststring1', 'strringrr', 'wow', 'strarirngr']
[ word for word in l if re.match(r'(.*r.*){4}', word) ]

output: ['strringrr', 'strarirngr']


text:
Q: Select smooth streaming bitrate while playing csm-files There are examples for switching bitrates: Load higher quality smooth streaming bitrate on start, IIS Smooth streaming low quality on start for SmoothStreamingMediaElement and SMFPlayer.
They work fine for .ism files. But they don't for .csm (composite manifests).
Segment.AvailableStreams and Segment.SelectedStreams collections are empty. And it looks like SetVideoBitrateRange doesn't do anything.
Is there a way for user to select a bitrate while playing a composite manifest?


text:
Q: Can NSUserDefault be overwritten? There's a NSUserDefault with Value:
[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"aValue"];
Can it be overwritten by the another value? As:
[[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"aValue"];
If yes what may be the pros and cons?

A: Yes, the value will be overwritten. NSUserDefaults is used to store information even after your app is closed.
This is often desired when you want to (for example in a game) increase the number of levels the user has completed.
The only disadvantage I see is that if you forget the name of a key, you might accidentally write over the value already there when you didn't intend to.


text:
Q: Django submitting many to one relation models I'm trying to develop a Django application with relation to exercises per workout.
I currently have two tables, one that stores exercise (multiple exercises per workout) information, and one that stores the workout information with a workout that is a foreign key between the two.
However, I'm having trouble grasping the concept of submitting multiple exercises inside of one form without it getting fairly ugly very fast.
Keep in mind I am a Django noob so feel free to point out any redundant or useless code you see
Models.py
class workout(models.Model):
    user = models.ForeignKey(User , db_column='userid')

    datesubmitted = models.DateField()
    workoutdate = models.DateField();
    bodyweight = models.FloatField(null=True);
    totalreps = models.IntegerField()
    totalweight = models.FloatField()
    numsets = models.IntegerField();
    numexercises = models.IntegerField()
    workoutname = models.CharField(max_length=250)

    def getallexercises (self,id):
        all_workout_exercises = exercise.objects.filter(workoutid = id)
        return all_workout_exercises
    def get_absolute_url(self):
        return "/home"

class workoutForm(ModelForm):

    class Meta:

        model = workout
        exclude = ('user','bodyweight','totalreps','totalweight','datesubmitted')

class exercise(models.Model):
    workout = models.ForeignKey(workout,db_column='workoutid')
    userid = models.IntegerField();

    exercisename = models.CharField(max_length = 100)
    repetitions = models.IntegerField()
    weight = models.FloatField()

    def get_absolute_url(self):
        return "/home"

class exerciseForm(ModelForm):
    class Meta:
        model = exercise

views.py
class workoutCreate(CreateView):
    form_class = workoutForm
    model = workout

    def form_valid(self,form):
        createxercise(self.request,self.model.pk)
        form.instance.user = self.request.user;
        form.instance.bodyweight = self.request.POST['weight']
        form.instance.datesubmitted = datetime.datetime.now()
        form.instance.totalweight = summation(list(self.request.POST['weightinputboxes']))
        form.instance.totalreps = summation(list(self.request.POST['repinputboxes']))
        return super(workoutCreate, self).form_valid(form)

Where should I attempt to submit the exercises? I've read about inlineformset_factory but I'm not sure if I can make this work for creating multiple exercise rows in my table...
Thanks for the help guys, I appreciate it!

A: Modelformset is what you need. Look at the documentation, which has good examples explaining it.

A: You did not ask a specific question, but here a few things to clean up your code:

*

*By convention, class names in Python use CapWords (initial caps on each word). PEP8 provides the style guide for Python.

*You don't need the getallexercises method, django provides methods to do relationship lookups. For your case, if w was a workout instance, you can do w.exercise_set.all()

*You should also avoid hard coding urls in get_absolute_url, consider using reverse along with naming your url patterns.

Finally, you are on the right track with inlineformset_factory.


text:
Q: Inner async not working in Angular template? I'm relatively new to reactive programming and I'm trying to create an Angular service which can display notifications to the user. So far this is what I have:
https://stackblitz.com/edit/angular-rxjs-notifications?file=app%2Fapp.component.html
But I noticed that when you click the "Queue Notification" button my *ngIf="message$ | async" <div> appears correctly but the inner {{ message$ | async }} text doesn't appear unless you click the button twice in a row without clicking "Clear"
Thanks in advance!

A: Your first problem can be solved like this.
<div *ngIf="message$ | async as messages" >
  <div>{{ messages }}</div>
</div>

We store the result from the pipe in a local variable called messages. This way you avoid a situation in which the inner async pipe is not called after the outer one emits.
Live demo


text:
Q: Why is this left join fetch not retrieving an entry? I am attempting to write a Hibernate query to retrieve an entity for a given id. This entity has a collection of another entity, but I only want to retrieve non-deleted entities to populate the collection:
Top-level entity:
@Entity
@Table(name="rss_feed_definition")
public class RSSFeedDefinition extends BaseEntity {

    [...]

    @OneToMany(mappedBy="rssFeedDefinitionId")
    private Collection<RSSFeedProperty> rssFeedProperties;

    [...]

and the HQL:
em.createQuery("from RSSFeedDefinition definition left join fetch definition.rssFeedProperties property where property.deleted = false and definition.id = :id");

Why is it not returning the RSSFeedDefinition, even though I am left joining on the property (that has a deleted flag of true)?

A: I am not a Hibernate expert but in pure SQL your problem is this:
select *
from RSSFeedDefinition definition
left join property on definition.someField = property.otherField
where property.deleted = false <--- this is the problem because it filters all data
and definition.id = :id

It should be like this:
select *
from RSSFeedDefinition definition
left join property on definition.someField = property.otherField
                  and property.deleted = false
where definition.id = :id

to filter only when the join could be made.

A: JPA doesn't support any conditions in a JOIN FETCH statement. But in your case, you can use the following workaround:
TypedQuery<RSSFeedDefinition> q = em.createQuery("SELECT definition FROM RSSFeedDefinition definition LEFT JOIN FETCH definition.rssFeedProperties property WHERE property.deleted = false or property.deleted = IS NULL and definition.id = :id", RSSFeedDefinition.class);

If there is no property associated with the definition, its attributes are null. So, you need to check if deletedis false or null.


text:
Q: Create kmz file with jpegs that can be viewed in google earth I need to add photos to a kmz file however my file which has the coordinates does not have a time/date field. So far everything i've found suggests georeferencing jpegs for kmz/kml needs to link on time via a gpx file.
I have a csv with the following fields: ID, X, Y, photo_id
I would think this would be more straight forward than relying on a time stamp however it's proving difficult.
Any advice appreciated.

A: I have discovered a work around to create a kmz with photos:
Create a file (txt or csv) which contains an ID column, your x/y coordinates in two columns, and one column with the file path

Then run it through QGIS and export to KML.
Save the KML in a folder and add your photos inside another folder called "files" (so now you your KML file next to a folder called files inside a main folder). Zip the main folder and rename the file extension to kmz. The file will then open in Google Earth with your photos linked to each geographic point.


text:
Q: How to display message from contact form on the main page I have PHP contact form and I want the Message sent or failed message to be displayed inside the main page.. I have  tag after the submit button with id="notification" I want the message from send.php to be displayed inside of it.
My code is:
<form method="post" action="send.php">

        Name
        <input name="name" placeholder="Type Here">

        Email
        <input name="email" type="email" placeholder="Type Here">

        Subject
        <input name="subject"  placeholder="Type Here">

        Message
        <textarea name="message" placeholder="Type Here"></textarea>

        <button id="submit" name="submit" type="submit">Dergo</button>

    </form>

Send.php code:
<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $from = 'From: KontaktFormular';
    $to = 'albanianboy2@gmail.com';
    $headers = "From:" . $email . "\r\n";
    $headers .= "Reply-To: ".$email."\r\n";
    $headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

if(@mail($to,$subject,$body,$headers))
{
  echo "Mesazhi juaj u dërgua me sukses";

}else{
  echo "Gabim! Ju lutemi provoni përsëri.";
}
?>

A: Change this part of your code:
}else{
  echo "Gabim! Ju lutemi provoni përsëri.";
}

to:
}else{
      header('Location: mainpage.php?msg=1');
    }

Then on main page, you can have:
<?php
if(isset($_GET['msg']) && $_GET['msg'] = 1)
    {
?>

    Gabim! Ju lutemi provoni përsëri.

<?php
    }
?>

A: Put your code in a PHP file.
Your code:
<?php session_start(); ?>

 <form method="post" action="send.php">

    Name
    <input name="name" placeholder="Type Here">

    Email
    <input name="email" type="email" placeholder="Type Here">

    Subject
    <input name="subject"  placeholder="Type Here">

    Message
    <textarea name="message" placeholder="Type Here"></textarea>

    <button id="submit" name="submit" type="submit">Dergo</button>

     <?php
           if(!empty($_SESSION["notification"])){
                echo $_SESSION["notification"];
                unset($_SESSION["notification"];
            }
      ?>

</form>

Your send.php file:
<?php

session_start();

$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$from = 'From: KontaktFormular';
$to = 'albanianboy2@gmail.com';
$headers = "From:" . $email . "\r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";

$body = "From: $name\n E-Mail: $email\n Message:\n $message";

if(@mail($to,$subject,$body,$headers))
  {
   $_SESSION["notification"] =  "Mesazhi juaj u dërgua me sukses";

  }else{
   $_SESSION["notification"] = "Gabim! Ju lutemi provoni përsëri.";
   }
 header("location: YOUR_PHP_FILE_WITH_THE_FORM ");
 ?>

A: The message
$notification = "put your message";

The Javascript:
// Appeding notification to Body
$('#notification').html($notification);

Do this where you do your php check.
Put this css on top:
#notification{
    display: none;
}

Setup your div


text:
Q: Determining if a point is inside a path element in Raphael.js I have an SVG map and I want to draw some data using circles on the map. I want to make sure that the center of the circle drops inside the path. I can not use the bounding box, because yet it may be outside of the boundaries.
How can I determine if a point is inside a path?

A: Raphael.isPointInsidePath() - http://raphaeljs.com/reference.html#Raphael.isPointInsidePath


text:
Q: how to start with MS dynamics CRM from basics? Im new to Microsoft dynamics CRM, actually i moved from .NET to CRM, i dont know where to start.
Can anyone help to overcome this? In stackoverflow is there any chat room availalble regarding MS Dynamics CRM2011
Thanks in advance.

A: Start from Microsoft Dynamics CRM Developer Center. They have Dynamics CRM 2011 Developer Training Kit and of course you need CRM SDK

A: Depending on the specialization you're aiming for, there are different ways. Given your background, I'm guessing you're going for developer competence.
In the addition to @paramosh I can suggest that you register a new organization on-line (free for 30 days) and achieve the following.

*

*Make CRM say "Hello" when you open creation of a contact. (JavaScript)

*Make CRM Switch the first and last names when saving it. (C#/plugin)

You can get started by preparing your VS by installing CRM Developer Toolkit and getting CRM SDK. Then, you'll have a project group under C# called CRM Dynamics. In there, you can select plugin project. Do what you'd like in the Execute method. After that, you compile and register the assembly as well as the steps using plugin registration tool to your CRM. Test it and voilà!
This is the answer to your question (you're welcome to check it as an answer). If you need more detailed help, I suggest that you make a new post, hence splitting the huge starting threshold into pieces.
Try to set up each questions according to this.

*

*What do you want to achieve (small baby steps)?

*What have you tried (if possible, present some code, not 1000 lines)?

*What is happening that you feel is incorrect or unwanted?

The clearer questions you ask, the faster and better help people will be prone to offer you.


text:
Q: Different results with scipy.optimize.curve_fit using list and array Attempting to use scipy.optimize.curve_fit to fit a group of 2D elements using a 3 parameter exponential function, I get wildly different results if I treat the lists containing the data as lists or as numpy arrays. The MWE is below.
The final fitted parameters values, a b c, are:
FINAL abc: [  1.39852692e-10   1.00000000e+00   1.39020816e-01]

for the function that performs the calculations using a list (exp_3p), and:
FINAL abc numpy: [ 0.00826326  0.18603007 -0.02641734]

for the function that uses a numpy array (exp_3p_np).
I'm pretty sure this is related to the floating point accuracy when using an array, but it'd be great if I could get confirmation (and possibly some more information) from someone with more knowledge on this.

Add
This is apparently a scipy 0.12.0 issue, which is the version I had installed in my system when I tried this. I upgraded to 0.14.0, run the code again and now both functions return the exact same values.

MWE
import numpy as np
from scipy.optimize import curve_fit

def exp_3p(x, a, b, c):
    return a * np.exp(b * x) + c

def exp_3p_np(x, a, b, c):
    return a * np.exp(b * np.asarray(x)) + c

x = [11.250861, 11.750861, 12.250861, 12.750861, 13.250861, 13.750861,
    14.250861, 14.750861, 15.250861, 15.750861, 16.250861, 16.750861,
    17.250861, 17.750861, 18.250861, 18.750861, 19.250861, 19.750861, 20.250861,
    20.750861, 21.250861, 21.750861]
y = [0.045588760000000006, 0.046796000000000004, 0.0556935, 0.0634055,
    0.083095124999999992, 0.092670656249999997, 0.098264620000000011,
    0.086176929999999999, 0.1062696625, 0.124142703125, 0.13172655,
    0.13762596999999999, 0.17699458749999999, 0.200194234375,
    0.19936675000000001, 0.24553768749999999, 0.28308924000000002, 0.3130945,
    0.35024002999999998, 0.39341382000000003, 0.40971550000000001,
    0.40854391000000001]

popt, pcov = curve_fit(exp_3p, x, y)
print '\nFINAL abc:', popt

popt, pcov = curve_fit(exp_3p_np, x, y)
print '\nFINAL abc numpy:', popt


text:
Q: test ansible roles with molecule and boto3 I have ansible roles that creates servers, S3 buckets, security groups ... and I want to establish some unit testing using Molecule.
After some researches, I found out that Molecule is using Testinfra to run some assert commands on the remote/local host. That can work for my roles that create some servers like apache2, nginx.. but how about the other roles that are just creating some other aws resources like load balancers, autoscaling groups, security groups, or just s3 buckets? in this case, there will be no host nor instances.
It would be easy to make tests by Unittest and boto3 and call the AWS API, but my question is can I use molecule only and fire up an EC2 instance everytime I want to test my role of security group and then do something like this :
def test_security_group_has_80_open(host):
    cmd = host.run('aws ec2 describe-security-groups --group-names MySecurityGroup')
    return_code = cmd.rc
    output = cmd.stdout
    assert output.contains('"ToPort": 80')

That EC2 instance would have AWSCLI installed. Is this a correct way ? Is it possible to test all type of roles by Molecule by firing an EC2 that runs awscli calls ?

A: I cannot comment or else I would, but to speed things up you can configure Molecule to not manage the create and destroy sequences.  And use the delegated driver with the converge playbook having connection=local.  This way you can simply just create the the security group using the role without provisioning instances and use boto3 to confirm your changes are correct.
This way you only need your test environment to have the proper keys available to make the API calls using boto instead of also worrying about whether or not the EC2 instance does as well.


text:
Q: Publish/Subscribe API design : Unsubscribe and Update I was looking for a Publication/Subscription system that lets me modify a current subscription. I couldn't find any, so I figured I would build my own (in JavaScript).
I have basic methods for publish and subscribe as follow :
ps.publish(params, function(err, res) {
...
});

ps.subscribe(params, function(err, data) {
...
});

Now I want to add methods for  unsubscribing and updateing my subscriptions. Ie. if subscribe is CREATE, then unsubscribe would be DELETE and update would be PUT.
How should I design these APIs ?
Should update just be an unsubscribe followed by another subscribe ? How do I let the user choose which subscription ?
Also, I am planning to use the return value to return a future, since I find it a more elegant way to combine asynchronous calls, but I am not sure if this is the best option, I am still weighting it against a fluent API. For that reason, and unless I can choose clearly, I prefer not to use it for now.
unsubscribe seems to be the easy one, but I don't want to end up in the wrong place :
ps.subscribe(params, function(err, data) {
   ps.unsubscribe(data.id);
});

How should I structure these methods ?

A: Usually subscribe function returns another function which you use to unsubscribe. You could return from subscribe a function which when called without any argument would unsubscribe, but when called with another function as an argument, would update subscription.
In code it would look like this.
ps.subscribe = function (params, callback) {
  ...
  return function (callback) {
    if (callback) {
      ...
      // update - replace with a new callback
    } else {
      ...
      // cancel subscription
    }
  }
}

var changeSubscription = ps.subscribe(params, callback);
changeSubscription(anotherCallback); // update
changeSubscription(); // unsubscribe


text:
Q: US Street Address Search in dataframe I am trying to pull the street address from a column in the dataframe

Eg: 1831 XXX Ave Dallas, TX 75206

I want

Street Address : 1831 XXX Ave City : Dallas State: TX
  Zip: 75206

I used the following code to parse the usaddress. But I dont know how to assign it to separate columns
import usaddress
for row in df3['Address']:
     usaddress.parse(row)


text:
Q: hyper-v failed to start worker process: ran out of memory 0x800700E I have a Windows Server 2016 DataCenter with 0.5TB of RAM (there is a 497GB of RAM currently available) and I have three hyper-v virtual machines there. They have been running perfectly until we added a few discs into the physical server. Suddenly I cannot start any of them and even newly created VM cannot be started as well. Every VM request maximum 16GB of RAM. I receive the "failed to start worker process: ran out of memory 0x800700E" error.

I have tried to alter the virtual images to the minimal configuration possible (one processor, dynamic RAM with 512MB min memory) without any success. There are no Hyper-V events in the log. What can be possibly wrong?

A: I had the same issue today.  I checked Drive space, which had 800GB free so that should be way more than plenty.
Then I remembered that I had switched settings to dynamic memory allocation and upped the virtual processors from 1 to 2 the last time I was playing with the VM.  I don't know enough about hyper-v to understand why that would affect it this way but going back to a fixed amount of memory (8GB) and a single virtual processor, I was able to start the machine.
I don't know if this is relevant, but there were a bunch of windows updates queued up for installation so that may have affected the necessary memory to start it?
I am VERY new to the whole world of administering VM's in any hypervisor.
I just thought I would share my specific experience to this helpful gang of people in case it may help others somehow.


text:
Q: Combinatorics: $2n$ sets with $n$ entries, disjointness. The following combinatorial problem came up that seems easy but has turned out to be very intricate.
Assume that you are given $2n$ sets, say $S_1, \ldots, S_{2n}$ such that

*

*each $S_i$ has exactly $n$ elements,

*each element is in at most $n$ sets,
$\forall x \colon | \{ S_i | x \in S_i \}| \leq n$,

*for each $S_i$, there is an $S_j$ such that they are disjoint, $S_i \cap S_j = \emptyset$.

The final goal is to prove that it is possible to pick in each $S_i$ a different element $x_i \in S_i$ (i.e. $i \neq j \Rightarrow x_i \neq x_j$).
Assume we could prove that there is always a pair of elements $x,y$ such that none of the $S_i$ contains both $x$ and $y$.
Then the statement above follows easily by induction.
But how to prove this? Is it actually true?

A: Okay, the original problem can be solved using the marriage theorem.
Using the marriage theorem, it is sufficient to prove that each collection of $S_i$ of size $k$ contains at least $k$ many different elements.
For $k \leq n$, there is nothing to do since already one single $S_i$ contains $n$ elements.
For an arbitrary $k$, note that a collection of $k$ many $S_i$ contains $n \cdot k$ elements (counted with multiplicity).
As each element occurs in at most $n$ many $S_i$, this means we have at least $\frac{n \cdot k}{n} = k$ many different elements.
The problem whether it is possible to pick a pair of elements such that none of the $S_i$ contains both remains unanswered.


text:
Q: Find all integers such that $2n-1 | n^3 +1$ I try
$$2n-1| n^3 +1$$
$$\therefore 2n11 | 2n^3 + 2 -n^2(2n-1)$$
$$\therefore 2n-1| 4n-2$$
But but this is valid for all $n$. How to proceed? Thanks in advance
and I'm sorry if this is a duplicate, I don't see any similar questions

A: Mod $(2n-1)$, you have that $2n\equiv1$. Now suppose $(2n-1)$ divides $n^3+1$. So always mod $(2n-1)$:
$$
\begin{align}
n^3&\equiv-1\\
8n^3&\equiv-8\\
(2n)^3&\equiv-8\\
(1)^3&\equiv-8\\
1&\equiv-8\\
9&\equiv0
\end{align}
$$
So $2n-1$ must divide $9$. That doesn't leave too many options to check. (Be sure to look at both positive and negative divisors of $9$.)

A: Hint. If $(2n-1)\mid(n^3+1)$, then at least $(2n-1)\mid8(n^3+1)$. Hence
$$\frac{8(n^3+1)}{2n-1}=(4n^2+2n+1)+\frac9{2n-1}$$
is an integer. Hence $(2n-1)\mid 9$. Can you finish it now?

A: Problem.  Find all integers $n$ such that $2n - 1\, |\, n^3 + 1$.
Sol.  Let $(a, b)$ denote the greatest common divisor (gcd) of $a$ and $b$. Then
$$\begin{array}{lll}
(2n - 1, n^3 + 1) &= (2n - 1, n^3 + 2n) \\
&= (2n - 1, n^2 + 2) \mbox{ since } (2n - 1, n) = 1 \\
&= (2n - 1, n^2 + 2 + 4n - 2) = (2n - 1, n(n + 4)) \\
&= (2n - 1, n + 4) \mbox{ since } (2n - 1, n) = 1 \\
&= (2n - 1 - 2(n + 4), n + 4) = (-9, n + 4).
\end{array}$$
 Since $2n - 1\, |\, n^3 + 1$, $2n - 1\, |\, 9$. So, $n$ may be $-4, -1, 0, 1, 2, 5$.

A: $$ 2n-1\mid (2n-1)(4n^2+2n+1) = 8n^3-1$$
and $$2n-1\mid 8n^3+8$$ so $$2n-1\mid (8n^3+8) - (8n^3-1)=9$$


text:
Q: Link to WP-CONTENT not working We have a couple PDF files that are included in our WP-CONTENT folder which the links are not working. Trying to debug I created domain.com/wp-content/test.php and when I point the browser to this page I get a wordpress 404. Any idea what could be causing this? Below is a copy of our .htaccess file which is the only thing I can figure would be causing it but I don't see any issues.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule !(js|ico|gif|jpg|png|css|swf|flv|libraries|maint|admin|login|logout|reg) index.php [QSA,L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: I have experience with this issue and find solution maybe work with your problem

*

*Check Wp-Content Permission change to 775

*Delete or rename your .htaccess like .bkphtaccess

*Setting permalinks as default and save

*Turn back permalinks as your custom permalink and save
If allowed new .htaccess will create automatic, if not copy text at the bottom permalink settings save as file .htaccess in root Wordpress Instalation

try to access your link


text:
Q: jQuery and SharePoint 2010 - How can I tell is the page is in edit mode, using javascript? I have some javascript in a CEWP that I want to execute only when the page is in display mode.  I've used firebug to scour the page for some "msEditMode" type of variable or something I can rely on.
I've seen tons of questions and answers about how to tell if a page is in edit mode, from server side, but I cannot find a solution for how to tell if the page is in edit mode, client side.
Can anyone point me in the right direction?  Do I need to create a web part that simply emits such a variable?  (That seems like overkill to me.)
Thanks so much!

A: I found Amal Hashim's blog post: Javascript Detect SharePoint Page In Edit Mode There are different approaches for pages, wikis and publishing pages. I combined them into one  helper function:
function isEditMode() {
    var publishingEdit = window.g_disableCheckoutInEditMode,
        form = document.forms[MSOWebPartPageFormName],
        input = form.MSOLayout_InDesignMode || form._wikiPageMode;
    return !!(publishingEdit || (input && input.value));
}

This returns true if the page is being edited, and false if the page is in the view mode.

A: Rob's solution - looking at the button - looks like a viable approach.
Also, feel free to take a look at my Easy Tabs v5 code:
http://www.pathtosharepoint.com/sharepoint-user-toolkit/Pages/Easy-Tabs-v5.aspx
In the case of the Easy Tabs, I used a different approach because I needed the code to work in both SP 2007 and SP 2010. Here are the tests I included:
p.getAttribute("contenteditable")=="true"; //(where p is a Web Part zone)
document.forms[0].elements["MSOLayout_InDesignMode"].value=="1";
document.forms[0].elements["_wikiPageMode.value"]=="true"; //(wiki page)

A: A somewhat cheesy approach is to look for an element on the page that exists when the page is in edit mode.  For example, when in edit mode the "Editing Tools" ribbon appears and there is a save icon off to the left.  If you use the IE developer tools, you'll see the code for the save button looks like this:

So using jQuery you can check for the existence of "Save & Close" on the page...or choose a different element entirely -- one that is unique.
Keep in mind that different page types (blogs, wikis, web part pages) may or may not use different tags so this may not work across the board.  So double-check the page you're working with before you include the script.

A: Found more info.  If you want to do it through the object model, see if either of these links helps:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.publishing.webcontrols.editmodepanel.aspx
Some example implementations of the aforementioned class:
http://mystepstones.wordpress.com/2008/09/23/detecting-the-current-mode-displayedit/


text:
Q: Append Custom Tags in Swagger.yaml using swagger-maven plugin I am using swagger-maven plugin to generate swagger.yaml for a spring boot 2 application. The plugin works fine for the default feilds like info, description,vender extension etc.
However, I need to append some custom yaml to the generated swagger.yaml. ex:

X-client-integration
      Name:test
  Package: test package
   Catalogs:
        -id: x
         Seq:1
        -id:y
          Seq:2

This appended yaml can be hard coded or copied from a file from a project.
Is there any way to achieve this?


text:
Q: Add opacity to hex representation of color I have a color code, for example #EB5757 which is a kind of red. I want to add opacity to it 0.15 or 15%. After looking on this question I saw in the accepted answer that for 15% one must add 26 at the beginning.
So I did it: #26EB5757 but now the resulted color is not a red with opacity but a green. I'm using this in Javascript/React if this information is useful.
style = {backgroundColor: '#26EB5757'}

Any ideas on how to set that original red color to be opaque?

A: 8 digit hexadecimal color notation in CSS has the following format:
#RRGGBBAA

RR - red
GG - green
BB - blue
AA - alpha

You should use:
#EB575726 (for your 15% red)

A: I guess you can use convertor to get actual RGB representation of that HEX.
You may try this one
Then you can simple add your opacity into rgba like this  use backgroundColor: rgba(235,87,87, 0.15)


text:
Q: Securing actions in Grails 2 rc3 In Config.groovy I decided to secure all actions that have to do with editing content like so:
grails.plugins.springsecurity.interceptUrlMap = [
        '/admin/**' : ['ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'],

        '/*/create/**' : ['ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'],
        '/*/save/**' : ['ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'],
        '/*/update/**' : ['ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'],
        '/*/edit/**' : ['ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'],

        '/contactUs/create/new_message.html' : ['IS_AUTHENTICATED_ANONYMOUSLY'],
        '/**':               ['IS_AUTHENTICATED_ANONYMOUSLY']

]

... just wonder if this is sufficient or am I asking for trouble? Or what would be better/proper way of securing all 'create,save,update,edit' actions in all controllers?
Thanks in advance.

A: just two thoughts...

*

*what about deleting objects? I guess with this config, everybody can delete anonymously

*and that brings me to my second point: you implement security with a black list (what are the controllers and actions which should be not accessible unauthenticated), but you should implement security through a white list (what are the controllers and actions which are accessible unauthenticated). The second aproach would have avoided the 'delete' problem.

PS: I use shiro, so I have no experience with spring security and don't know how to whitelist controllers and actions.


text:
Q: mysql parse exception in simple case statement I am honestly baffled why this simple case statement would throw a parse exception
case when (table.col1 = 'A' and table.col2 = 'X') then
     coalesce(((col3 + col4)/(col5-col6))/floor(datediff(date('2022-11-11'), date('2022-08-27'))/7),0)
     when (table.col1 = 'B' and table.col2 = 'X') then
     coalesce((col3 + col4)/(col5-col6)),0) end as final

it works if I remove the second when statement


text:
Q: Position of $\mathbb{Z}[\sqrt{-d}]$ in class hierarchy for all integers $d$ For any real number $d,$ define
$$\mathbb{Z}[\sqrt{-d}]: = \{a+b\sqrt{-d}: a,b\in \mathbb{Z}\}.$$
It is well-known that $\mathbb{Z}[\sqrt{-2}]$ and $\mathbb{Z}[\sqrt{-1}]$ are ED but not fields,
$$\mathbb{Z} \bigg[ \frac{1+\sqrt{19}}{2} \bigg]$$
is a PID but not ED, $\mathbb{Z}[\sqrt{-5}]$ and $\mathbb{Z}[\sqrt{-4}]$ are UFD but not PID.
What interests me is that different $d$ places $\mathbb{Z}[\sqrt{-d}]$ in different position in the class hierarchy.

Question: For all integer $d,$ do we know the position of $\mathbb{Z}[\sqrt{-d}]$ is the class hierarchy?


text:
Q: Can i store 2 * 12bit unsigned numbers in a file as 3 bytes in C++ using bit fields? I`m working on an LZW compression app in C++. Since there are no data types that can store 12 bit numbers for representing table elements up to 4095 I thought that I can store 2 of those nrs as 3 bytes in a file and then read them as a struct with 2 unsigned short members. Is there a way to do that or I should just use unsigned short? This is what I have tried but it stores 4 bytes as there are 2 unsigned short members.
#define BITS 12

struct LZWStruct {
    unsigned short code1 : BITS;
    unsigned short code2 : BITS;
};

int main() {
    LZWStruct test;
    test.code1 = 144;
    test.code2 = 233;

    FILE* f = fopen("binary.bin", "wb");
    fwrite(&test, sizeof(test), 1, f);
    fclose(f);
}

A: Your question title and question body are two different questions with different answers.
No, you absolutely cannot store 3 * 12-bit unsigned numbers (36 bits) in four bytes (32 bits).
Yes, you can store two 12-bit numbers (24 bits) in three bytes (24 bits).
The bit fields in C++, inherited from C, that you are trying to use do not guarantee exactly how the bits are packed in the structure, so you cannot know which three bytes in the structure have your data. You should simply use the shift and or operators to put them in an integer. Then you will know exactly which three bytes to write to the file.
Then to be portable, in particular not dependent on the endianess of the machine, you should write bytes from the integer also using the shift operator. If you write using a pointer to the integer, it won't be portable.
In your example, you could have tried fwrite(&test, 3, 1, f), and it might work,  if the compiler put the codes in the low bits of test, and if your machine is little-endian. Otherwise, no.
So to do it reliably:
Put in an integer:
unsigned short code1;
unsigned short code2;
uint32_t test = (code1 & 0x3ff) | ((uint32_t)(code2 & 0x3ff) << 12);

Write to a file:
putc(test, f);
putc(test >> 8, f);
putc(test >> 16, f);

You can skip the intermediate step if you like:
putc(code1, f);
putc(((code1 >> 8) & 0xf) | (code2 << 4), f);
putc(code2 >> 4, f);

(In the above I am assuring that I only store the low 12 bits of each code with the & operators, in case the bits above the low 12 are not zero. If you know for certain that the code values are less than 4096, then you can remove the & operations above.)

A: From here, multiple adjacent bit fields are usually packed together. The special unnamed bit field of size zero can be forced to break up padding. It specifies that the next bit field begins at the beginning of its allocation unit. Use sizeof to verify the size of your structure.
The exact packing, however, may depend on platform and compiler. This may be less a problem if the data are later loaded by the same program, or some closely related, but may be an issue for some generic format.


text:
Q: How do I send a struct from C# to VB6, and from VB6 to C#? I need to send a struct from C# to a VB6 app, modify the data in VB6, and send the result back via windows messaging.  How do I do this?
I am able to send basic ints back and forth with PostMessage (using DllImport in C# and registering the vb6 app with windows messaging), but need to send more structured data, consisting of strings, ints, and decimal.
Looking for the easiest solution to implement passing of structures data back and forth.
Basic sample of VB6 type
Public Type udtSessionData
    SessionID As Integer
    SessionName As String
    MinVal As Currency
    PctComplete As Double
    NVal As Integer
    ProcessedFlag As Boolean
    ProcessedDate As Date
    Length As Integer
End Type

A: You have to assign GUIDs and use the MarshalAs attribute. .NET COM Interop handles the translation. Not too much different than a class. This series of posts illustrates what you need to do.

A: By using P/Invoke on .NET and importing CopyMemory in VB6 you can make this work but this is so much of a maintenance disaster I'd recommend running from anything like this.

A: Caveat:
Before I begin, people may be interested in noting items from your other question.
REF: How do I send/receive windows messages from VB6 and C#?
As mentioned here and in your other post, you should really reconsider trying to make this work. In particular, even if you are fine with the techniques here, your coworkers or other people who may have to maintain your code will be in for a really bad time. Note that the debugging process is also very tough in VB6- save often and use lots of breakpoints! Expect lots of crashes if there are errors in your code.
Also, PostMessage should not be used with this technique. It will require a lot more cleanup.
Solution:
I've enclosed a sample that can pass back a structure containing only a string and integer type. Making this work requires a lot of moving parts. We'll cover going from C# to VB in depth, as that is more tricky. The reverse is not as hard once you know how to do this.
First, on the C# side, you should declare your structure. Packaging up the structure is actually not bad in C#. Here is a C# sample class that is COM-visible that demonstrates how to wrap the structure up. The key is to use Marshal.StructureToPtr and Marshal.DestroyStructure on opposing sides of your call. Depending on the types involved, you may not even have to write code to map types, either. Use the MarshalAs attribute to flag the correct mappings for VB6. Most of the items in the enum used in MarshalAs correspond to different variable types used in VARIANTs and COM automation.
The buffer that is used here is supported by a HGlobal, which needs to be freed after the call is over. It also may be possible to use GCHandle here, which also requires similar cleanup.
MarshalAsAttribute Class @ MSDN
Marshal.StructureToPtr Method @ MSDN
Marshal.DestroyStructure Method @ MSDN
Marshal.AllocHGlobal Method @ MSDN
Marshal.FreeHGlobal Method @ MSDN
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace HostLibrary
{
    public struct TestInfo
    {
        [MarshalAs(UnmanagedType.BStr)]
        public string label;
        [MarshalAs(UnmanagedType.I4)]
        public int count;
    }

    [ComVisible(true)]
    public interface ITestSender
    {
        int hostwindow {get; set;}
        void DoTest(string someParameter);
    }

    [ComVisible(true)]
    public class TestSender : ITestSender
    {
        public TestSender()
        {
            m_HostWindow = IntPtr.Zero;
            m_count = 0;
        }

        IntPtr m_HostWindow;
        int m_count;

#region ITestSender Members
        public int hostwindow {
            get { return (int)m_HostWindow; }
            set { m_HostWindow = (IntPtr)value; } }

        public void DoTest(string strParameter)
        {
            m_count++;
            TestInfo inf;
            inf.label = strParameter;
            inf.count = m_count;

            IntPtr lparam = IntPtr.Zero;
            try
            {
                lparam = Marshal.AllocHGlobal(Marshal.SizeOf(inf));
                Marshal.StructureToPtr(inf, lparam, false);
                // WM_APP is 0x8000
                IntPtr retval = SendMessage(
                    m_HostWindow, 0x8000, IntPtr.Zero, lparam);
            }
            finally
            {
                if (lparam != IntPtr.Zero)
                {
                    Marshal.DestroyStructure(lparam, typeof(TestInfo));
                    Marshal.FreeHGlobal(lparam);
                }
            }
        }
#endregion

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        extern public static IntPtr SendMessage(
            IntPtr hwnd, uint msg, IntPtr wparam, IntPtr lparam);
    }
}

On the VB6 side, you will need to setup a mechanism to intercept messages. As the details are covered in your other question and in other places, I will skip over the topic of subclassing.
To unwrap a struct on the VB6 side, you will need to do this per-field, as there is no mechanism readily available to dereference a pointer value and cast it into a structure. Fortunately, you can expect field members to be aligned on 4-byte boundaries in VB6, provided you haven't specified otherwise in C#. This allows us to work field by field, mapping items from one representation to the other.
First, some module code to do all the support work. Here are functions and items of note.
TestInfo type - A mirror definition of the structure used on both sides.
CopyMemory - A win32 function that may be used to copy bytes.
ZeroMemory - A win32 function that resets memory to zero byte values.
In addition to those items, we make use of the undocumented VarPtr() function in VB6 to get the address of items. We can use this to index into the structure on the VB6 side. See the following link for details on this function.
How to get the Address of Variables in Visual Basic @ support.microsoft.com
Public Const WM_APP As Long = 32768
Private Const GWL_WNDPROC = (-4)
Private procOld As Long

Type TestInfo
    label As String
    count As Integer
End Type

Private Declare Function CallWindowProc Lib "USER32.DLL" Alias "CallWindowProcA" _
    (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal uMsg As Long, _
    ByVal wParam As Long, ByVal lParam As Long) As Long

Private Declare Function SetWindowLong Lib "USER32.DLL" Alias "SetWindowLongA" _
    (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

Private Declare Sub CopyMemory Lib "KERNEL32.DLL" Alias "RtlMoveMemory" _
    (ByVal pDst As Long, ByVal pSrc As Long, ByVal ByteLen As Integer)

Private Declare Sub ZeroMemory Lib "KERNEL32.DLL" Alias "RtlZeroMemory" _
    (ByVal pDst As Long, ByVal ByteLen As Integer)

Public Sub SubclassWindow(ByVal hWnd As Long)
    procOld = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf SubWndProc)
End Sub

Public Sub UnsubclassWindow(ByVal hWnd As Long)
    procOld = SetWindowLong(hWnd, GWL_WNDPROC, procOld)
End Sub

Private Function SubWndProc( _
        ByVal hWnd As Long, _
        ByVal iMsg As Long, _
        ByVal wParam As Long, _
        ByVal lParam As Long) As Long

    If hWnd = Form1.hWnd Then
        If iMsg = WM_APP Then

            Dim inf As TestInfo
            ' Copy First Field (label)
            Call CopyMemory(VarPtr(inf), lParam, 4)
            ' Copy Second Field (count)
            Call CopyMemory(VarPtr(inf) + 4, lParam + 4, 4)

            Dim strInfo As String
            strInfo = "label: " & inf.label & vbCrLf & "count: " & CStr(inf.count)

            Call MsgBox(strInfo, vbOKOnly, "WM_APP Received!")

            ' Clear the First Field (label) because it is a string
            Call ZeroMemory(VarPtr(inf), 4)
            ' Do not have to clear the 2nd field because it is an integer

            SubWndProc = True
            Exit Function
        End If
    End If

    SubWndProc = CallWindowProc(procOld, hWnd, iMsg, wParam, lParam)
End Function

Note that this solution requires the cooperation of the sender and the recipient. Because we do not wish to free the string field twice, we empty out the copy made on the VB6 side before returning control. It is undefined what will happen here if you attempt to assign a new value to field members, so avoid editing fields in the structure.
In mapping fields, UnmanagedType.BStr in C# is directly analogous to string in VB6.
UnmanagedType.I4 maps to Integer and Long in VB6. The other fields you have specified in your UDT also have equivalents, although I am unsure about DateTime in VB6.
The remainder of the VB6 app (Form source code) is straightforward.
Dim CSharpClient As New HostLibrary.TestSender

Private Sub Command1_Click()
    CSharpClient.DoTest ("Hello World from VB!")
End Sub

Private Sub Form_Load()
    CSharpClient.hostwindow = Form1.hWnd
    Module1.SubclassWindow (Form1.hWnd)
End Sub

Private Sub Form_Unload(Cancel As Integer)
    CSharpClient.hostwindow = 0
    Module1.UnsubclassWindow (Form1.hWnd)
End Sub

Now, in sending a structure from VB6 to C#, you need to do the reverse. For some simple structures, you may even be able to send just the address of the structure itself. If you need memberwise control, you can obtain suitable buffer memory by using GlobalAlloc, and then release it with GlobalFree. Memberwise copies may be performed the same way as parameters were unwrapped from C#, for each field. However, cleanup is simpler after the call. If you used a buffer, you only need to zero out the memory in the buffer before handing it over to GlobalFree.
GlobalAlloc Function (Windows) @ MSDN
GlobalFree Function (Windows) @ MSDN
When the message arrives on the C# side, use Marshal.PtrToStructure() to map an IntPtr into a .NET structure.
Marshal.PtrToStructure Method @ MSDN


text:
Q: Trying to pass Boolean value from child component to parent component Child Component:
import { Component} from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './app-test.component.html',
  styleUrls: ['./app-test.component.scss']
})
export class TestComponent implements OnInit {

  testBoolean: boolean;

  constructor() { }
}

Parent Component
.html
<app-test [testBoolean]="testBoolean"></app-test>
<button (click)="onClick()"></button>

.ts
import { Component, Input} from '@angular/core';

@Component({
  selector: 'app-test1',
  templateUrl: 'app-test1.component.html',
  styleUrls: ['app-test1.component.scss']
})
export class TestParentComponent {

  @Input() testBoolean;

  constructor() { }

  onClick() {
    console.log(this.testBoolean);
  }
}

When I run the application getting below error:
Can't bind to 'testBoolean' since it isn't a known property of 'app-test'.

*

*If 'app-test' is an Angular component and it has 'testBoolean' input, then verify that it is part of this module.

*If 'app-test' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

*To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

A: Dan is right,
import { Component,Input} from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './app-test.component.html',
  styleUrls: ['./app-test.component.scss']
})
export class TestComponent implements OnInit {

  @Input() testBoolean: boolean;

  constructor() { }
}

A: Your question is wrong but you mean to ask you are getting error in passing data from parent to child which as rightly said in answer need to use @Input() property .
If you want to pass data from child component to parent there are multiple ways one way is to use output property in child component
@Output() someEvent = new EventEmitter();
and on click of child component pass some data using emit
click() {
       this.someEvent.emit({isChild: true});
}

Now in parent component listen inside app-test using
<app-test (someEvent)="onClickEventCLicked($event)" >

in parent component's ts file you can access value inside
onClickEventClicked function
as
 onClickEventClicked(value: {test: boolean}) {
  console.log(value);
}


text:
Q: flutter:: Is it possible to load statefulwidget as a second page? I have main.dart, a.dart and b.dart.
When I run main.dart, the results of a and b are all displayed in one page. But I want the results of a and b to be displayed on different pages.
So I used MaterialPageRoute to make a visible on the first page and b on the second page.
but An error has occurred.

The named parameter 'records' is required, but there's no
corresponding argument.

My guess is that a and b are both written with statefulwidget, so the error appears.
Any advice on this?
a.dart example
class Recorder extends StatefulWidget {
  final Function save;

  const Recorder({Key? key, required this.save}) : super(key: key);
  @override
  _RecorderState createState() => _RecorderState();
}

class _RecorderState extends State<Recorder> {

b.dart example
class Records extends StatefulWidget {
  final List<String> records;
  const Records({
    Key? key,
    required this.records,
  }) : super(key: key);

  @override
  _RecordsState createState() => _RecordsState();
}

class _RecordsState extends State<Records> {

main.dart example
class HomePage extends StatefulWidget {
  final String _appTitle;

  const HomePage({Key? key, required String title})
      : assert(title != null),
        _appTitle = title,
        super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

main.dart example(error)
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: (){
        },
        child:  InkWell(child: Icon(Icons.mic),onTap: (){
          Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => Records());
              },),
      ),

A: You are missing your parameter for Records. Your solution is to either remove

required this.records

or change your Navigator.pushto this
 MaterialPageRoute(builder: (context) => Records(['']));


text:
Q: 1180 error:Call to a possibly undefined method addFrameScript in as3 package {
import flash.display.Sprite;
import flash.utils.*;

public class SetTimeoutExample extends Sprite {
    private var delay:Number = 1000; // delay before calling myDelayedFunction

    public function SetTimeoutExample() {
        var intervalId:uint = setTimeout(myDelayedFunction, delay,stopTime);
    }

    public function myDelayedFunction():void {
        if(arguments[0] ==fk.playheadTime)
        {fk.pause();}
    }
}
}//this is my document class named SetTimeoutExample.as

import flash.net.URLLoader;
import fl.video.*;
import flash.utils.getTimer;
import flash.events.Event;

fk.autoPlay = false;

var myLoaderInfo=new Object();

myLoaderInfo.myParamsLoaded = false;

myLoaderInfo.loaderComplete = loaderComplete;

this.loaderInfo.addEventListener(Event.COMPLETE, myLoaderInfo.loaderComplete);

myLoaderInfo.useParams = useParams;

var myParams:Object = new Object();
var myParamsLoaded:Object = new Object();

function loaderComplete(myEvent:Event)
{
this.myParams = this.loaderInfo.parameters;
this.myParamsLoaded = true;//Parametrelerin yuklendigine emin olduk.

this.useParams();

    fk.play(src);
}

var src:String;
var startTime:Number;
var stopTime:Number;

function useParams()
{
    var obj:Object = new Object();

var j;
for (j in this.myParams)
{
    if (j == "url")
    {
        src = this.myParams[j];
    }
    else if (j=="bas")
    {
        startTime = int(this.myParams[j]);
    }
    else
    {
        stopTime = int(this.myParams[j]);
    }
}
}

fk.addEventListener(VideoEvent.READY, bitti);
function bitti(eventObject:VideoEvent):void
{
    fk.seekSeconds(startTime);

}  //this is my player.fla

hi,i get this 1180 error in as3.how can i solve this?i google it but i can't apply the solutions to my my code.i'm really new to as3.thanks for any help.

A: Let me get this straight: you have set a Document Class in fla properties and are writing code directly in fla as well?
If this is the case, solution is simple: either write your code only in external .as files and not fla or do not use Document Class if you wish continue writing code on the Timeline.
The error code you get states that you have code on your Timeline which behaves like a MovieClip, while your Document Class extends Sprite and therefore is not aware of method called addFrameScript (this method is called while compiling code that is on the Timeline into SWF file).
In short, I'd adviced you to change
public class SetTimeoutExample extends Sprite {
to
public class SetTimeoutExample extends MovieClip {
and move all your fla code to Document Class.

A: Do you have any timeline code? AddFrameScript() is the method that gets called to allow timeline code to execute. I've seen that error myself.
Just make sure you don't have any code on the timeline in any of your assets and that should go away.

A: I solved the problem and now I'm successfully using an external AS class while implementing some other function on the TimeLine:
The problem can be solved just following this simple "rule":

*

*if you want to JUST load everything from the external CLASS, you have to "link" the .fla file to the .as ("Document Class"):
the timeline use the addFrameScript function

*if you want to USE something from the class, while doing something else on the timeline, you JUST HAVE TO PUT a similar line on the TimeLine:
var myClassObject:myClass = new myClass();
this.addChild(myClassObject);

A: I just had this issue as well. The problem was that my container movie clip was extending Sprite and inside, one of the controls was converted to flash component with properties... I have a feeling Flash was trying to set value of those properties on the timeline. Removing component from the stage and adding it from the library fixed the issue for me after 30 minutes of pulling my hair out....

A: Got
TypeError: Error #1034: Type Coercion failed: cannot convert the_game@2a9c50b1 to flash.display.MovieClip.
    at Game::Player/update()
    at the_game_itself/update()
with Bit slow...

A: If the error in the question (title) happens to you when adding code to a movieclip (not on the timeline), try this:
It might be that the library item (movieclip) has had it's actionscript properties set to inherit from Sprite (baseclass)... Some kind of coding bug... Check that movieclips actionscript properties (in the library, rightclick (on the movieclip)/properties).


text:
Q: AngularJS performance - too many watchers? I'm trying to debug an AngularJS website to improve performance of the load time. At the moment the browser freezes for 1-2 seconds on the first load with no caching.
From reading various posts I learned that watchers are often the biggest problem for performance in AngularJS apps.
Here is a screenshot from batarang:

But, how many is too many watchers?  7k~ is a lot, but is that too many?
When debugging in the Chrome console CPU profile, I have a hard time figuring out what calls h - k - z.onload and in general how to improve performance besides having less watchers:

I know it's a broad question, but I'm looking for any performance tips for AngularJS.

A: Angular start to hit the performence wall when having more then 2000 watchers.
If you have 7K+ watchers in your app, it is due to bad design.
see here https://coderwall.com/p/d_aisq/speeding-up-angularjs-s-digest-loop
and here How does data binding work in AngularJS?


text:
Q: Как убрать лишние отступы и ничего не сломать Доброй ночи. получил такое замечание по коду от ревьювера
1)Браузер автоматически добавляет марджины сверху и снизу всем тегам заголовков (h1-h6) и параграфов (p). Нужно пройтись по всем классам на странице и по удалять лишние марджины.
Вот вопрос в следующем
есть ди какой то способ сразу узнать где лишние отступы ? или на каждый элемент в браузере пкм и там отслеживать , меняется что то или нет ?.

A: Просто добавьте в самом начале CSS-кода:

* {
  pading: 0;
  margin: 0;
  box-sizing: border-box;
}

Это сбросит все внешние и внутренние отступы. Если вы работаете с препроцессором и имеете несколько файлов, соединяющихся в один, то прописывать это нужно в начале самого главного файла.


text:
Q: checking on success of write.csv in R In R, how do I verify that write.csv(my.data.frame, file='test.csv') was successful without re-reading it in again?  It doesn't seem to return anything.  I was thinking of doing a file.exists('test.csv') and then grabbing a timestamp before and after the write.csv() and checking that the timestamp on the file is between the two?  Any suggestions?

A: You may use the function try():
res <- try(write.csv(1:100, "SOME GOOD PATH/temp.csv"))
is.null(res)
# [1] TRUE
res <- try(write.csv(1:100, "SOME BAD PATH/temp.csv"))
is.null(res)
# [1] FALSE
class(res)
# [1] "try-error"


text:
Q: How to get the css value of transform directly using jquery that witch set as percent I  am set transform: translate(200%, 700%);
when i try to read it by code below it take me this valuse as px :
calculateAllowed = function (obj) {
        var matrix = $(obj).css('transform');
        alert(matrix);
        var values = matrix.match(/-?[\d\.]+/g);
        var x = values[4];
        alert(x);
};

x is an integer number
I expect to get 200 or "200%".
How can i get it as percent that i set first time?

A: You need to divide it by the width and multiply it by 100 to get it in percent form.

function calculateAllowed(obj) { //just for easy testing
        var matrix = $(obj).css('transform');
        console.log(matrix);
        var values = matrix.match(/-?[\d\.]+/g);
        var x = values[4];
        var end = x / $(obj).width() * 100;
        console.log(end);
};

calculateAllowed( $("div") )

afwe

A: Instead of
$(element).css('transform');

You can use:
If using javscript:
element.style.transform

Using Jquery:
$(element).style.transform

FIDDLE
Snippet using Javascript

function myFunction() {
  var matrix = document.getElementById("myDIV").style.transform;
  alert(matrix);
  var values = matrix.match(/-?[\d\.]+/g);
  alert(values);
}
#myDIV {
  margin: auto;
  border: 1px solid black;
  width: 200px;
  height: 100px;
  background-color: coral;
  color: white;
}
<button onclick="myFunction()">Try it</button>

myDIV


text:
Q: Django - list of choice in a ModelForm I want to customize a modelForm with a list of choices from 0 to 10.
I tried to add a widget, but can't figure out how to make it work :
class Abonnements(models.Model):
    id                          = models.AutoField(primary_key=True)
    nombre_d_exemplaire         = models.IntegerField(blank=True, null=True)
    numero_d_adherent           = models.IntegerField(blank=True, null=True)
    date_d_enregistrement       = models.DateTimeField(blank=False, null=False)  # This field type is a guess.
    premier_numero_a_servir     = models.FloatField(blank=True, null=True)
    remarques                   = models.TextField(blank=True, null=True)
    destinataire_facture        = models.TextField(blank=True, null=True)
    adresse_facture             = models.TextField(blank=True, null=True)
    code_postal_facture         = models.TextField(blank=True, null=True)
    ville_facture               = models.TextField(blank=True, null=True)
    personne                    = models.ForeignKey('personnes.Personnes',on_delete=models.PROTECT,)

    class Meta:
        db_table                = 'abonnements'
        ordering                = ['-date_d_enregistrement']

class  AbonnementsForm(ModelForm):

    class Meta:
        model   = Abonnements
        fields  = [ "nombre_d_exemplaire"    ]
        widgets = {'"nombre_d_exemplaire"    : forms.ChoiceField(widget=forms.RadioSelect, choices=range(10))  }

Gives me an error :
'ChoiceField' object has no attribute 'is_hidden'

A: I think that the choices parameter expects a List of Tuples. It should be something like:
forms.ChoiceField(widget=forms.RadioSelect, choices=[(x, x) for x in range(10)])

Because we need to pass a "value" and a "key" format, the first one is used as value on the inputs and the second one as a Label for that value. You also can use something like:
[('first', 'First'), ('second', 'Second'), ('third', 'Third')]

A: If I understand correctly your question,
you can do as follows:
 first create a list before the class definition:
 options = []
 for i in range(0,11):
     options.append((i,i))

then add the needed field explicitly:
 number = forms.ChoiceField(choices=options)


text:
Q: Forgetting to merge changes from trunk to branch Recently, I forgot to merge changes from trunk to our maintenance branch.  This caused us to rebuild - twice - and put QA on hold for two days while we fixed the mess.
Normally, when committing to both branches, I commit a single changeset to trunk, and immediately merge it over to the maintenance branch.
However, this time there were 12 changesets spanning many code review changes, and I failed to merge all of the changes over.  I had only merged one change over, which completely threw me off - I thought I remembered it was a rollup commit of all of the other changesets, but it wasn't.
After some development discussion, we decided that the best approach would be to make 1-to-1 trunk and maintenance branch commits, so you could visually verify that all of the code was there.
Is there a way to enforce changeset commits for a given fix-for version?
We use JIRA, Fisheye, and Crucible, and our Fisheye workflow won't let you resolve an issue unless the code reviews are complete.  I'd like something similar that enforced parallel checkins on trunk and maintenance branches, based on the fix-for version specified in the issue.
Or is there a better solution to this whole mess besides "don't do that"?

A: Obviously this only works if you use git, but here's how I'd approach it...
Each feature request, and each bug, get their own branch locally. The developer then does all the changes needed. When they're done, rebase the branch and merge/split the commits into logical work units. For small features and for bugfixes, this shouldn't be hard to keep them at a single commit. For larger features, you may want to have multiple commits, eg: "Add interface for foo". "Add implementation of foo". "Have Whizbang use the new foo feature". The point is to keep all logically connected lines of code in one commit. At that point, the work unit has one (or a set) of commits. Your bug tracker should let you link commits to tickets. The bugfix ticket would link to the bugfix commit and it should be easy to see that the commit was merged onto the proper release branch.

A: At my job we have home-built software that helps us start/end projects.  When you land the project, it creates a tree, applies your changes, then merges any changes in the trunk.  (You resolve conflicts there.)  When you end it commits those (and deletes your project).
When you start a project you specify whether it is a hotfix or not.  If it is a hotfix, then when you land it it builds patches both to the trunk and the maintenance branch.
Of course now you have to remember to make the project a hotfix.  But it makes it easy to make sure that a whole lot of related changes all will get committed together where they need to be.

A: What you did is likely a result of a process defect that requires you to remember to do it, (hence you do it immediately), with no tracking that it did really get done.
Question : Can you easily produce a report that confirms all merges have been complete. If so, can the failure by a single individual of a single action cause the report to be incorrect (i.e. does you process have a single point failure mode)?
You actually have 2 changes required. One is delivery to the main branch and one is delivery into the maintenance branch. Use Jira to track these as two related deliveries.
This has advantages, such as you can defer a merge into the maintenance it desired, and still see what has been deferred, but does have an overhead.  It also may make your reporting system to management report more defects that you really have, depending how you record and report these.


text:
Q: Using playlistitem.insert via one link I've been able to do video searches and read info using just one link that starts with googleapis.com but for the playlistitemsinsert to put videos into a playlist, I'm having trouble with the syntax. I'm trying to randomize the order of videos in a YouTube playlist. I understand you can shuffle play but its easier for me to remove the videos if they're played in chronological order, also its easier to go back to a video you recently watched.
I have all of the video ids in a column in excel I'm just not sure how to use vba to do a POST HTTP request to insert the videos into a playlist. Can you help me with the syntax on this?

A: Although not using excel as database This works using youtube api. and users youtube created play list . shuffles the play list into new order every time page is refreshes

*

*Load YT-player API.

*Load YT-playlist user playlist id "**.youtube.com/playlist?list=PLo16_*******"

*To Shuffle playlist use > player.setShuffle(true);

*To Start YT-player at video 1 in shuffled playlist use > player.playVideoAt(0)
working demo Responsive shuffled YouTube Playlist on Google sites
code jsfiddle.net
<!DOCTYPE html>
<html>
<!-- Responsive YouTube shuffled playlist player -->
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag.
style =  replaces  size in the player script makes it responsive -->

<div style=" top: 0; left: 0; width: 100%; height: 100%; position: absolute;"
id='player'>
</div>
</body>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: {
  autoplay: 0,
  loop: 1,
  controls: 1,
  showinfo: 1,
  frameborder: 1,
  'listType': 'playlist',
  'list': "PLo16_DLriHp4A8BvkJFZfO_4KDVv7yGgy", // your YouTube playlist id here
 },

 events: {
  'onReady': onPlayerReady,
  'onStateChange': onPlayerStateChange
 }
 });
 }

  // 4. The API will call this function when the video player is ready.

 function onPlayerReady(event) {
  // first shuffle play list

 player.setShuffle(true);

  // Onload and on refresh shuffles the users YT playlist but always starts playing
  // the first video in the original list at its new index position
  //ie. video (1) = video( new shuffled pos ?)
  // to get over this we can start the player at the new shuffled playlist
  //video 1(index=0) this changes every time it's refreshed

 player.playVideoAt(0)

 }
  // 5. The API calls this function when the player's state changes.
  //  option to to add bits
 function onPlayerStateChange(event) {
  const player = event.target;
 }

 </script>

 </html>


text:
Q: c++: How do I safely cast a const double** to a const void** The following code gives a compiler error in C++:
const double** x;
const void** y = x;

How do you get a const-safe equivalent?
Of course, you can get this to work with a simple cast:
const void** y = (const void**) x;

But surely the compiler should know that this ok? Why does it complain?

A: Why should the compiler know that that is OK? I think you want the following instead
void *y = x;
x = static_cast<const double**>(y); // casting back needs static_cast or c-style cast

A void** doesn't have the special properties that a void* has (that of being an universal data pointer).

A: Why does it complain?
Because it's NOT OK.
There's a FAQ explaining why but I can't seem to find it right now.
Your C-Style cast resolves to a reinterpret_cast, which tells the compiler to ignore types.