text:
Q: Why does AccordionSummary background change to grey when clicking inside TextField in Material-UI? I am using Material-UI's Accordion and inside AccordionSummary I have a <TextField /> (which is actually controlled by Formik and formik-material-ui) and the background of AccordionSummary turns grey when clicking inside the field only. I don't want it to do this and it doesn't appear to be anything configured by the Accordion API, unless I am missing something. How can I stop it from behaving this way?
I've recreated the issue on Codesandbox.
Here's the full code from the sandbox:
import React from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import { TextField, CheckboxWithLabel, Select } from "formik-material-ui";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import FormControl from "@material-ui/core/FormControl";
import MenuItem from "@material-ui/core/MenuItem";
import Button from "@material-ui/core/Button";
import Accordion from "@material-ui/core/Accordion";
import AccordionDetails from "@material-ui/core/AccordionDetails";
import AccordionSummary from "@material-ui/core/AccordionSummary";

export default function App() {
  return (
    <div className="App">
      <Formik>
        <Form>
          <Accordion>
            <AccordionSummary>
              <FormControl fullWidth>
                <Field
                  component={TextField}
                  name="itemName"
                  placeholder="What do you want to buy?"
                  variant="outlined"
                />
              </FormControl>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container>
                <Grid item xs={2}>
                  <Box pt={2}>
                    <FormControl fullWidth>
                      <Field
                        component={TextField}
                        name="quantity"
                        label="Qty"
                        type="number"
                        variant="outlined"
                        size="small"
                      />
                    </FormControl>
                  </Box>
                </Grid>
                <Grid item xs={2}>
                  <Box pt={2} pl={1}>
                    <FormControl fullWidth>
                      <Field
                        component={TextField}
                        name="volume"
                        label="Vol"
                        type="number"
                        variant="outlined"
                        size="small"
                      />
                    </FormControl>
                  </Box>
                </Grid>
                <Grid item xs={2}>
                  <Box pt={2} pl={1}>
                    <FormControl label="Type" size="small" fullWidth>
                      <Field
                        component={Select}
                        name="volumeType"
                        as="select"
                        variant="outlined"
                      >
                        <MenuItem value="g">grams</MenuItem>
                        <MenuItem value="kg">kg</MenuItem>
                        <MenuItem value="ml">ml</MenuItem>
                        <MenuItem value="cl">cl</MenuItem>
                        <MenuItem value="litre">litre</MenuItem>
                        <MenuItem value="pint">pint</MenuItem>
                        <MenuItem value="pack">pack</MenuItem>
                      </Field>
                    </FormControl>
                  </Box>
                </Grid>
                <Grid item xs={4}>
                  <Box pt={2} pl={1}>
                    <FormControl fullWidth>
                      <Field
                        component={TextField}
                        name="brandName"
                        label="Brand"
                        variant="outlined"
                        size="small"
                      />
                    </FormControl>
                  </Box>
                </Grid>
                <Grid item xs={2}>
                  <Box pt={2} pl={1}>
                    <Button
                      type="submit"
                      variant="contained"
                      color="primary"
                      disableElevation
                      fullWidth
                    >
                      Add
                    </Button>
                  </Box>
                </Grid>
              </Grid>
            </AccordionDetails>
          </Accordion>
        </Form>
      </Formik>
    </div>
  );
}

A: What you are seeing is the focused styling for AccordionSummary. You can observe this in the Accordion demos as well by clicking on an accordion and then using the Tab key to move to the next AccordionSummary. This is there for accessibility reasons so that the user can tell where focus is within the Accordion when navigating with the keyboard.
You can override this with the following:
import MuiAccordionSummary from "@material-ui/core/AccordionSummary";
import { withStyles } from "@material-ui/core/styles";

const AccordionSummary = withStyles({
  root: {
    "&.Mui-focused": {
      backgroundColor: "inherit"
    }
  }
})(MuiAccordionSummary);


text:
Q: 'The local variable XXX may not have been initialized' error - why does it arise in my code, while doesn't in this example? Whenever I declare a local variable in a method and then assign values to it in a conditional like if/else block or try/catch, and then try to return the variable, I get the compiler error
The local variable XXX may not have been initialized

I understand that the if/else or try/catch block might not be executed under certain conditions, and so the variable will not be initialized, and thus the error.
But more often than not, I come across code in which they do not initialize the variable and still it works.  For example, on this page, see the following method:
public int getItemViewType ( int position ) {
        int viewType;
        if ( groups.get ( position ).getImagePath () != null ) {
            viewType = TYPE_IMAGE;
        } else {
            viewType = TYPE_GROUP;
        }
        return viewType;
    }

When I wrote the same method, I got the error on the return statement. The only difference of my method from this one is that I have only if and else-if blocks, and no else block.
Do people suppress this error through some annotation on the method or something, I don't think so.
So why don't they get the error, while I do?

A: It works because when you reach the return statement, viewType is guaranteed to have a value.
    int viewType;
    if ( groups.get ( position ).getImagePath () != null ) {
        viewType = TYPE_IMAGE;
    } else {
        viewType = TYPE_GROUP;
    }
    return viewType;

It will have either TYPE_IMAGE or TYPE_GROUP
In your code you might be doing some thing like :
     int viewType;
     try{
        // some code which can cause an exception.
        viewType=something;

     } catch(Exception e){}

     return viewType;

or
       int viewType;
       if(some condition){
          viewType=something;
       }
       return viewType;

In both these cases, you can not guarantee that viewType will have a value when you reach return statement.
If the try block throws any exception or the condition fails in your if block, viewType will not have any value.
That is why you will get the error. But in the code you have posted it's not the case, the code guarantees to have some value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python requests - login and store the cookies for later use I want to start the script to login into one website and store the cookies in some file, and later i wanna start the script to visit other pages of that website but with same cookies, so I do not have to login everytime for everypage that I wanna visit:
import requests
import random
import sys
link = sys.argv[1]
link = link.replace("%26", "&")
link = link.replace("######", "&")
if len(sys.argv) > 3 :
    username = sys.argv[2]
    password = sys.argv[3]
else:
    username = ''
    password = ''
###LOGIN PART###
payload = {
    'username': username,
    '_spring_security_remember_me': '',
    'password': password,
    'targetUrlNonEncoded': 'false',
}

UAS = (
       "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
       )
ua = UAS[random.randrange(len(UAS))]
headers = {'user-agent': ua}
s = requests.Session()
r = s.post(link, headers=headers,data = payload)
print(r.text.encode('utf8'))

I did this and it works great, can someone help me how from this i can save the cookies and use them again later?


text:
Q: The fields of Model in Extjs4 can not contains some special characters, such as dot, dash I have to maintain a legacy project which developed by extjs4.2. But i found the grid cannot use a  store with dynamic fields. And the field contains character dash and minus that cause errors. Please just take a look the following code snippet and focus on the fields of the grid store.  It will throw syntax error 'Invalid left-hand in assignment'.

    Ext.create('Ext.grid.Panel',{
       title:'mygrid',
       store: Ext.create('Ext.data.Store'{
         fields:['group','alfa=-2.0','alfa=0','alf=2.0'],
         data:[
            {'group':'beta', 'alfa=-2.0':1.3, 'alfa=0':1.4, 'alfa=2.0':1.5 },
            {'group':'beta', 'alfa=-2.0':1.3, 'alfa=0':1.4, 'alfa=2.0':1.5 },
         ]
       }),

     columns:[
        {'dataIndex':'group','header':'group'},
        {'dataIndex':'alfa=-2.0','header':'alfa=-2.0'},
        {'dataIndex':'alfa=0','header':'alfa=0'},
        {'dataIndex':'alfa=2.0','header':'alfa=2.0'}
     ]
    });

A: Your sample contains a syntax error. Ext.create('Ext.data.Store'{ there is a , missing after the first argument.
In the background Ext is calling recordDataExtractorTemplate what will try to access the record values with the dot notation. This results a code value = source.alfa=-2 && source.alfa=-2.0; what is obviously syntactically incorrect.
Any of the solutions below may work. It is up to you which one you go for.

*

*The quickest solution to change the field names in your code if possible if those fields are not used widely in the app.

*You can check if later versions of Ext fixes this problem. However the migration can be a pain.

*You can create an override of Ext.data.reader.Reader and patch the failing function.


text:
Q: troubleshoot a timeout happening while deploying via VS Hi I am getting timeout error while trying to deploy my sp solution via visual studio 2010. It happens when my a particular feature is trying to activat. The generic error message I get goes something like this:

Error occurred in deployment step 'Activate Features': A timeout has
  occurred while invoking commands in SharePoint host process.

I've tried increasing the timeout in the IIS console for the SharePoint website (via the Advanced settings Dialog).
How can I solve this problem?

A: There is a registry value that doesn't exist by default, that can be added to change the timeout of the server, I think on development machines the default SP settings dont allow for deployment of large .WSP solutions, or could also be slower platforms.
Goto the following regustry key:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\SharePointTools
Add the following as a DWORD (wont be there by default)
ChannelOperationTimeout
REG_DWORD that specifies the time, in seconds, that Visual Studio waits for a SharePoint command to execute. If the command does not execute in time, a SharePointConnectionException is thrown.
The default is 120 seconds.
This explains at the bottom some registry keys that can be added for debugging, which includes the one mentioned.

A: it could be related to ChannelOperationTimeout
http://msdn.microsoft.com/en-us/library/ee471440(v=vs.100).aspx
Also, don't forget to restart Visual Studio


text:
Q: How to suppress compiler warnings en masse in Xcode Within several projects, I am using 3rd party code that produce more than a few compiler warnings. I obviously do not want to go through and modify code of actively updated 3rd party projects.
This leaves me with a lot of unnecessary warnings that drown out warnings in MY code.
I have used some compiler flags to suppress specific warnings on a per file basis, but that is much too tedious for open source code with 10-20 .m files.
Is there a way all warnings by Xcode group or file path? Or does somebody have a better suggestion?
(FYI: I am using the LLVM 1.5 compiler)

A: In my experience, XCode 3.x seems to only show the warnings for files that have actually been compiled in the most recent build, so if you build the project, modify a single file and then build the project again, you'll only see the warnings for the modified file. I generally find this to do more harm than good (especially since in Objective-C it's only a warning to call a selector that doesn't exist!) — and thankfully it's fixed in XCode 4 — but in your case in might be useful.
However, for various reasons you might want to consider putting the third-party code into a Framework. This wouldn't automatically suppress the warnings (although it might make it easier to suppress them) but it would mean that the third-party code was compiled into a library and therefore wasn't part of your normal compile cycle.

A: Turning off warnings on a per file basis is super simple. All that is required is a compiler flag. Here's the step by step process.

*

*Open the Project Navigator in Xcode

*Click on the Project icon at the very top of the navigator

*In the resulting detail pane select the target that you are working
with

*Select "Build Phases"

*Expand "Compile Sources"

*In the list locate the file that you're interested in

*Double click the column under the "Compiler Flags" column next to
your file

*Add a -w to the resulting dialog

*Click "Done"

*Build your now warnings free project

here is the reference link
http://blog.bluelightninglabs.com/2011/12/suppressing-xcode-warnings-on-a-per-file-basis/

A: This is certainly not the easier solution, but you could go through these third-party libraries and fix their warning-causing bugs and submit patches. Then, the warnings go away, the bugs are fixed, and everybody gets to enjoy both improvements.
(How many warnings you'll be able to squash this way will depend on what they are: Deprecated-API warnings may be unavoidable if the library needs to support an older version of Mac OS X or iOS where the now-deprecated APIs were the only way.)


text:
Q: How to set data before login and get it after log in, Magento 1.9.1.0 I'm developing a module in Magento 1.9. My module has form and to submit the form, the user needs to log in. After login, I wanna get data of the form which user submit before login.
I set:
Mage::getSingleton('module/session')->setFormData()

I get:
Mage::getSingleton('module/session')->getFormData()

But when I debug, after customer login, I get form data is null.
How can I set form data like above?

A: Use below code for it:
Mage::getSingleton('core/session')->setFormData() ;

You can retrieve data using below code:
Mage::getSingleton('core/session')->getFormData();


text:
Q: C# .net Windows Forms Listview with image in Detail View I want something like this develop using C# .net for Windows Forms. (ListView Details View). Putting a Image is the problem.

Help me ..!!
Thank You
Yohan

A: You may want to take a look at this Code Project entry.
Extended ListView

A: Hope that the following code can help you out.
using C#
ImageList il = new ImageList();
il.Images.Add("test1", Image.FromFile(@"c:\Documents\SharpDevelop Projects\learning2\learning2\Koala.jpg"));

listView1.View = View.LargeIcon;
listView1.LargeImageList = il;
listView1.Items.Add("test");

for(int i = 0; i < il.Images.Count; i++)
{
    ListViewItem lvi = new ListViewItem();
    lvi.ImageIndex = i;
    lvi.Text="koala 1";
    listView1.Items.Add(lvi);
}

Running this kind of code can get you the image and the text in a listview.
For further more details, refer to this post


text:
Q: RealmDB does not get populated New to Realm... so hopefully a simple fix!
I have a data object of:
class GasFile : Object {
  @objc dynamic var gasFilename : String = ""
 // @objc dynamic var gasCategory : String? = ""
}

In my ViewController I have the following function:
func PopulateRealmWithFilenames() {
    let fm = FileManager.default
    var path = Bundle.main.resourcePath!
    path += "/NBTFiles"
    //let items = try! fm.contentsOfDirectory(atPath: path)
    let items : [String] = try! fm.subpathsOfDirectory(atPath: path)

    for item in items {
        do {
            print("item for realm is: \(item)")
            try self.realm.write {
                let newGasFile = GasFile()
                newGasFile.gasFilename.append(item)
                print("newGasFile written ok")
            }
        } catch {
            print("Error writing new item to Realm \(error)")
        }
    }
}

This sets up the RealmDB ok, but never gets populated.
 The aim of the function is to save all the filenames (not paths) of the files stored in a folder called NBTFiles.
 I get the 'newGasfile written ok printed out' so it is getting into the loop.
datatype error ?
(I know I could just put it into an Array, but I want to use realm)

A: how do you want to add new object to realm without using adding function ?
you should use  realm.add(object: newGasFile)
try this
func PopulateRealmWithFilenames() {
let fm = FileManager.default
var path = Bundle.main.resourcePath!
path += "/NBTFiles"
//let items = try! fm.contentsOfDirectory(atPath: path)
let items : [String] = try! fm.subpathsOfDirectory(atPath: path)

for item in items {

    do {
        print("item for realm is: \(item)")
        try self.realm.write {
            let newGasFile = GasFile()
            newGasFile.gasFilename.append(item)
            realm.add(object: newGasFile)
            print("newGasFile written ok")
        }
    } catch {
        print("Error writing new item to Realm \(error)")
    }
}
}


text:
Q: PlayRunHook afterStopped method not being called on Windows I'm implementing the Play framework's PlayRunHook trait and overriding the afterStarted and afterStopped methods like this:
object PlayHooks extends PlayRunHook {
    override def afterStarted(add: InetSocketAddress): Unit = {
        println("started")
    }

    override def afterStopped(): Unit = {
        println("stopped")
    }
}

On a Linux machine, both hooks are called as expected (the former at sbt run and the latter on CTRL + D or CTRL + C).
On Windows, the afterStarted hook is called but when I stop sbt, it stops immediately and doesn't call the afterStopped method at all. If I run it with a debugger, a breakpoint in the afterStopped method never gets hit.
Is there some Windows-specific thing I need to do for this to work?


text:
Q: bbpress plug-ins and buddypress Is it possible to use the standalone bbpress plug-ins with a buddypress site - using bbpress forums site-wide and disabling the buddypress forums. I need to add moderation. I have decided not to use buddypress forums.

A: Yes, it is possible.  However, your buddypress theme must be compatible with bbpress or else /forums won't be setup correctly.
Reference: http://devpress.com/blog/how-to-make-a-site-like-devpress/

bbPress for Forums or Message Board Although BuddyPress has group
  forums, I don't have it enabled on DevPress. It's because I prefer
  having a central forum for interaction and support instead of having a
  forum for each group. When DevPress get to 10,000 members or more then
  it would make sense to turn on group specific forums. When nurturing a
  community or social network, it's important to make your site not feel
  empty. Only when you have more members than you can handle do you let
  everything go wild. But before that, you need to have one central
  place for member interaction.


text:
Q: Post Back variable value for captcha i want the value of $code variable to get on my other page--- captcha.php.
captcha_image.php

$captcha = new CaptchaCode();  //class defined in captcha_code.php
$code = str_encrypt($captcha->generateCode(6));  //function defined in captcha_code.php
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,str_decrypt($code));

captcha.php

<input type="hidden" name="security_check" value="<?php echo $code; ?>">  // want value of $code here

I cant include captcha_images.php file in my code and even dont want it to be done using sessions, tried that way.If anyone has a solution for this, please help me to solve this issue.

A: Better solution is save code into SESSION.
For example:
captcha_image.php:
session_start();
$captcha = new CaptchaCode();
$code = $captcha->generateCode(6);
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,$code);
$_SESSION["captchacode"] = $code;

And check correctness after submit of the form:
session_start();
...
if($_SESSION["captchacode"]!=$_POST["security_check"]){
    echo "Wrong captcha!";
}else{
    // captcha is correct, process the form
}

A: If you cannot use cookies and session, you cannot get information from captcha_image.php which returns only image. You must generate information in else request, for example:
<img id="captcha_img" src="captcha_images.php?encoded_code=<?php echo $code ?>" onclick="refresh_captcha();"/>
<input type="hidden" id="captcha_hidden" name="security_check" value="<?php echo $code ?>">

Here generate_captcha.php returns encoded captcha, captcha_images.php doesnt generate code, only decode code from hims parameter encoded_code and this code is also inserted into hidden.


text:
Q: Rails Multiple forms in one view rendering errors issue I have built a dashboard of sorts with multiple forms from different models in the same view. My goal is to have all of the error messages from each form render on the dashboard. The dashboard is part of the PagesController and the forms belong to other controllers.
All of the forms currently work great. However, when errors occur they render in other views not the dashboard. When I attempt to "render" the errors on the dashboard page I get errors that the other form's models are missing.
Example of "render" that renders outside of the dashboard view.
class NotesController < ApplicationController
    def create
        @note = Note.new(params[:note])
        if @note.save
            flash[:notice] = "Note Created!"
            redirect_to dashboard_path
        else
            flash[:alert] = "Note failed"
            render :action => "new"
        end
    end
 end

The example I would like to work, which renders the errors inside the dashboard view.
class NotesController < ApplicationController
    def create
        @note = Note.new(params[:note])
        if @note.save
            flash[:notice] = "Note Created!"
            redirect_to dashboard_path
        else
            flash[:alert] = "Note failed"
            render 'pages/home'
        end
    end
 end

To reiterate, I am trying to make it so all errors will show up on the dashboard page with out breaking the site. Let me know if you would like more information.

A: You can accomplished this by just setting errors to an instance variable that all the forms use:
class NotesController < ApplicationController
    def create
        @note = Note.new(params[:note])
        if @note.save
            flash[:notice] = "Note Created!"
            redirect_to dashboard_path
        else
            @errors = @note.errors
            load_home
            render 'pages/home'
        end
    end

    private

    def load_home
      @instances = Model.all
      @instance_1 = Model.find(1)
    end
 end

All your controllers would set @errors = @model.errors then in your view you just have something like this instead of relying on f.error_messages or whatever you have in your form:
(in haml)
- unless @errors.nil?
  #errorExplanation
    %h2 Please correct these errors
    %ul
      - for e in @errors
        %li= e[1]


text:
Q: Problem with encoding while parsing XML in Python I am trying to parse an XML document using python and I am having a problem with the written accents, UTF-8 encoding should be enough. I have seen many questions about it but they didnt solve my problem her is my code:
def procesarXMLToHTML(archivoXML):

    try:
        f = open("generatedHTML.html", "w")

        #Escribimos la cabecera del HTML y sus metadatos
        writeHead(f)

        f.write('\n')
        f.write('\t
 Presentacion de mi arbol genealogico hasta mis bisabuelos.
\n')

        try:
            with open(archivoXML, 'r', 1, 'utf-8') as xml_file:
                arbol = ET.parse(xml_file) #Parsea el fichero XML
        except IOError:
            print ('No se encuentra el archivo ', archivoXML)
            exit()

        except ET.ParseError:
            print("Error procesando en el archivo XML = ", archivoXML)
            exit()

        raiz = arbol.getroot()

        print("\nElemento raiz = ", raiz.tag)

        if raiz.text != None:
            print("Contenido = ", raiz.text.strip('\n')) #strip() elimina los '\n' del string
        else:
            print("Contenido = ", raiz.text)

        print("Atributos = ", raiz.attrib)

        # Recorrido de los elementos del árbol
        for hijo in raiz.findall('.//'): # Expresión Path
            if(hijo.tag == 'persona'):
                f.write('\t\t
 Persona: ' + hijo.attrib['nombre'] + ' ' + hijo.attrib['apellido'] + '
\n')

            print("\nElemento = " , hijo.tag)
            if hijo.text != None:
                print("Contenido = ", hijo.text.strip('\n')) #strip() elimina los '\n' del string
            else:
                print("Contenido = ", hijo.text)
            print("Atributos = ", hijo.attrib)

        f.write('\n')
        f.write('\n')

    finally:
        f.close()

Ignore the prints and many ather things, I think the problem comes in that line:
with open(archivoXML, 'r', 1, 'utf-8') as xml_file:
                arbol = ET.parse(xml_file) #Parsea el fichero XML

HTML file looks like that and written accents are not shown right:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="keywords" content = "Arbol genealogico, Familia"/>
    <meta name="author" content = "Diego Glez. Su�rez"/>
    <title> Arbol Genealogico </title>

 Presentacion de mi arbol genealogico hasta mis bisabuelos.

 Persona: Diego Gonz�lez Su�rez

 Persona: Mar�a �ngeles Su�rez Fern�ndez

 Persona: �ngeles Fern�ndez Prado

 Persona: Adela Prado Prado

 Persona: Belarmino Fern�ndez

 Persona: Jos� Ram�n Su�rez Mu�iz

 Persona: Mercedes Mu�iz Casero

 Persona: Felix Su�rez

 Persona: Juan Manuel Gonz�lez Garc�a

 Persona: Mar�a Teresa Garc�a Garc�a

 Persona: Oliva Garc�a Garc�a

 Persona: Jos� Garc�a Men�ndez

 Persona: Jos� Manuel Gonz�lez Fern�ndez

 Persona: Visitaci�n Fern�ndez Fern�ndez

 Persona: Manuel Gonz�lez

A: Thats solved:
When I create the output file it was necesary to specify the encoding.
f = open('generatedHTML.html', 'w', 1, 'UTF-8')


text:
Q: Htaccess - difference between: .* and .+ Can you tell me what is defference between .* and +* in htaccess? For example I have this rule:
RewriteRule ^profil/([0-9]+)/.*/(.*)$ index.php?url=profile/show/$1/$2 [L]

And if I have the same with .+ instead .+ it still works. Thanks a lot for your answers.

A: This is basic regular expression stuff, and nothing specific to Apache configuration or mod_rewrite.
* means "Zero or more"
+ means "One or more"

A: The .+ matches any char that occures 1 to n times
The .* matches any char that occures 0 to n times
This is not apache specific. You may want to look for regular expressions (regex) for further information:
http://www.regular-expressions.info/reference.html
http://msdn.microsoft.com/en-us/library/ae5bf541%28v=vs.90%29.aspx
Best regards


text:
Q: Is the busybox cpio THAT different from GNU cpio? I'm trying to do an incremental backup using cpio but it seems that the busybox version doesn't work the same as the normal one? This is what I've got so far:
find data/Backup -mtime -2 | cpio -cm media/USB_FLASH_2
I origianlly used:
find . -mtime -2 | cpio -cm /media/USB_FLASH_2
However, I've seen people say busybox doesn't like definitive paths while using cpio. Unsure about that though.
It returns an error that basically says I'm using cpio wrong. I can't find anyone using the busybox cpio to do things like this, does that mean i can't do it? I've looked at using rsync as well but again, it doesn't do what i would expect.
For reference I'm using PuTTY to connect through SSH to a ReadyNAS 102.
After using find . -mtime -2 | cpio -o | { cd /media/USB_FLASH_2 && cpio -imd; }
i get the output:
BusyBox v1.20.2 (Debian 1:1.20.0-7) multi-call binary.

Usage: cpio [-dmvu] [-F FILE] [-H newc] [-tio] [EXTR_FILE]...

Extract or list files from a cpio archive, or
create an archive using file list on stdin

Main operation mode:
        -t      List
        -i      Extract EXTR_FILEs (or all)
        -o      Create (requires -H newc)
        -d      Make leading directories
        -m      Preserve mtime
        -v      Verbose
        -u      Overwrite
        -F FILE Input (-t,-i,-p) or output (-o) file
        -H newc Archive format

A: The options that the BusyBox commands have depends a lot on the options that BusyBox is compiled with. BusyBox aims to be highly configurable so that very small cut down versions can be compiled for systems where resources are very limited. Larger, more full featured versions can be built where this isn't an issue.
In your case cpio needs the -p or --pass-through (long form) option enabled. Normally cpio behaves more like an archive utility like tar, however it also has an extra function which allows it to copy files. To enable this in BusyBox, it needs to be built with FEATURE_CPIO_P defined (also LONG_OPTS for long form options to be enabled for any program).
From your last question, I strongly recommend that you use rsync for what you are doing. You are probably better off asking another question detailing exactly what you are doing with rsync and why it doesn't do what you expect. rsync is an extremely versatile tool and can no doubt be configured to do what you want.
That said, you could try the following with cpio, this will create an archive and then extract it again (somewhat less efficient, but still the same result):
find . -mtime -2 | cpio -o | { cd /media/USB_FLASH_2 && cpio -imd; }

Unfortunately the -o option can also be disabled in BusyBox (FEATURE_CPIO_O build option), so this may not work either.
Update
Based on this line of output, you need to add an extra option when creating an archive:
    -o      Create (requires -H newc)

This changes the command to:
find . -mtime -2 | cpio -oH newc | { cd /media/USB_FLASH_2 && cpio -imd; }

This time I have tested with the cpio in the BusyBox for my own system and it works for me, however in some cases the mtimes for directories won't be preserved. rsync should be the best way to do this.


text:
Q: Receive emails to configured domain in mvc I have to create email receiver,sender to my systems. Senario is like this,
Login user will configure his email server settings to my system,I can be gmail,yahoo or any other domain.then user should be able to send & receive emails through the system.
it's like outlook or http://webmail.com/ but no need that advance.. just need simply send and receive email using configured mail server.
I search internet so much couldn't find any helpful article. :(
can anyone help me on this..?

A: Its not that simple..
Steps to follow to achieve your requirement
1. First you need figure it out for whichever email domains you can support like gmail,outlook,hotmail..
2. For each domain you need to create a webhook, based on user(example:if you have 2 gmail id configured then there will be 2 web-hook created for gmail)
3. If you create webhook it sends you an email to your api, when user got new email.
4. You need to store that in your db, and then you can show it in your application
Hope this helps:)


text:
Q: PayPal and form ordering HTML Is it possible to make a link in site A to site B.
But you Can't visit site B with an URL. Only go from A to B.
What I want to do is:
You pay on a HTML with a PayPal button, after paying PayPal redirect you to a form page where you fill in the form for ordering.
But to avoid fraud I don't want that people can visit the form page without paying.
I hope that somebody can help me!

A: You cant do that with HTML only, you'll need javascript.
Assuming that you know Javascript, you can use the jwt token to give the user access when a certain condition is true (in this case, when the user has paid)

A: You should use paypal braintree integration or any other payment gateway provide built in solution which prevents the case you are refering to, look at adyen integration.


text:
Q: Scrollable TableLayout & Column Headers I am trying to create a basic datasheet in my application using a TableLayout. The first row contains the titles of each column. Every row thereafter is data. I would like the data to be scrollable while keeping the first title row visible (i.e. the first row would not scroll with the rest).
I have tried something like the following (unsuccessfully):
<TableLayout>
  <TableRow>
    <!-- The headers -->
    <TextView android:text="Header #1"/>
    <TextView android:text="Header #2"/>
    <TextView android:text="Header #3"/>
  </TableRow>

  <ScrollView>
    <!--The rest of the data -->
    <TableRow>
    <TableRow>
    ...
  </ScrollView>
</TableLayout>

This causes the program to crash. Any other suggestions?

A: you dont need to have tablerow as direct descendant, it crashes because scrollview accepts one child only. put another tablelayout in scrollview and put rows in it.

A: It crashes because you can only have TableRows as direct descendants in a TableLayout.
What you probably want to use is a ListView and a 'header' above it.
Example (not complete):
<LinearLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
>
   <TextView
      android:id="@+id/header1"
      android:layout_weight="1"
   />
   <TextView
      android:id="@+id/header2"
      android:layout_weight="1"
   />
   <TextView
      android:id="@+id/header3"
      android:layout_weight="1"
   />
</LinearLayout>
<ListView
    android:layout_width="fill_parent"
...
/>

The key is the layout_weight="1" and the android:layout_width="fill_parent" that will give you 3 views of equal size. You'll then need to create an Adapter and in your custom layout provided by the Adapter do the same thing for the child views. You might have to fiddle slightly with the padding/margins for them to line up horizontally exactly.

A: Using in the RelativeLayout both ScrollView and TableLayout aligned to the top, and populating both TableLayouts with the same first Row can make a trick.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    <ScrollView
            android:id="@+id/tabscrvie"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            <TableLayout
                android:id="@+id/gridview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >

        </TableLayout>
    </ScrollView>
    <TableLayout
            android:id="@+id/headergridview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/tabscrvie"
            >
    </TableLayout>
</RelativeLayout>


text:
Q: LINQ equivalent in Rails I am new to Rails, and i am wondering is there any concept like LINQ in Rails?
I am trying to store values in an object and query the object without saving it in database,
as like in LINQ?
is it really possible in Rails?
Please suggest.
thanks.

A: You may find your answer in the ActiveRecord Guide.

A: As i understand you are looking for something like LINQ to Object approach.
I think you can try to look to DataMapper and this post.


text:
Q: When google calendar v3 API was officially release? Please some one tell me what is the release date of calendar v3 API

A: I'm not sure about the precise release date of v3, but the deprecation of v2 was Novermber 17th, 2014.  So you could consider November 17th to be the official v3 enforcement date.


text:
Q: How to convert stl output to dataframe but keep time series time step? I have time series data that where I have used the stl() command to extract seasonality from the data. Now, I want to use the trend data for some other analyses but am having trouble converting the stl output to a dataframe.
I have tried:
KK.DF <- as.data.frame(KK14stl$time.series)

But that leaves out out the date intervals of the data as this is monthly data for over 40 years in some cases.
I have also tried:
KK.DF.V2 <-as.data.frame(as.xts(KK14stl$time.series))

But makes a data frame with the monthly dates nested within the column number column and now sure how to extract that from a nameless column. It does not appear when I do
names(KK.DF.V2)

Any suggestions on how to obtain a data frame with dates and time series data?

A: They are calculated only when you observe the ts object by the print.ts method and are not stored in the object. You can plunder print.ts for the code that takes into account the various nuances and frequency types.
If you are just wanting a quick fix for monthly data you can use something like:
s <- stl(nottem,"per")
s.DF <- as.data.frame(s$time.series)
rownames(s.DF) <- paste(month.abb[cycle(s$time.series)], floor(time(s$time.series)))

head(s.DF)
          seasonal    trend remainder
Jan 1920 -9.347198 49.68067 0.2665254
Feb 1920 -9.855250 49.54552 1.1097288
Mar 1920 -6.853301 49.41037 1.8429318
Apr 1920 -2.763471 49.32862 0.1348488
May 1920  3.501357 49.24688 1.3517676
Jun 1920  8.983303 49.21027 0.3064259

A: The stl output is such:
            seasonal    trend     remainder
Jan 1975  0.045860672 7.606192 -1.2870523041
Feb 1975 -0.165838793 7.557013 -1.0261737394
Mar 1975  0.182449236 7.507833  0.8597173305

Using as.data.frame yields the following:
KK.DF <- as.data.frame(KK14stl$time.series)

       seasonal    trend     remainder
1    0.045860672 7.606192 -1.2870523041
2   -0.165838793 7.557013 -1.0261737394
3    0.182449236 7.507833  0.8597173305
4    0.023504974 7.457380  1.0691145599
5   -0.006006918 7.406927  1.1490794183
6   -0.046599828 7.366488  1.2301122554

names(KK.DF)
"seasonal"  "trend"     "remainder"

Using as.xts yields the following:
KK.DF.V2 <-as.data.frame(as.xts(KK14stl$time.series))

            seasonal    trend     remainder
Jan 1975  0.045860672 7.606192 -1.2870523041
Feb 1975 -0.165838793 7.557013 -1.0261737394
Mar 1975  0.182449236 7.507833  0.8597173305
Apr 1975  0.023504974 7.457380  1.0691145599
May 1975 -0.006006918 7.406927  1.1490794183
Jun 1975 -0.046599828 7.366488  1.2301122554

names(KK.DF.V2)
"seasonal"  "trend"     "remainder"

The KK.DF.V2 data frame has the time time steps but in an unnamed column that I cannot call.


text:
Q: How does Mathematica compute the determinant of a matrix? I have been trying to write efficient code for calculating the matrix determinant for some time now. I noticed last night that Mathematica is able to compute the determinant of a $200 \times 200$ random matrix I made in seconds. My code in python is nowhere even close to this. I looked around but couldn't find much information on how it works, can anyone shed some light on what is going on under the hood?
Specifically, I want the exact determinant value. I tried C++ originally for speed but long long quickly overflows for even order 10 matrices. Python's inbuilt BigInt type seemed preferable.


text:
Q: Refresh page periodically using jquery, ajax and django I am trying to create notifications for my django app where I have to display changes in database in a div in my template. I want ajax to hit my database periodically and if there are any changes then they should be displayed in that div.
I want my data to come from 3 different models and any change in either of them should be notified in my template's div.
How can I do that?
Template:

        {% for like in likes_notify %}
        {% if like.item.reward != None %}

                  {{ like.user.get_full_name }} liked your post : {{ like.item.reward }}

           {% else %}

{{ like.item.comment.pk }}
                 {{ like.user.get_full_name }} liked your comment "{{ like.item.comment }}".

        {% endif %}
    {% endfor %}

    {% for comment in comments_notify %}
        {% if comment.item.reward != None %}

                  {{ comment.user.get_full_name }} commented on your post : {{ comment.item.reward }} with "{{ comment }}".

        {% else %}

{{ comment }}
                  {{ comment.user.get_full_name }} commented on your post "{{ comment }}".

        {% endif %}
    {% endfor %}

    {% for reward in rewards_notify %}

             {{reward.role_history.organisation_role.user.get_full_name }} got a reward :  {{ reward }}

    {% endfor %}

JS:
  function worker(){
    var url =  '/employee/'+get_emp_code()+'/home/dashboard/';
//    $(".notification").load(url + ' .notification',data, function () { setTimeout(worker, 5000);  });
    $.ajax({
        type:'get',
    url: url,
    success: function(data) {
//      $('.notification').load(url + " .notification", data);
//      $('.notification').load(url + " .notification").html(data);
      $('.notification').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 3000);
    }
  });
}
$(document).ready(function(){
setTimeout(worker, 5000);
    });

I have tried writing this js but this loads my entire page twice and not the div. I have actually extended a base template into this template so it loads the entire base template's data also in my div.
View:
def get_context(request,*args,**kwargs):
    context = {}
    likes = Like.objects.exclude(user = request.user).order_by('-date_edited')[:2]
    comments = Comment.objects.filter(user = request.user).order_by('-last_updated')[:2]
    rewards = Reward.objects.filter(role_history__organisation_role__organisation=request.user.organisation_user.organisation, approved=True).order_by('-last_updated')[:2]
    #notification = chain(likes,comments,rewards)

    context.update({'likes_notify':likes,'comments_notify':comments,
                    'rewards_notify':rewards})

This is the portion in my view for which i want to make my notifications for.

A: Finally found the answer to my question. I just modified my js with this code:
JS:
success: function(data) {
var dtr = $('.notification',data);
$('.notification').html(dtr);
}


text:
Q: Windows phone not recognized I upgraded my Dell Venue Pro on someone else's computer and since then I'm unable to get it to be recognized by my own computer.
Its a T-mobile version operator-unlocked developer-unlocked device and I'm on Windows 7.
Can someone please suggest what to do( except hard resetting the device ).
It has mango and Dell's post-mango firmware update.
Edit: If it helps to know, I upgraded to Mango on my own computer using the leaked Mango build. I upgraded Dell firmware on someone else's computer.
After using ghostbuster to remove useless driver it now says that my device is not recognized
as it has malfunctioned. I installed a new copy of Windows 8 developer preview and it says the same. Does this mean that my device actually has something wrong?
Thanks.


text:
Q: ruby adding to hash with array value I tried the following ruby code, which I thought would return a hash of word lengths to the words with those lengths. Instead it is empty.
map = Hash.new(Array.new)
strings = ["abc","def","four","five"]
strings.each do |word|
  map[word.length] << word
end

However, if I modify it to
map = Hash.new
strings = ["abc","def","four","five"]
strings.each do |word|
  map[word.length] ||= []
  map[word.length] << word
end

It does work.
Doesn't the first version just create a hash whose default values are an empty array? In this case, I don't understand why the 2 blocks give different values.

A: The problem is that you aren't actually assigning anything to the hash keys, you're just using the << operator to modify the existing contents of a default value. Since you don't assign anything to the hash key, it is not added. In fact, you'll notice the default value is the one modified:
h = Hash.new []
p h[0]           # []
h[0] << "Hello"
p h              # {}
p h[0]           # ["Hello"]
p h[1]           # ["Hello"]

This is because the same Array object is maintained as the default value. You can fix it by using the + operator, though it may be less efficient:
map = Hash.new []
strings = ["abc", "def", "four", "five"]

strings.each do |word|
    map[word.length] += [word]
end

And now it works as expected.

A: I think what the first version really means is that the default value is only one array. The second example explicitly creates a new array if one doesn't exist yet.
This looks like a good read to further clarify.

A: All being said, check Enumerable#group_by:
["abc", "def", "four", "five"].group_by(&:length)
#=> {3=>["abc", "def"], 4=>["four", "five"]}


text:
Q: Huggingface Load_dataset() function throws "ValueError: Couldn't cast" My goal is to train a classifier able to do sentiment analysis in Slovak language using loaded SlovakBert model and HuggingFace library. Code is executed on Google Colaboratory.
My test dataset is read from this csv file:
https://raw.githubusercontent.com/kinit-sk/slovakbert-auxiliary/main/sentiment_reviews/kinit_golden_games.csv
and train dataset:
https://raw.githubusercontent.com/kinit-sk/slovakbert-auxiliary/main/sentiment_reviews/kinit_golden_accomodation.csv
Data has two columns: column of Slovak sentences and 2nd column of labels which indicate sentiment of the sentence. Labels have values -1, 0 or 1.
Load_dataset() function throws this error:

ValueError: Couldn't cast
Vrtuľník je veľmi zraniteľný pri dobre mierenej streľbe zo zeme. Brániť sa, unikať, alebo vedieť zneškodniť nepriateľa je vecou sekúnd, ak nie stotín, kedy ide život. : string
-1: int64
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 954
to
{'Priestorovo a vybavenim OK.': Value(dtype='string', id=None), '1': Value(dtype='int64', id=None)}
because column names don't match

Code:
!pip install transformers==4.10.0 -qqq
!pip install datasets -qqq

from re import M
import numpy as np
from datasets import load_metric, load_dataset, Dataset
from transformers import TrainingArguments, Trainer, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding
import pandas as pd
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer

#links to dataset
test = 'https://raw.githubusercontent.com/kinit-sk/slovakbert-auxiliary/main/sentiment_reviews/kinit_golden_games.csv'
train = 'https://raw.githubusercontent.com/kinit-sk/slovakbert-auxiliary/main/sentiment_reviews/kinit_golden_accomodation.csv'

model_name = 'gerulata/slovakbert'

#Load data
dataset = load_dataset('csv', data_files={'train': train, 'test': test})

What is done wrong while loading the dataset?

A: The reason is since delimiter is used in first column multiple times the code fails to automatically determine number of columns ( some time segment a sentence into multiple columns as it cannot automatically determine , is a delimiter or a part of sentence.
But, the solution is simple: (just add column names)
dataset = load_dataset('csv', data_files={'train': train,'test':test},column_names=['sentence','label'])

output:
DatasetDict({
    train: Dataset({
        features: ['sentence', 'label'],
        num_rows: 89
    })
    test: Dataset({
        features: ['sentence', 'label'],
        num_rows: 91
    })
})


text:
Q: Material ui selectFiled multi select default value was splitting into multiple values I have implemented material -ui multiple selections, i am getting an issue with multiple selection values which means i have a default selection whose value is "hai" and when use selected another item from the dropdown whose value was "hello" and values i am getting by splitting the default value and selected value as array like ['h','a','i','hello'], its suppose to be array of two elements as ['hai','hello']. Not sure what wrong. Please find the below code snippet
 import React, {Component} from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const names = [
  'hai',
  'hello',
  'how are you',
  ];

export default class SelectFieldMultiSelect extends Component {

  handleChange = (event, index, values) {
    console.log(values);
  }

  menuItems(values) {
    return names.map((name) => (
      <MenuItem
        key={name}
        checked={values && values.indexOf(name) > -1}
        value={name}
        primaryText={name}
      />
    ));
  }

  render() {
    return (
      <SelectField
        multiple={true}
        hintText="Select a name"
        value="hai"
        onChange={this.handleChange}
        options={this.menuItems}
      >
      </SelectField>
    );
  }
}

A: You've hard coded the value property on the <Selectfield> component to be "hai". Therefore, when "hai" goes through the menuItems function, the menuItems function call map and iterates through h, then a, then i. Remove the hardcoded value property and replace with some value on the component's state.


text:
Q: Is this evidence my random forest model is over fit? I am investigating win probabilities in cricket and calculating the chances of winning a game depending at what stage the game is at. I created a logistic regression model and a random forest model. When I tested the models on a random game I got the following plot

They both follow the same broad trend but the random forest is a lot more variable. I am just trying to understand the causes of this and what I can do to improve it?

A: Without knowing the details of your model, it's very hard to give specific comments. However, in general a random forest can in principle have relationships of variables and outcomes, and interactions between predictors of arbitrary complexity. In contrast, a logistic regression with only main effects and continuous predictors used in a linear fashion (potentially after some transformation) will tend to be a less complex model that might be able (for better or worse) to react more strongly/in a more nuanced fashion to changes in predictors.
Additionally, you did not say whether your example is from the data you trained the model on or not. If it is, then a random forest is typically easier to overfit on the actual data than a logistic regression, but can also (when trained appropriately with well chosen hyperparameters) be somewhat better at predicting new data following the same distribution as the original data. If this is new data, that is a more meaningful evaluation. If you look at enough data that the models never saw, then you will find out whether the RF is overfit or not by seeing its performance on that new data. In the absence of new data, an evaluation using cross-validation may be the best thing you can manage.

A: As it's been pointed out already, to see whether a model suffers from overfitting one needs to choose a cross-validation scheme and compare training and test errors. For Random Forests you have two options.

*

*Keep a subset of your data (usually 20%) aside, and train your model on the remaining set. Afterwards, you test the performance on your training and test data and compare these two numbers. This is applicable to any ML-model.

*Alternatively, in Random Forests one can use Out Of the Bag (OOB) error estimation. As you might well know, Bootstraping is implemented in each tree in Random Forests, i.e. whenever a tree is built, a random subset of the training data is left aside (i.e. not considered in training). This is called an OOB subset. Using the OOB of each tree one can obtain the OOB error estimation. In modern ML API's like Sklearn, obtaining the OOB error estimation is rather straightforward. Assuming the numbers of trees is big enough, this can be shown to be equivalent to Leave-One-Out cross validation. (See An Introduction to Statistical Learning by Gareth James et. al.).


text:
Q: Run test case failed in fabric project , version release1.2 In the directory of ./core/chaincode/exectransaction_test.go
Run the TestExecuteDeployTransaction function of line 795 , got error :
2019-01-17 09:37:18.925 CST [ledgermgmt] initialize -> INFO 003 Initializing ledger mgmt
2019-01-17 09:37:18.925 CST [kvledger] NewProvider -> INFO 004 Initializing ledger provider
2019-01-17 09:37:20.113 CST [kvledger] NewProvider -> INFO 005 ledger provider Initialized
2019-01-17 09:37:20.114 CST [ledgermgmt] initialize -> INFO 006 ledger mgmt initialized
2019-01-17 09:37:20.118 CST [sccapi] registerSysCC -> INFO 007 system chaincode cscc(github.com/hyperledger/fabric/core/scc/cscc) registered
2019-01-17 09:37:20.118 CST [sccapi] registerSysCC -> INFO 008 system chaincode lscc(github.com/hyperledger/fabric/core/scc/lscc) registered
2019-01-17 09:37:20.118 CST [sccapi] registerSysCC -> INFO 009 system chaincode (qscc,github.com/hyperledger/fabric/core/scc/qscc,true) disabled
2019-01-17 09:37:20.443 CST [ledgermgmt] CreateLedger -> INFO 00a Creating ledger [testchainid] with genesis block
2019-01-17 09:37:20.493 CST [fsblkstorage] newBlockfileMgr -> INFO 00b Getting block information from block storage
2019-01-17 09:37:20.731 CST [kvledger] CommitWithPvtData -> INFO 00c Channel [testchainid]: Committed block [0] with 1 transaction(s)
2019-01-17 09:37:20.731 CST [pvtdatastorage] func1 -> INFO 00d Purger started: Purging expired private data till block number [0]
2019-01-17 09:37:20.732 CST [pvtdatastorage] func1 -> INFO 00e Purger finished
2019-01-17 09:37:20.884 CST [ledgermgmt] CreateLedger -> INFO 00f Created ledger [testchainid] with genesis block
2019-01-17 09:37:20.886 CST [cscc] Init -> INFO 010 Init CSCC
2019-01-17 09:37:20.887 CST [sccapi] deploySysCC -> INFO 011 system chaincode cscc/testchainid(github.com/hyperledger/fabric/core/scc/cscc) deployed
2019-01-17 09:37:20.887 CST [sccapi] deploySysCC -> INFO 012 system chaincode lscc/testchainid(github.com/hyperledger/fabric/core/scc/lscc) deployed
2019-01-17 09:37:20.887 CST [sccapi] deploySysCC -> INFO 013 system chaincode (qscc,github.com/hyperledger/fabric/core/scc/qscc) disabled
getting deployment spec for chaincode spec: type:GOLANG chaincode_id:<path:"github.com/hyperledger/fabric/examples/chaincode/go/example01" name:"example01" version:"0" > input:<args:"init" args:"a" args:"100" args:"b" args:"200" >
2019-01-17 09:37:22.129 CST [msp] DeserializeIdentity -> INFO 014 Obtaining identity
2019-01-17 09:37:22.777 CST [dockercontroller] func2 -> INFO 015 Container example01-0 has closed its IO channel
2019-01-17 09:37:22.940 CST [dockercontroller] Start -> ERRO 016 start-could not start container: API error (400): OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"chaincode\": executable file not found in $PATH": unknown
2019-01-17 09:37:22.983 CST [chaincode] Launch -> ERRO 017 start failed: API error (400): OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"chaincode\": executable file not found in $PATH": unknown
error starting container
error starting container


text:
Q: How to pass an array of conditions in mongokit find query How can i pass array of condtions in mongokit find query.
Untill now , i am implementing queries like :
data = db.entry.find({'title':{'$regex':'test'},'status':{'$regex':'active'}}).limit(3);

Condtions are bound to increase. Is there any way i can pass an array of conditions?

A: conditions = {'title':{'$regex':'test'},'status':{'$regex':'active'} ..... other conditions }
data = db.entry.find(conditions).limit(3);


text:
Q: ASP.NET MVC4 and Web API Authentication + Authorization (Windows 8 and Web) I created an ASP.NET MVC 4 Internet Web Application using Simple Membership db for storing users, roles and profiles.
In my app I created a Web API controller that will respond to the http:// 127.0.0.1/api/users and this call will return a list of all users stored in the db as JSON.
The UsersController is decorated with [Authorize] attribute therefore any call to the http:// 127.0.0.1/api/users have to be authenticated.
On the main page I have a button that once pressed a jQuery ajax get request is performed and will show the list of users returned by the Web API (json).
If I am logged in and I press the button, everything works fine ... the list of users is retrieved and shown.
If I am not logged in, the message show is 401 - Unauthorized (custom message in jquery call statusCode) so it works as it should because of the [Authorize] attribute.
My question: How can I authenticate when a Web API makes a request to it, to get the list of users and show them from a Windows 8 app or Windows Phone 8 or Windows Forms for example? In other words, from a client other than the web browser?

A: That depends on how you're coding your app, but basically, you'll use http protocol for this. Take a look at ASP.NET MVC - HTTP Authentication Prompt and http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/

A: You should make another api, that checks the authentication from the Windows 8 app or Windows.
If its pass successfully from the authentication, then only you have to show user list to the client.


text:
Q: Error: self signed certificate in certificate chain in node js application I work for a company that has strict IT policy. I work behind a proxy and i mostly use Proxifier or sometimes set proxy in Windows setting.
I am developing API with Node.js and at first just to test I created a simple route that makes a call to 'https://jsonplaceholder.typicode.com/posts'. Whenever I test my route in Postman, I get error "Error: self signed certificate in certificate chain" in command prompt where node js is running.
But when I test 'https://jsonplaceholder.typicode.com/posts' directly in Postman, it works.
here is the simple code I wrote to test:
exports.testing = async(req, res, next) => {
    try {
        const data = await axios.get("https://jsonplaceholder.typicode.com/posts")
        console.log({"Data": data.data})
    }catch(err){
        console.error({"ERROR": err});
    }
}

What I have tried:
npm config set strict-ssl false --global (didn't help, i assume this is for downloading npm packages)
npm config set cafile /path/to/your/cert.pem --global (didn't help)
set NODE_TLS_REJECT_UNAUTHORIZED=0 (didn't help)
set NODE_EXTRA_CA_CERTS=/path/to/your/cert.pem (didn't help)
P.S.
When I use mobile data, it works perfectly

A: httpsAgent: new https.Agent({
    rejectUnauthorized: false
})

Not a perfect solution, but ok for development env


text:
Q: Iterating through entity framework models from another related project I have just started working with .Net and I have created an Entity Framework Model and an associated context for the password reset functionality of a website and I have created this in a class library called MYSITE.Reset.Data with 3 classes (email,mapping,link).
I have now created a windows form application MYSITE.Reset but am having trouble in iterating through my models from the program.cs file. I am not quite sure of the structure of the syntax and I have unsuccessfully tried the following:
foreach(MYSITE.Reset.Data.Maps mp)

A: Try this:
var maps = from m in context.Maps
                select m;

foreach(var map in maps)
{
    // do stuff
}


text:
Q: Return a collection of type class for a method returning a collection of interface I have a interface, ISensor that has a method that returns a list of an interface type ISensorMeasurement. I then implement ISensor and want to know if there is a way to return a collection that implements ISensorMeasurement.
For example, the SensorModel.GetMeasurementsInRange<TemperatureMeasurement> Method returns a List<TemperatureMeasurement>. TemperatureMeasurement Implements ISensorMeasurement, but the compiler doesn't like me returning this type.
I have trimmed down the interface and class to a minimum for the sake of simplicity.
public interface ISensor
{
    int Id { get; set; }

    List<ISensorMeasurement> GetRangeOfMeasurements(DateTime startDate, DateTime endDate);
}

public class TemperatureSensor : ISensor
{
    public int Id { get ;; }
    private SensorModel SensorModel { get; set; } = new SensorModel();

    public List<ISensorMeasurement> GetRangeOfMeasurements(DateTime startDate, DateTime endDate)
    {
        return SensorModel.GetMeasurementsInRange<TemperatureMeasurement>(Id, startDate, endDate);
    }
}


text:
Q: I want to add the class just in the clicked span when I tried to use jQuery it changes every span with the same class but I don't want to add an id for each span
$(".bay-btn").click(function (e) {
        e.preventDefault();
        $(".bay-btn").addClass('bay-btn-clicked');
    });

I want to add a class to the clicked span without the unclicked yet

Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius esse consequatur magnam exercitationem quisquam.

            10$
            Bay

Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius esse consequatur magnam exercitationem quisquam.

            10$
            Bay

A: It seems that you misspelled the class name
".pay-btn" and ".bay-btn" in jQuery, so the code would be:
$(".pay-btn").click(function (e) {
        e.preventDefault();
        $(".pay-btn").addClass('pay-btn-clicked');
    });

And dont forget to update the class names in HTML file as well:
bay-btn -> pay-btn


text:
Q: RegEx для ввода имени и фамили, а также двойной фамили через - Нужна проверка введенной в форму имени и фамилии, а также двойной фамилии, например Irina Naro-fominskaja

A: Валидация имён и фамилий — это плохая идея. Вы ничего этим не добьётесь, кроме раздражения пользователей, когда им понадобится ввести что-то, что не проходит проверку вашей "универсальной регуляркой".
Обратимся к классике:

Итак, ради всеобщего блага, я составил список предположений, которые ваша система, вероятно, может делать об именах людей. Все эти предположения ошибочны. Попробуйте хотя бы уменьшить список, когда будете проектировать систему в следующий раз.

*

*У каждого человека есть одно каноническое полное имя.

*У каждого человека есть одно полное имя, которое он использует.

*В данный момент времени у каждого человека есть одно каноническое полное имя.

*В данный момент времени у каждого человека есть одно полное имя, которое он использует.

*У каждого человека есть в точности N имён, независимо от значения N.

*Имена вмещаются в определённое количество символов.

*Имена не меняются.

*Имена меняются, но только в определённых ограниченных случаях.

*Имена записаны в ASCII.

*Имена записаны в какой-нибудь одной кодировке.

*Все имена соответствуют символам Unicode.

*Имена чувствительны к смене регистра.

*Имена не чувствительны к смене регистра.

*Иногда в именах встречаются префиксы или суффиксы, но вы можете безопасно их игнорировать.

*Имена не содержат цифр.

*Имена не могут быть записаны ЦЕЛИКОМ ПРОПИСНЫМИ буквами.

*Имена не могут быть записаны целиком строчными буквами.

*В именах есть порядок. Выбор одной их схем упорядочивания записи автоматически приведёт к постоянному порядку среди всех систем, если все они используют ту же схему упорядочивания.

*Имя и фамилия обязательно отличаются.

*У людей есть фамилия или что-то подобное, общее для родственников.

*Имя человека уникально.

*Имя человека почти уникально.

*Ладно, ладно, но имена достаточно редки, так что нет миллиона человек с тем же именем и фамилией.

*Моя система никогда не будет иметь дело с именами из Китая.

*Или Японии.

*Или Кореи.

*Или Ирландии, Великобритании, США, Испании, Мексики, Бразилии, Перу, Швеции, Ботсваны, ЮАР, Тринидада, Гаити, Франции, Клингонской Империи — во всех перечисленных используются «странные» схемы для имён.

*Клингонская Империя была шуткой, правда?

*К чёрту культурный релятивизм! Люди в моём обществе, по крайней мере, имеют одинаковое представление об общепризнанном стандарте для имён.

*Есть алгоритм, который преобразует имена в одну и другую сторону без потерь. (Да, да, ты можешь сделать это, если алгоритм на выходе возвращает то же, что и на входе, возьми себе медаль).

*Я могу уверенно предположить, что этот словарь нецензурных слов не содержит фамилий.

*Имена людям даются при рождении.

*OK, может не при рождении, но довольно скоро после него.

*Ладно, ладно, в течение года или около того.

*Пять лет?

*Ты шутишь, верно?

*Две различные системы, в которых указано имя одного и того же человека, будут использовать для него одно и то же имя.

*Два различных оператора ввода данных, если им дать имя человека, обязательно впишут один и тот же набор символов, если система хорошо спроектирована.

*Люди, чьи имена ломают мою систему, — странные чужаки. У них должны быть нормальные, приемлемые имена, вроде (последовательность иероглифов).

*У людей есть имена.

  Список ни в коем случае не исчерпывающий. Если вам нужны примеры реальных имён, которые опровергают любой из этих пунктов, я с удовольствием назову их. Можете добавлять в комментариях другие пункты для этого списка заблуждений, и отправляйте людям ссылку на этот список в следующий раз, когда им придёт в голову гениальная идея сделать базу данных с колонками first_name и last_name.

Соус: http://habrahabr.ru/post/146901/


text:
Q: Ampscript Disappearing from Image Block (but stays in HTML) When building an image ref URL in Ampscript, I'm finding that it's getting mangled when saving...vs the same HTML in an HTML block (where things will save correctly).  Has anyone else run into this?  Is this a known issue?
Saving in HTML block -

Image Block (looks fine until I save) -

A: The WYSIWYG is changing AMPScript code in certain spots/ between certain characters. This is a known issue that Salesforce isn´t addressing tho. I had a ticket open for months when the Content Builder was introduced.
Using HTML Block is the save way to go here.


text:
Q: What is the current classification of linear motors used for positioning and scanning applications? I am doing some research on positioning and scanning systems but I am encountering some problems trying to categorize linear motors. I can't understand what type of linear motors based on induction are available. I tried to categorize into the following table where each cell corresponds to the possibility to choose between one of the element.
TYPE            SUB-TYPE       BEARINGS
induction       stepper motor  air bearings
                servo motor    guide bearings

piezoelectric   stepper motor
                squiggle motor

For instance, I can have an induction stepper motor with air bearing, or an induction servo motor with air bearings and so on with the other combinations.
I don't understand if the induction linear motor can be subdivided in stepper and servo motor as I did. And this hold true also for thrust-tube motors, that however, I think are not used in positioning and scanning applications. Is there a more extensive and precise categorization of the linear motors available for positioning and scanning applications?

A: Motors can probably be classified in different ways depending on the reason for classifying them. It appears that you may be attempting to classify motors starting with their fundamental mode of operation.
You seem to be using the term "induction" where it would be more appropriate to use "electromagnetic." An electromagnetic motor converts electric current and magnetic fields to mechanical force.
A piezoelectric motor is a type of electrostatic motor. An electrostatic motor uses an electric field to create a force
Electromagnetic motors can use either alternating current of direct current. Alternating current motors use rotating magnetic fields. Direct current motors have stationary magnetic fields and use a commutator or another form of sliding contact to allow the rotor's magnetic field to remain aligned with the stator field.
Induction motors are a type of AC motor that has a rotating magnetic field induced in the rotor by the stator field. The stator and rotor field rotate together in synchronism with an angle between them but the rotor speed is not synchronous with the magnetic fields. Induction motors are also called asynchronous motors. Sub-categories of induction motors include squirrel-cage motors and wound-rotor motors.
Reluctance motors are a type of AC motor that has only the rotating magnetic field produced by the stator. The rotor does not have its own magnetic field. The rotor turns synchronously with the stator field under the force of the magnetic field to maintain the path of lowest reluctance.
Synchronous motors have magnetic fields that are produced in the rotor by permanent magnets, permanent-magnet synchronous motors or by DC current in the rotor wound-field synchronous motors. The attraction of that magnetic field to the rotating stator field keeps the rotor turning synchronously with the stator field.
Brushless DC motors are similar to synchronous motors. They have rotating magnetic fields that are produced by electronic control schemes either built into the motor or in an external control unit.
Stepper motors are motors that rotate in incremental steps rather than in a steady motion. They are not exactly part of the above classification system. Stepper action can be implemented in reluctance and synchronous types of motors. Induction motors are not good candidates for use as stepper motors.
Servo motors are also not part of the above classification system. They are used for precise position control. They generally use motion and position feedback in implementing a control scheme. Most of the above motor types can be used as servo motors.
Many of the above types of motors can be constructed as Linear Motors.
Selection of the motor type for use as servo motors, linear motors, position control, scanning etc. Depends on the order of magnitude of power involved. Motors have been constructed in power levels from microwatts to megawatts.
Bearings, motor enclosure types, mounting provisions, cooling provisions and other construction details are not covered by the above classification system. Those are design details that are applicable to most types of motors.

A: This is a good start and each combination has a useful application in industry for both Linear AND rotary motion control with position feedback and current or energy control with time to control motion of mass. the air bearings only affect friction due to gravity.
Examples:

*

*power meter with rotating disc is on a magnetic spindle rotary vertical air bearing to prevent drag with low induced torque from metal eddy currents and torque.

*Maglev train uses sequential magnets to step and accelerate linear motion by V/F control and friction free air bearing.

*HDD Servo writer  uses a air bearing rotary induction motor to eliminate wobble due to bearing friction on large HDD's . Now small HDD's are ferro-fluidic spindles to bind the grease from contaminating the HDA, head disk Assy, and the embedded inter-sector gaps are written between tracks to give a relative dibits for position error signal, PES, while Rotary Head motor uses rare earth magnet and moving rectangular voice coil on similar clean bearings to last > 100 million seeks

*linear stepper is actually rotary motor with gear/belt conversion to linear motion with gear ratio as diameter but std packed grease bearings.

*original fastest 14 and 5.25" HDD's used much bigger linear fixed magnet moving coils and relied on dedicated surface for Servo PES.

*induction motors accelerate with current DC to AC or AC and use current feedback then integrate for v or differentiate Position to control velocity then use Position sensors for feedback such as differential Quadrature encoders with a home sensor .

*Piezo types use charge energy to move a certain distance by combining Voltage and C to load C such as those Inkjet printers or microMEM pumps or perhaps nano pump technology. I.e. dump then short accelerates and stops with known load.
Many more examples but gotta get back to fixing gearbox in hedge trimmer.
Steppers are incremental and not absolute, so some reference sensor is needed for home and/or GPS .  E.g. Floppy drives used an optical home sensor for Track 0


text:
Q: Что делать с промисом и оберткой? Непонятно, как избавиться от замечаний к коду:
на строке 101 Promise.all заворачиваете в промис - это не нужно делать, Promise.all уже возвращает промис;
на строке 151 тоже лишняя обертка из промиса, и еще там же .then древовидно выстроены, а надо плоско.
Кто может помочь?
Код в песочнице - https://repl.it/repls/BothCraftyUsernames

A: 101 строка: Промисы уже получены  от getCurrencyRate(), по этому сразу после PromiseAll можно строить цепочку .then:
let convertCurrency = (amount, fromCode, toCode) =>
    Promise.all([getCurrencyRate(fromCode), getCurrencyRate(toCode)])
        .then(result => Math.round(result[1] * amount / result[0]))
        .catch(err => console.error(`\n[Error: ${err}]`));

151 строка: Тоже самое getTeg() возвращает промис, с этого места можно строить цепочку .then():
let getTagItemsCount = (title) => getTag(title)
            .then(tag => getTagItems(tag.id))
            .then(products => products.length)
            .catch(err => console.error(err));

Хорошее чтиво по теме:https://habr.com/company/nixsolutions/blog/323066/


text:
Q: readr::read_file not being able to read the file I'm using the read::readfile function to make some changes to the XML file by R itself. For some reason, the above function doesn't work on my computer (it returns Error: Invalid multibyte sequence), while it works on a colleague's computer. Could it be an encoding problem or has anyone had the same problem?
> library(magrittr)
> "20220218_Pedidos_xml_2020.xml" %>%
+   readr::read_file(locale = readr::locale(encoding = "UTF-16LE")) %>%
+   stringr::str_replace_all("<Pedido ", "\n\t<Pedido ") %>%
+   stringr::str_replace("</Pedidos>", "\n</Pedidos>") %>%
+   stringr::str_remove_all("&#x[0-9A-F]{2};") %>% # Remover caracteres inválidos
+   stringr::str_c('<?xml version="1.0" encoding="UTF-8"?>\n', .) %>%
+   readr::write_file("20220218_Pedidos_xml_2020.xml")
Error: Invalid multibyte sequence

File: 20220218_Pedidos_xml_2020.xml available in https://dadosabertos-download.cgu.gov.br/FalaBR/Arquivos_FalaBR_Filtrado/Arquivos_xml_2020.zip
PS: the file name changes according to the day it is downloaded, but the content remains the same.


text:
Q: react-router link router.createHref is not a function error I am creating a header which shows sign in / sign up link if the user is not already signed in or a sign out link if a user is already signed in
Here is my header component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';

class Header extends Component {
  renderLinks() {
    if(this.props.authenticated) {
      return (

          <Link to="/signout" className="nav-link">Sign Out</Link>

      );
    }
    else {
      return (
        [

            <Link to="/signin" className="nav-link">Sign In</Link>

,

            <Link to="/signup" className="nav-link">Sign Up</Link>

        ]
      );
    }
  }

  render () {
    return (

        <Link to="/" className="navbar-brand">Redux Auth</Link>

            {this.renderLinks()}

    );
  }
}

const mapStateToProps = (state) => {
  return { authenticated: state.auth.authenticated };
}

export default connect(mapStateToProps)(Header);

I am getting the following error in the browser
Warning: Failed Context Types: Required context router.push was not specified in Link. Check the render method of Header.
Uncaught TypeError: router.createHref is not a function
I am using react router version 2.0.1
Why am I facing this issue? What does this error mean?

A: react-router does not provide Link, you need to use react-router-dom for this.
Replace
import { Link } from 'react-router';

with
import { Link } from 'react-router-dom';

That'll work for you.


text:
Q: How to find error line in eval of multi-line variable definition Suppose I have the following Makefile with an intentional error in line 4:

define TEMPLATE
all:

this line contains some errors
endef

$(eval $(call TEMPLATE))

When I run make I get this:

$ make-3.81
Makefile:7: *** missing separator.  Stop.
$

Make is telling me that there is an error in line 7, which is technically correct because the TEMPLATE variable is expanded on line 7.  But this is not tremendously useful.  In order to quickly debug this sort of thing it would be much more handy if make could somehow point me directly to the error on line 4.  Is there any way to do this?
In case it makes any difference, this is GNU make-3.81.

A: Electric Make, a high-performance GNU-make-compatible implementation of make, reports errors the way you want:
$ cat Makefile
define BOGUS
foo: bar
    abcd

endef

$(eval $(BOGUS))
$ gmake
Makefile:7: *** missing separator.  Stop.
$ emake
Makefile:7:eval:2: *** missing separator.  Stop.

It's a commercial product, but you can download a free version from Electric Cloud.
Disclaimer: I am the architect of Electric Make


text:
Q: Memoir 3.7e: treating bibliography like a section, not a chapter Update: as pointed out in moewe's comment below, the 'culprit' is not memoir but biblatex. The change was introduced in v. 3.0 of biblatex, and as a result the bibliography is printed as a chapter unless \printbibliography[heading=subbibliography] is specified.

Using the memoir class (v. 3.7c), with the article option, the bibliography is formatted like a section.
For example:
\documentclass[article]{memoir}

\usepackage[style=authoryear-comp,backend=biber]{biblatex}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@article{Bli74,
  author = {Blinder, Alan S.},
  year = {1974},
  title = {The economics of brushing teeth},
  journaltitle = {Journal of Political Economy},
  volume = {82},
  number = {4},
  pages = {887--891},
}
\end{filecontents}

\bibliography{\jobname}

\counterwithout{section}{chapter}
\makechapterstyle{mydefault}{
\addtocounter{secnumdepth}{2}
\setsecheadstyle{\raggedright\scshape}
\setsubsecheadstyle{\raggedright\itshape}
\setsubsubsecheadstyle{\raggedright\itshape}
}

\chapterstyle{mydefault}

\begin{document}

\section{First section}

This paper really is very good: \cite{Bli74}.

\printbibliography

\end{document}

yields the following:

Using memoir v 3.7e, however, yields the following instead:

From looking at the .aux file, the following line suggests that the references section is now being treated as a chapter:
\@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {chapter}{References}{1}}

The corresponding bit in the .aux file using 3.7c has this instead:
\@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{References}{1}}

Is this behavior intended? I couldn't find anything in the newest version of the manual to suggest that it is.
I should add that the switch to the newer version of memoir happened when I upgraded to texlive 2015. I haven't tried to see what happens if I use the older version of memoir using texlive 2015, so I've been switching  to texlive 2014 in order to use the older version of memoir. But my guess is that the problem is not with the newer texlive distribution, but with the newer version of memoir.
In any case, I would like to be able to force memoir to treat the bibliography as a section, at least when using the article option. I tried explicitly redefining \bibsection, as suggested on p. 300 of the manual for v 3.7e, but that doesn't seem to make a difference::
\documentclass[article]{memoir}

\usepackage[style=authoryear-comp,backend=biber]{biblatex}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@article{Bli74,
  author = {Blinder, Alan S.},
  year = {1974},
  title = {The economics of brushing teeth},
  journaltitle = {Journal of Political Economy},
  volume = {82},
  number = {4},
  pages = {887--891},
}
\end{filecontents}

\bibliography{\jobname}

\counterwithout{section}{chapter}
\makechapterstyle{mydefault}{
\addtocounter{secnumdepth}{2}
\setsecheadstyle{\raggedright\scshape}
\setsubsecheadstyle{\raggedright\itshape}
\setsubsubsecheadstyle{\raggedright\itshape}
}

\chapterstyle{mydefault}

\begin{document}

\renewcommand{\bibsection}{%
   \section{\bibname}
   \prebibhook}

\section{First section}

This paper is very good: \cite{Bli74}.

\printbibliography

\end{document}

A: The biblatex package disables or redefines many features of memoir, making \renewcommand{\bibsection}{...} useless.
The biblatex manual states in section 3.12.2: Usage with the memoir class:

When using Biblatex with the memoir class, most class facilities for
  adapting the bibliography have no effect. Use the corresponding
  facilities of this package instead (§§ 3.6.2, 3.6.8, 3.6.9). Instead
  of redefining memoir's \bibsection, use the heading option of
  \printbibliography and \defbibheading (§§ 3.6.2 and 3.6.8). Instead of
  \prebibhook and \postbibhook, use the prenote and postnote options of
  \printbibliography and \defbibnote (§§ 3.6.2 and
  3.6.9). All default headings are adapted at load-time such that they blend well with the default layout of this class.

Redefine \defbibheading etc. to change to \section or \section* instead!
\documentclass[article]{memoir}

\usepackage[style=authoryear-comp,backend=biber]{biblatex}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@article{Bli74,
  author = {Blinder, Alan S.},
  year = {1974},
  title = {The economics of brushing teeth},
  journaltitle = {Journal of Political Economy},
  volume = {82},
  number = {4},
  pages = {887--891},
}
\end{filecontents}

\bibliography{\jobname}

\counterwithout{section}{chapter}
\makechapterstyle{mydefault}{
\addtocounter{secnumdepth}{2}
\setsecheadstyle{\raggedright\scshape}
\setsubsecheadstyle{\raggedright\itshape}
\setsubsubsecheadstyle{\raggedright\itshape}
}

\chapterstyle{mydefault}

\defbibheading{bibliography}[\bibname]{%
\section*{#1}%
\markboth{#1}{#1}}

\AtBeginDocument{%
  \renewcommand{\bibname}{References}
}

\begin{document}
\tableofcontents

\section{First section}

This paper is very good: \cite{Bli74}.

\printbibliography

\end{document}


text:
Q: What about tag-bags or a tag-category in order to simplify favorite tags As a Stack Overflow user, I'm interested in a few subjects, for example WMI, Active-Directory, and PowerShell. But to follow these subjects on SO, I have to register to multiple tags. If I use Active-Directory as an example, when I want to answer questions around this subject, it concerns Active-Directory, ADSI, ADAM, LDS tags.
So I would find it useful to find along with favorite tags, favorite tag-bags. (Or tags-set?)
The behaviour of a tag-bag should be to show the recent questions about the tags that are present in the bag.
I understand that my tag-bags on one subject are not the same as another user's. It would be nice if each user can define up 3 or 4 bags.


text:
Q: Trying to map my physics experiment onto an optimisation problem I'm running an experiment consists in setting voltages on a set of 4 gates in an electronic device, and performing a measurement that will return a probability of success. My goal is to set the gates to a specific value that maximises the probability of success.
I can make a good initial estimate of the gate voltages I need, but I would then like to optimise over a bounded range of gate space, to maximise the probability of success.
The main issue that even though the 4D parameter space is not so large (average step in parameters is 1/10 of the bounded range), the measurement is very slow (~5 seconds), so going through the entire space by brute force will take too long.
So I am looking for an optimisation algorithm to do a more efficient walk through my gate voltage space and find the maximum success probability from my experiment.

A: Crude possible answer. Your "$1/10$ of the range" for step size for each parameter means a brute force search would require $10^4$ experiments. You could consider a local search algorithm that evaluates at the $3^4 = 81$ points that divide each parameter interval in quarters. Then look near the single point that offers the maximum so far. That might reduce the number of measurements from ten thousand to some hundreds.
Whether a strategy like this is likely to find a value at (or near) the maximum depends on how regular/convex the objective function is. If it actually has a single maximum at the top of a single hill you will be close. If it oscillates a lot as a function of parameter values you are out of luck.
Edit. Actually, brute force would call for $11^4$ evaluations since you want to check at the boundary points too. That makes this a fence post problem. But the essence of my suggestion is unchanged.


text:
Q: Is it possible to show all inherited attributes and associations in Enterprise Architect? I have a complex data model and want to quickly show all inherited attributes and associations of a feature.
One possibility according to the EA-documentation would be to use Elements->Feature visibility (Ctrl+tab+y), but the option is unfortunately greyed out in the model. I guess this is a specific model setting or a limitation of the used EA-Version (Prof. Edition).
What (other) kind of possibilities do I have in Enterprise Architect Professional Edition to show inherited attributs and associations of a feature?
edit:
Below is a a screenshot of the greyed-out Feature Visibility, as requested in the comments. The model is the german street/traffic OKSTRA-model 2.017(EAP-file downloadable under www.okstra.de).

A: OP had his diagram locked, preventing appearance modifications such as showing attributes


text:
Q: cassandra timeuuid columns showing buffer type data insted of string I am retrieving data from Cassandra timeuuid column using NodeJS Cassandra driver. Now the data retrieved as buffer type instead of string type. I need the data as string type

A: While it's still difficult to understand what you're expecting to see, this will return your PostedDate in a more-readable format:
SELECT DateOf(PostedDate) FROM facehq.timeline;

Also, as your data grows in size, unbound queries will become problematic and slow.  So make sure you qualify queries like this with a WHERE clause whenever possible.

i need result like "posteddate":"f6ca25d0-ffa4-11e4-830a-b395dbb548cd".

It sounds to me like your issue is in your node.js code.  How are you executing your query?  The Node.js driver documentation on the GitHub project page has an example that may help:
client.stream('SELECT time, val FROM temperature WHERE station_id=', ['abc'])
  .on('readable', function () {
    //readable is emitted as soon a row is received and parsed
    var row;
    while (row = this.read()) {
      console.log('time %s and value %s', row.time, row.val);
    }
  })
  .on('end', function () {
    //stream ended, there aren't any more rows
  })
  .on('error', function (err) {
    //Something went wrong: err is a response error from Cassandra
  });

The DataStax documentation also has a specific example for working with timeUUIDs:
client.execute('SELECT id, timeid FROM sensor', function (err, result) {
    assert.ifError(err);
    console.log(result.rows[0].timeid instanceof TimeUuid); // true
    console.log(result.rows[0].timeid instanceof Uuid); // true, it inherits from Uuid
    console.log(result.rows[0].timeid.toString());      // <- xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    console.log(result.rows[0].timeid.getDate());       // <- Date stored in the identifier
});


text:
Q: Way to load/access all stores in Sencha project I need to retrieve a security token and use it in all my stores to load them.
I could put autoLoad to false, make an event that gets each of my stores and calls the load event:
Ext.getStore('one').load();
Ext.getStore('two').load();

But I'd rather not have add a line every time I add a store. Is there a way to access or loop through all stores and load them? Or have an observer and make the stores wait until a value is available in LocalStorage before they load?
Note: I know about the stores property in app.js but they contain the full classnames, not the store id's.

A: Just load the first store that retrieves the token (store it in a cookie or a global variable) then in the load event of that token loading store, do a Ext.StoreManager.each(function(store) { //code... }) loop.
Obviously, in that loop, skip over the token loading store.


text:
Q: mysql command does not work in rails without the -u root I cannot seem to inspect my database with mysql and I'm a bit new and I don't know how to do this even after reading related posts.
I'm on Rails 4.1.5 and the adapter gem is gem 'mysql2', '~> 0.3.0'.
mysql version:
mysql --version
mysql  Ver 14.14 Distrib 5.7.23,

and I want to stay on this because it's too difficult to change the legacy app right now.
This is my database.yml:
development:
  adapter: mysql2
  database: some_development
  username: root
  password:
  host: localhost
  port: 3306

This works:
mysql -u root -p some_development
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 47
Server version: 5.7.23 Homebrew

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show tables;
+--------------------------------+
| Tables_in_some_development |
+--------------------------------+
| activities                     |
| addresses                      |
| associated_products            |

But I'm doing this from root all the time. The password is the password I use when I log onto my mac. Is this fine?
If I try it like this:
mysql some_development
ERROR 1045 (28000): Access denied for user 'jwan'@'localhost' (using password: NO)

it fails.

A: mysql -uroot -p
grant all privileges on some_development.* to 'jwan'@'localhost' identified by 'some_password'
mysql -ujwan -psome_password some_development
Be sure some_password matches database.yml
Of course some_password isn't literal it's the password you create


text:
Q: Running 2 java codes I have 2 java programs (ciphers), one is Playfair and second is Transposition.
Now i want to run Playfair code, then right after that compile Transposition using the result i got from Playfair code. How should i make this?(
Playfair code
import java.awt.Point;
import java.util.Scanner;

public class PlayfairCipher {
    private static char[][] charTable;
    private static Point[] positions;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
        String txt = prompt("Enter the message: ", sc, 1);
        String jti = prompt("Replace J with I? y/n: ", sc, 1);

        boolean changeJtoI = jti.equalsIgnoreCase("y");

        createTable(key, changeJtoI);

        String enc = encode(prepareText(txt, changeJtoI));

        System.out.printf("%nEncoded message: %n%s%n", enc);
        System.out.printf("%nDecoded message: %n%s%n", decode(enc));
    }

    private static String prompt(String promptText, Scanner sc, int minLen) {
        String s;
        do {
            System.out.print(promptText);
            s = sc.nextLine().trim();
        } while (s.length() < minLen);
        return s;
    }

    private static String prepareText(String s, boolean changeJtoI) {
        s = s.toUpperCase().replaceAll("[^A-Z]", "");
        return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
    }

    private static void createTable(String key, boolean changeJtoI) {
        charTable = new char[5][5];
        positions = new Point[26];

        String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);

        int len = s.length();
        for (int i = 0, k = 0; i < len; i++) {
            char c = s.charAt(i);
            if (positions[c - 'A'] == null) {
                charTable[k / 5][k % 5] = c;
                positions[c - 'A'] = new Point(k % 5, k / 5);
                k++;
            }
        }
    }

    private static String encode(String s) {
        StringBuilder sb = new StringBuilder(s);

        for (int i = 0; i < sb.length(); i += 2) {

            if (i == sb.length() - 1)
                sb.append(sb.length() % 2 == 1 ? 'X' : "");

            else if (sb.charAt(i) == sb.charAt(i + 1))
                sb.insert(i + 1, 'X');
        }
        return codec(sb, 1);
    }

    private static String decode(String s) {
        return codec(new StringBuilder(s), 4);
    }

    private static String codec(StringBuilder text, int direction) {
        int len = text.length();
        for (int i = 0; i < len; i += 2) {
            char a = text.charAt(i);
            char b = text.charAt(i + 1);

            int row1 = positions[a - 'A'].y;
            int row2 = positions[b - 'A'].y;
            int col1 = positions[a - 'A'].x;
            int col2 = positions[b - 'A'].x;

            if (row1 == row2) {
                col1 = (col1 + direction) % 5;
                col2 = (col2 + direction) % 5;

            } else if (col1 == col2) {
                row1 = (row1 + direction) % 5;
                row2 = (row2 + direction) % 5;

            } else {
                int tmp = col1;
                col1 = col2;
                col2 = tmp;
            }

            text.setCharAt(i, charTable[row1][col1]);
            text.setCharAt(i + 1, charTable[row2][col2]);
        }
        return text.toString();
    }
}

and Transposition
import java.util.*;
import java.util.Scanner;  // needed for Scanner

public class transpositionCipher
{

public static void main(String args[])
{
String key;
String message;
String encryptedMessage;
// Letters in the x-axis
int x=0;
// Letters in the y-axis
int y=0;

// Prompt the user
System.out.print( "Type your Key : " );

// Read a line of text from the user.

Scanner scan = new Scanner(System.in);
key = scan.nextLine();

// Display the input back to the user.
System.out.println( "Your Key is " + key );

//Prompt the user
System.out.print( "Type your Message : " );

//Read a line of text from the user.
message = scan.nextLine();

//Display the input back to the user.
System.out.println( "Your Message is " + message );

int msgchar = message.length();
int keycahr = key.length();

if (!((msgchar % keycahr) == 0)){

do{
message = message + "x";
msgchar = message.length();
}while(!((msgchar % keycahr) == 0));

}

encryptedMessage = "";

// To set the temp as [x][y]
char temp[][]=new char [key.length()][message.length()];
char msg[] = message.toCharArray();
// To populate the array
x=0;
y=0;
// To convert the message into an array of char
for (int i=0; i< msg.length;i++)
{
temp[x][y]=msg[i];
if (x==(key.length()-1))
{
x=0;
y=y+1;
} // Close if
else
{
x++;
}
} // Close for loop

// To sort the key
char t[]=new char [key.length()];
t=key.toCharArray();
Arrays.sort(t);

for (int j=0;j<y;j++)
{
for (int i=0;i<key.length();i++)
{
System.out.print(temp[i][j]);
}
System.out.println();
}

System.out.println();

// To print out row by row (i.e. y)
for (int j=0;j<y;j++){
// To compare the the sorted Key with the key
// For char in the key
for (int i=0;i<key.length();i++){
int pos=0;
// To get the position of key.charAt(i) from sorted key
for (pos=0;pos<t.length;pos++){
if (key.charAt(i)==t[pos]){
// To break the for loop once the key is found
break;
}
}
System.out.print(temp[pos][j]);
encryptedMessage+=temp[pos][j];
}
System.out.println();
}

System.out.println(encryptedMessage);
System.exit(0);
}enter code here
}

A: Take the output of one operation (PlayfairCipher.encode), which is the cyphertext and input it to the second operation (your transpositionial code) as it's plaintext.
Scanner sc = new Scanner(System.in);

String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);

boolean changeJtoI = jti.equalsIgnoreCase("y");

PlayfairCipher.createTable(key, changeJtoI);

String enc = PlayfairCipher.encode(prepareText(txt, changeJtoI));

//Now instead of using 'message' for the second encryption, you use the output of the first operation 'enc'

int x=0;
int y=0;
int msgchar = enc.length();
int keycahr = key.length();

if (!((msgchar % keycahr) == 0)){

   do{
      enc = enc + "x";
      msgchar = enc.length();
   }while(!((msgchar % keycahr) == 0));
}

...


text:
Q: Mover archivo cargado al servidor con laravel necesito poder subir un documento al servidor a traves de laravel, si ejecuto mi formulario, este me guarda los datos en la base de datos y me guarda el documento localmente, pero en el servidor no hay caso que aparezca dicho documento, pongo mi codigo
    if ($request->hasFile('archivo')) {
       $file = $request->file('archivo');
       $name = $file->getClientOriginalName();
       $newName = "/personal/".$name;
       $path = public_path() .'\personal';
       $file->move($path,$name);
   }else{
       echo "Debes subir documento"
   }

Si imprimo mi varible $path me arroja lo siguiente
C:\Users\JUANJO\Desktop\Trabajos - Proyecto\public\personal
Y como digo, si apreto el botón guardar de mi formulario, este me guarda como debe ser en la base de datos y en mi carpeta local también guarda.  Pero al servidor no me sube, tampoco me arroja error.  Si me voy al servidor y veo que permiso tiene mi carpeta personal es 775, que estoy realizando mal, ayuda plis

A: A lo que entiendo estas tratando de subir un archivo a un servidor remoto.
si es que ese es tu problema sigue los siguientes pasos...

*

*Entra a la ruta config/filesystem.php de tu proyecto y agrega las siguientes
lienas de codigo.

'ftp' => [
        'driver'   => 'ftp',
        'host'     => '192.168.0.210',
        'username' => 'admin',
        'password' => '*****',
        'root' => 'Folder1/Folder2/2020',
    ],

*Después entras a tu controlador y agregas lo siguiente.

use Illuminate\Support\Facades\Storage;

$carpeta = "nombre-de-tu-carpeta";
$files = $request->file('archivo');
$nombre_archivo = $files->getClientOriginalName();

Storage::disk('ftp')->put($carpeta.'/'.$nombre_archivo.'/', \File::get($files));

Esto funciona para almacenar un archivo en una carpeta que este en algún servidor externo.
Espero y te sirva