text:
Q: How can i get elements to stack on top of each other for mobile users without changing the view for desktop users As you can see in the screenshot, there is an image and then the title, price, options, add to cart button, countdown timer and description to the right. I'm happy with this but when I view this through a mobile browser, it doesn't look too appealing. How can I change my CSS/HTML so each of the elements next to the image are stacked below the image when viewing on a mobile ?
Desktop View:
Desktop View
Mobile View:
Mobile View
HTML:

.photoarea {
 float: left;
 vertical-align: top;
 width: 50%;
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-sizing: border-box;
}
.detailsarea {
 float: left;
    width: 50%;
 vertical-align: top;
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-sizing: border-box;

  <meta itemprop="url" content="{{ shop.url }}{{ product.url }}">
  <meta itemprop="image" content="{{ product.featured_image.src | img_url: 'grande' }}">

          {% assign featured_image = product.selected_or_first_available_variant.featured_image | default: product.featured_image %}
          {% for image in product.images %}
            {% capture img_wrapper_id %}productPhotoWrapper-{{ section.id }}-{{ image.id }}{% endcapture %}
            {% capture img_id %}productPhotoImg-{{ section.id }}-{{ image.id }}{% endcapture %}

              {%- assign img_url = image | img_url: '1x1' | replace: '_1x1.', '_{width}x.' -%}

              <img id="{{ img_id }}"
                  {% if forloop.first == true %}
                  src="{{ featured_image | img_url: '300x300' }}"
                  {% endif %}
                  class="lazyload no-js lazypreload"
                  data-src="{{ img_url }}"
                  data-widths="[180, 360, 540, 720, 900, 1080, 1296, 1512, 1728, 2048]"
                  data-aspectratio="{{ image.aspect_ratio }}"
                  data-sizes="auto"
                  alt="{{ image.alt | escape }}"
                   {% if section.settings.product_image_zoom_enable %} data-zoom="{{ image | img_url: '1024x1024', scale: 2 }}"{% endif %}>

            {% if forloop.first == true %}

            {% endif %}
          {% endfor %}

        {% if product.images.size > 1 %}

            {% for image in product.images %}

            {% endfor %}

        {% endif %}

{{ product.title }}

    {% if section.settings.product_vendor_enable %}

{{ product.vendor }}

    {% endif %}

      {% assign variant = product.selected_or_first_available_variant %}

      <meta itemprop="priceCurrency" content="{{ shop.currency }}">
      <meta itemprop="price" content="{{ variant.price | divided_by: 100.00 }}">

            {% include 'price' with variant.price %}

        {% if product.compare_at_price_max > product.price and section.settings.product_show_saved_amount %}

            {% assign compare_price = variant.compare_at_price %}
            {% assign product_price = variant.price %}
            {% include 'price-sale' %}

        {% endif %}
        {% if section.settings.product_reviews_enable %}

        {% endif %}

      <link itemprop="availability" href="http://schema.org/{% if product.available %}InStock{% else %}OutOfStock{% endif %}">

      <form action="/cart/add" method="post" enctype="multipart/form-data" id="addToCartForm-{{ section.id }}">
        <select name="id" id="productSelect-{{ section.id }}" class="product-variants product-variants-{{ section.id }}">
          {% for variant in product.variants %}
            {% if variant.available %}

              <option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} data-sku="{{ variant.sku }}" value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money_with_currency }}</option>

            {% else %}
              <option disabled="disabled">
                {{ variant.title }} - {{ 'products.product.sold_out' | t }}
              </option>
            {% endif %}
          {% endfor %}
        </select>

        {% if section.settings.product_quantity_enable %}
          {{ 'products.product.quantity' | t }}
          <input type="number" id="quantity" name="quantity" value="1" min="1" class="quantity-selector">
        {% endif %}

        <button type="submit" name="add" id="addToCart-{{ section.id }}" class="btn">

          {{ 'products.product.add_to_cart' | t }}
        </button>

        {% if section.settings.product_quantity_message%}
          <span id="variantQuantity-{{ section.id }}" class="variant-quantity {% if variant.inventory_management and variant.inventory_quantity < 10 and variant.inventory_quantity > 0 %} is-visible{% endif %}">
           {% if variant.inventory_management and variant.inventory_quantity < 10 and variant.inventory_quantity > 0 %}
              {% assign qty = variant.inventory_quantity %}
              {{ 'products.product.only_left' | t: count: qty }}
            {% endif %}

        {% endif %}

        {% if section.settings.product_incoming_message %}
          <span id="variantIncoming-{{ section.id }}" class="variant-quantity {% if variant.inventory_management and variant.inventory_quantity <= 0 and variant.incoming %} is-visible{% endif %}">
            {% if variant.inventory_management and variant.inventory_quantity == 0 or variant.inventory_quantity < 0 and current_variant.incoming %}
              {% if variant.available %}
                {% assign date = variant.next_incoming_date | date: "month_day_year" %}
                {{ 'products.product.will_not_ship_until' | t: date: date  }}
              {% else %}
                {% assign date = variant.next_incoming_date | date: "month_day_year" %}
                {{ 'products.product.will_be_in_stock_after' | t: date: date }}
              {% endif %}
            {% endif %}

        {% endif %}

      </form>

      {{ product.description }}

A: You should use media queries to arrange your elements in a different way for a smaller screens. You do this be changing the css that is applied at different screen sizes.
You'll probably have to do some trial and error to work out how to show your items in the best way for the smaller screen. Here is an example to get you started:
/* Small screens */
@media all and (max-width: 700px) {
    .detailsarea, .photoarea  {float:none; display:block}
}

Here I've removed the float and added a display block so that detailsarea element will be displayed below the photoarea element on smaller screens.


text:
Q: How to search by an attribute of another attribute with Hibernate? I have PlaceDTO and CategoryDTO, which connect in PlaceCategoryDTO(many to many).
public class PlaceCategoryDTO implements Serializable{

private Long id;
private Long categoryID;
private Long placeID;
private CategoryDTO category;
private PlaceDTO place;
//getters and setters
}

I have PlaceCategoryDAO and i want to search by two attributes. One is the categoryID and the other is an attribute of PlaceDTO(region). For searching by categoryID and placeID i have this method in PlaceCategoryDAO:
public class PlaceCategoryDAO extends GenericHibernateDAO<PlaceCategoryDTO,Long>{
  public  List<PlaceCategoryDTO> findByParameters(Long placeID, Long categoryID)
    {
      List<Criterion> criteria = new ArrayList<Criterion>();
      if (placeID != null)
        {
          criteria.add(Restrictions.eq("placeID",placeID));
        }
      if (categoryID != null)
        {
          criteria.add(Restrictions.eq("categoryID",categoryID));
        }
      return findByCriteria(criteria);
    }
}

I am wondering if i can search by place.region instead of placeID.

A: Yes you can, see this. Just add another criterion and your restriction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: set and set delayed in dynamic programming The first one is running
   Module[{f},
     f[1] = f[2] = 1;
     f[n_] := f[n - 1] + f[n - 2];
     f[5]
     ]

But the second one never ends its loop.
Module[{f},
 f[1] = f[2] = 1;
 f[n_] = f[n - 1] + f[n - 2];
 f[5]]

Why does this loop never end?


text:
Q: Web Application + Silverlight project in TFS, .xap file keeps being checked in, can I avoid it? When I look at my ASP.NET application that hosts a Silverlight project, it has a Clientbin folder, inside of which there is a .xap file, the one being compiled from my Silverlight project.
This file keeps being checked into TFS. Is there a way for me to tell TFS to just plan ignore it?
The reason is that once the file is checked in, if I forget to check it back out, it appears Visual Studio will silently (there is a warning, but nothing that prevents me from starting the debugger) fail when building the Silverlight project, so when I debug, it starts the version in TFS, not the version I just built.
What I have to do is either check our, or just plain delete (which also checks out) the corresponding xap files, then build the Silverlight project. When I do that, I notice that Visual Studio puts the file(s) back into the Clientbin directory (if I deleted it, it first undos the delete, but keeps it checked out). Now I can debug the right version of the binary.
So, what am I doing wrong, how can I fix this?

A: There is a bug in TFS2008 which caused this error for Web Application Projects (as opposed to Web Site Projects, which should work fine), so at least it's not your fault.  This was fixed in VS2010/TFS2010.
This thread on the Silverlight forums contains this suggestion:

We had the same problem.
I deleted the clientbin folder with the xap in it, checked in.
On the _Web project, properties, silverlight app, Removed the sl project, save, check in.
Then I readded my silverlight project.
It seems to be working for everyone now and isn't getting readded to source control. I hope that helps out.

This other thread from the Silverlight forums contains this suggestion:

Hi, it seems that now in SL 3.0 the things have changed.
  Now we are using the following three steps in order to get the xap correctly published.
1) Remove any post/pre build script in the SL project.
2) In the host project (web):
  Make sure the ClientBin.xap file has these settings:
  Build Action: Content
  Copy to Output Directory: Do not copy
3) In post pre-build event, put the following script:
  attrib -r ....\Sources[WebProject_NAME]\ClientBin[XAPFileName].xap
For example:
  attrib -r ....\Sources\test.web\ClientBin\sl.xap
(this last step avoid the "unable to copy the xap file" error from TFS Build)


text:
Q: InvocationTargetException caused by ArrayIndexOutofBound exception i have a function where am using methodaccesor's invoke function,the problem is the application which am using is very vast,so there are times when this exception InvocationTargetException is thrown and the cause for this happens to  be ArrayIndexOutofBounds Exception. The problem which occurs is comparitively less 8% of the transactions result in this (am unable to replicate this scenario),am unable to figure out what/how  is causing this
can you guys please give me suggestions regarding this problem ,as to how to go about it?
am using reflector's PropertyUtils class here getindexedproperty is causing InvocationTargetException the thing am unable to replicate the issue what could be causing this as it happens very rarely

A: You are probably suffering from code that catches exceptions and does not log a proper stack trace.
Change all such instances in your code to do this instead:
try {
    // dangerous stuff here
} catch (SomeException e) {
    // Personally, I like to send a stack trace to stderr.
    // You may prefer to print this to your log, eg if you don't capture stderr,
    // or won't/can't for whatever reason.
    e.printStackTrace(System.err);
}

And you will never again be at a loss as to where in your code these exceptions bubbled up from.
As you visit each try-catch, ask yourself if you should really be robust to such failures; sometimes the best thing is to let the code fail fast and not catch the exception in the first place.  When the application fails due to some code/data that was in an incorrect state, you will find out quickly and get a roadmap (stack trace) to the root cause.


text:
Q: react-native-webrtc remote stream does not work on android 5.0.2 I am trying to make a video call app using react-native-webrtc. it is working well both local and remote stream on android 8.1
But remote stream is not working on android 5.0.2
import React, {useState, useEffect} from 'react';
import {StyleSheet, SafeAreaView, TouchableOpacity, Text, View} from 'react-native';
import styles from '.styles';
import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
  mediaDevices,
  registerGlobals
} from 'react-native-webrtc';

let globalStreamState = null, globalRemoteStreamState = null;

export default App = props => {

  const [stream, setStream] = useState({toURL:()=>null});
  const [streamRemote, setStreamRemote] = useState({toURL:()=>null});

  globalStreamState = setStream;
  globalRemoteStreamState = setStreamRemote;

  console.log('App rendered..');

  return (
    <View style={styles.container}>

        <View style={{flex: 1, flexDirection: 'row'}}>
            <TouchableOpacity style={styles.callButton} onPress={makeLogin}>
              <Text style={styles.callText}>LOGIN</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.callButton} onPress={callSomeone}>
              <Text style={styles.callText}>CALL</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.callButton} onPress={cancelCall}>
              <Text style={styles.callText}>Cancell Call</Text>
            </TouchableOpacity>
        </View>

        <RTCView style={{flex: 1, width: '100%', height: '100%'}} streamURL={stream.toURL()} />
        <RTCView style={{flex: 1, width: '100%', height: '100%'}} streamURL={streamRemote.toURL()} />

    </View>
  );

}

var name = "";
var connectedUser = "";

var conn = new WebSocket('ws://192.168.38.152:8000');

conn.onopen = function () {
   console.log("Connected to the signaling server");
}

conn.onmessage = function (msg) {

   var data = JSON.parse(msg.data);

   switch(data.type) {
      case "login":
         handleLogin(data.success);
         break;
      case "offer":
         handleOffer(data.offer, data.name);
         break;
      case "answer":
         handleAnswer(data.answer);
         break;
      case "candidate":
         handleCandidate(data.candidate);
         break;
      case "leave":
         handleLeave();
         break;
      default:
         break;
   }

}

conn.onerror = function (err) {
   console.log("Got error", err);
};

function send(message) {
   //attach the other peer username to our messages
   if (connectedUser) {
      message.name = connectedUser;
   }

   conn.send(JSON.stringify(message));
}

var yourConn;
var stream;

const makeLogin = ()=> {
  name = "muhammad";
    send({ type: "login", name: name });
}

async function handleLogin(success) {
   if (success === false) {
      alert("Ooops...try a different username");
   } else {
      let isFront = true;
      const sourceInfos = await mediaDevices.enumerateDevices();
      let videoSourceId;
      for (let i = 0; i < sourceInfos.length; i++) {
        const sourceInfo = sourceInfos[i];
        if(sourceInfo.kind == "videoinput" && sourceInfo.facing == (isFront ? "front" : "environment")) {
          videoSourceId = sourceInfo.deviceId;
        }
      }

      mediaDevices.getUserMedia({
        audio: true,
        video: {
          mandatory: { minWidth: 320, minHeight: 200, minFrameRate: 30 },
          facingMode: (isFront ? "user" : "environment"),
          optional: (videoSourceId ? [{sourceId: videoSourceId}] : [])
        }
      })

      .then(myStream => {

            stream = myStream;

            globalStreamState(stream);

            var configuration = {"iceServers": [{ "url": "stun:stun.l.google.com:19302" }]};

            yourConn = new RTCPeerConnection(configuration);

            yourConn.addStream(stream);

            yourConn.onaddstream = e =>  {
              globalRemoteStreamState(e.stream);
            };

            yourConn.onicecandidate = event => {
              if (event.candidate) {
                  send({
                    type: "candidate",
                    candidate: event.candidate
                  });
              }
            };

      })

      .catch(error => {
        console.log("Error in handleLogin: ", error);
      });

   }
}

const callSomeone = ()=> {
  var callToUsername = "wafa";

  if (callToUsername.length > 0) {

     connectedUser = callToUsername;

      yourConn.createOffer().then(desc => {
          yourConn.setLocalDescription(desc).then(() => {
            send({ type: "offer", offer:  yourConn.localDescription});
          });
      });
  }
}

function handleOffer(offer, name) {

   connectedUser = name;
   yourConn.setRemoteDescription(new RTCSessionDescription(offer));

   yourConn.createAnswer().then(answer => {
      yourConn.setLocalDescription(answer).then(()=> {
        send({ type: "answer", answer: answer});
      });
   });

}

function handleAnswer(answer) {
   yourConn.setRemoteDescription(new RTCSessionDescription(answer));
}

function handleCandidate(candidate) {
   yourConn.addIceCandidate(new RTCIceCandidate(candidate));
}

const cancelCall = ()=> {
  send({
    type: "leave"
  });

  handleLeave();
}

function handleLeave() {
   connectedUser = null;

   yourConn.close();
   yourConn.onicecandidate = null;
   yourConn.onaddstream = null;
};


text:
Q: word automation save as pdf When saving a document as pdf in MS Word 2010 we get other options like "optimize for". These options can not be set as parameters of Document.Saveas function in c#. Please tell how can i set these options before saving a pdf.
Document doc = word.Documents.Open(ref filename, ref oFalse, ref oTrue, ref oFalse, "?#nonsense@$", "?#nonsense@$", ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse, ref oFalse, WdDocumentDirection.wdLeftToRight, ref oTrue);
doc.Activate();
object outputFileName = wordFile.FullName.Replace(".docx", ".pdf");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse);

A: OptimizeFor parameter in Document.ExportAsFixedFormat will do your need


text:
Q: Extracting a value from a file that is organized into columns and rows I have a file with five columns formatted as such:
1 213 1 545 0.0988697879 0.9084867680

There are 300 rows like this. I would like to take values from column four and five of a row and perform mathematical operations, then save the result, and repeat that process with all 300 rows.
So far the closest thing to a solution I have found is building an array with the command
while IFS= read -a line; do   printf "Line number %d:\n" $i;   printf "%s\n" "${line[@]}";   let i++; done < "workfile.txt""

What are better ways to go about this?

A: Fields can be manipulated with awk, more info here. The following one-liner sums 4th and 5th fields and saves the result in the output file:
awk '{print $4 + $5}' input.file > output.file


text:
Q: How can I catch Sybase bcp errors reliably? We're using named pipes with Sybase bcp so that we can compress output on-the-fly.
The Sybase bcp utility does not return much information in its exit code.
Sybase documentation directs the user to inspect error messages written by the process.
This is a paraphrase of the error handling idiom we use, some error checking in the non-bcp parts of the script has been removed to shorten the example.
while :
do
    {
        rm -f $fifo
        mkfifo $fifo
        cat $fifo &
        CatPid=$!

        bcp $db.$owner.$table out $fifo -c $db_creds >$log 2>&1
        grep -qi deadlock $log || break

        # Must have been a deadlock, clean up.
        kill $CatPid
    } > $output
done

Basically, if the word 'deadlock' appears in bcp output messages, we try again.
Two questions

*

*Does this approach look reasonable?

*What other bcp errors than deadlock might we need to worry about?

I'm specifically interested in detecting transient bcp errors, where we can try again.
We use a compound statement so that we can insert headers and footers around the bcp data before the compression, but I've omitted that to simplify the example.

A: I had idea use named pipe for bcp out and compress data from Sybase ASE to file and then load into Sybase IQ using LOAD TABLE statement. Unfortunately there was a big performance lost. LOAD TABLE from named pipe was 10x slower than LOAD TABLE from file on HP-UX :-( I vote for implementing simple compress alghoritm directly into OC utils (bcp,isql).

A: So all you need is just reliable fail fast bcp. Bcp for some of Sybase versions has a command argument controlling max error-count.
1) if you set error count = 1, then it will fail more reliably.
2) The problem then boils down to trapping the exit code of bcp process, launched on background with &. I dont know what shell syntax should be used for this exactly, but there might be some common shell technique for this.

A: This is one is easy.
Does this approach look reasonable?
Not really.  First, the shell script is not very good, it does not need all that work but I will leave that alone, as that is not the question.
Second, bcp will not deadlock, even on an active database (unless you are doing something very strange in the database, or running multiple parallel bcp streams), it waits for shared locks to clear, so there is no need to check for that.
Third, bcp provides complete and full error messages.  Use the -e bcp_err_file invocation parameter.  Then grep ... bcp_err_file for errors or patterns ("^[Ee]rr" and "^Msg" are typical).  I trap separately for errors; exceptions; and other messages.
Fourth, I would never retry forever like that within a shell script.  Potential infinite loop, waste of resources.  Have it execute once, and produce "success" xor "failure" and the list of errors.  Any loop should be only for the list of tables to be exported.

*

*It is written as a proper unix utility/command. If you do not specify an error file, sure, then all error messages go to $stdout and they are mixed up with progress messages.  You can trap for errors in that stream, but that is legless; specify a separate error file.

*It is normal to capture $stdout to a bcp_log_file, but that is separate to the bcp_err_file

*Inspecting exit status on Unixis a different thing.  If bcp ran successfully (whether it produced error messages or not), it exits as "success"; you will get a non-zero exit status only if a unix program fails.

*it will tolerate any number of errors, unless you limit that by -m max_errors
What other bcp errors than deadlock might we need to worry about?
Any and all errors, they cannot be predicted (it is an online server with fixed resources), capture all of them, and then inspect the bcp_err_file.  You can automate the inspection via grep as detailed above.
I'm specifically interested in detecting transient bcp errors, where we can try again.
No problem at all.  Detailed above.  Transient errors are few and far between.
You should also worry about hard errors and resource errors, and not try again (because it will fail again).
Most of us worry about errors that result in missing rows, which means the bcp_data_file is incomplete or unusable.

A: Is that really going to do what you want? My understanding of the bcp commandline tool is that there is no transaction - ie. if you are loading M rows, but inserting row N fails for any reason (constraints etc.), the first N-1 rows have been inserted. So restarting the whole file isn't a great idea.
You can use the -m X option to allow bcp to carry on in the face of up to X errors, and then try to identify which rows failed to insert and retry them.
You could also look into Michael Peppler's Sybase::BCP Perl module, but our investigations suggest that it may have issues with ASE 15.


text:
Q: How can I make a relatively positioned parent that contains absolutely positioned children have 'flexible' height? <img> (child) is absolutely centered within .carousel (parent). However, with responsive behavior, I would like to have .carousel (parent) have a height relative to the screen size and/or relative to the tallest <img>. Again, <img> height will vary depending on screen width.
.carousel {
  background: #dfe2e4;
  background: url(../images/bg/port-bg.png) no-repeat top center;
  background-size: contain;
  margin: 4px;
  min-height: 221px;
  position: relative;
}

.carousel img {
  margin: auto;
  width: 100%;
  /* 'Absolute' centering. */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

I think we can get this to work with JS, but using JS for styles sort of makes me cringe a little bit.


text:
Q: Attaching the foldername to all the all files in that particular folder There are 100s of folders in a directory and inside each of the folder there is a (filename).ini file.
All I need to do is to attach the parent folder name to the .ini file so that it becomes (foldername)-(filename).txt file.
Is there a batch script which could do this? i am new to batch files. So, any help is greatly appreciated!

A: setlocal enabledelayedexpansion

for /R %%a in (*.ini) do (
  set relativepath=%%a
  set relativepath=!relativepath:%cd%\=!
  set newname=!relativepath:\=-!
  set newname=!newname:.ini=.txt!
  ren !relativepath! !newname!
)

endlocal

A: This works for any folder and any folder structure.
@echo off
setlocal enabledelayedexpansion
for /R %%a in (*.ini) do (
  set foldername=%%~pa
  set foldername=!foldername:\=_!
  echo ren "%%~fa" "(!foldername!)-%%~na.txt"
)

For all the ini files in the current directory: extract the path from the filename, using the ~p modifier; change all backslash occurrencies to underscores, using the := modifier; finally rename the original ini file.
After testing, remove the ECHO
See HELP FOR and HELP SET for more information.


text:
Q: How to convert a wav audio file format (sample width) into 8 bits format? I am using a Python gui that records the voice and I need to set the Width format of the wav file into 8 bits. When I run the recording has nothing but noise!
import tkinter as tk
import threading
import pyaudio
import wave
from tkinter import *
import tkinter.font as font
from tkinter.filedialog import asksaveasfilename

class App():
    chunk = 1024
    sample_format = pyaudio.paUInt8
    channels = 2
    fs =44100

frames = []

def __init__(self, master):
    self.isrecording = False
    myFont = font.Font(weight="bold")
    self.button1 = tk.Button(audio_window, text='Record', command=self.startrecording,
                             height=2, width=20, bg='#0052cc', fg='#ffffff')
    self.button2 = tk.Button(audio_window, text='stop', command=self.stoprecording,
                             height=2, width=20, bg='#0052cc', fg='#ffffff')
    self.button1['font'] = myFont
    self.button2['font'] = myFont
    self.button1.place(x=30, y=30)
    self.button2.place(x=280, y=30)

def startrecording(self):
    self.p = pyaudio.PyAudio()
    self.stream = self.p.open(format=self.sample_format, channels=self.channels,
        rate=self.fs, frames_per_buffer=self.chunk, input=True)
    self.isrecording = True

    print('Recording')
    t = threading.Thread(target=self.record)
    t.start()

def stoprecording(self):
    self.isrecording = False
    print('recording complete')

    self.filename = asksaveasfilename(initialdir="/", title="Save as",
        filetypes=(("audio file", "*.wav"), ("all files", "*.*")),
        defaultextension=".wav")

    wf = wave.open(self.filename, 'wb')
    wf.setnchannels(self.channels)
    wf.setsampwidth(self.p.get_sample_size(self.sample_format))
    wf.setframerate(self.fs)
    wf.writeframes(b''.join(self.frames))

def record(self):
    while self.isrecording:
        data = self.stream.read(self.chunk)
        self.frames.append(data)
        print("does it")

audio_window = tk.Tk()
audio_window.title('recorder')
app = App(audio_window)
audio_window.geometry('520x120')
audio_window.mainloop()

This is the recording GUI I used. I need the recording to be in 8 bits because I need to encrypt it later.

A: You can use soundfile.write() like this:
import librosa  # just to demo, not necessary, as you already have the data
import soundfile

# read some wave file, so that y is the date and sr the sample rate
y, sr = librosa.load('some.wav')

# write to a new wave file with sample rate sr and format 'unsigned 8bit'
soundfile.write('your.wav', y, sr, subtype='PCM_U8')

To get available subtypes for a certain format, use:
>>> soundfile.available_subtypes('WAV')
{'PCM_16': 'Signed 16 bit PCM', 'PCM_24': 'Signed 24 bit PCM', 'PCM_32': 'Signed 32 bit PCM', 'PCM_U8': 'Unsigned 8 bit PCM', 'FLOAT': '32 bit float', 'DOUBLE': '64 bit float', 'ULAW': 'U-Law', 'ALAW': 'A-Law', 'IMA_ADPCM': 'IMA ADPCM', 'MS_ADPCM': 'Microsoft ADPCM', 'GSM610': 'GSM 6.10', 'G721_32': '32kbs G721 ADPCM'}


text:
Q: NLP Классификация документов Есть набор документов - контракты, акты, служебки и т.д.
Необходимо в последующем проверять соответствие нового документа одному из классов (контракт? акт? и т.д.)
В каком направлении идти? Может быть есть алгоритм такого анализа? Какими библиотеками пользоваться? Пока набрел на Gensim.

A: Для начала стоит определиться с предобработкой документов. То есть, в каком виде требуется представить исходный документ. Это может быть вектор с частотами слов в документе (bag-of-words), а может быть сумма из векторов слов word2vec. В обоих случаях подойдёт библиотека gensim. Bag-of-words можно создать как обычный, так и с TF-IDF частотами для каждого слова. Также можно найти примеры использования своеобразного гибрида bag-of-words с word2vec подходом (вектор слова просто домножается на IDF слова)
Просле предобработки документов уже можно подумать о классификаторе. Он может быть как и простой (разнообразие таких можно найти в библиотеке sklearn), так и нейронный (keras, tensorflow, pytorch). Если рассматривать простой классификатор, то легче всего начать с решающего дерева, который рассматривает bag-of-words как набор правил и делает вывод по каждому документу.


text:
Q: How to send sms from vb.net I need to setup an application with the purpose of sending an sms . Already know the sms gateway type . But i really want to integrate with sim . i need to send via a sim ( which was connected to pc through COM port)

A: Here you can find free library that can help you with your task: http://www.codeproject.com/KB/cs/SMS.aspx?msg=3179142
Or you can opt some commercial library that do the same thing: http://www.logixmobile.com/products/mcorelib/index.asp, for instance.

A: Imports System.IO.Ports
Public Class Exampl1
Public Class Form1
    Dim WithEvents serialport As New IO.Ports.SerialPort
    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For i As Integer = 0 To My.Computer.Ports.SerialPortNames.Count - 1
            .Items.Add(My.Computer.Ports.SerialPortNames(i))
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If serialport.IsOpen Then
            serialport.Close()
        End If

        Try
            With serialport
                .PortName = ComboBox1.Text
                .BaudRate = 96000
                .Parity = Parity.None
                .DataBits = 8
                .StopBits = StopBits.One
                .Handshake = Handshake.RequestToSend
                .DtrEnable = True
                .RtsEnable = True
                .NewLine = vbCrLf
            End With
            serialport.Open()
        Catch ex As Exception

        End Try

        serialport.WriteLine("AT+CMGF=1" & vbCr)
        System.Threading.Thread.Sleep(200)
        serialport.WriteLine("AT+CMGS=" & Chr(34) & "destination" & Chr(34) & vbCr)
        System.Threading.Thread.Sleep(200)
        serialport.WriteLine("test message" & vbCrLf & Chr(26))
        System.Threading.Thread.Sleep(200)
    End Sub
End Class

End Class


text:
Q: javascript : create and save files to device this code is working fine when I open it in browser. but when I create application it's showing nothing..!!
please help. how do I create application that saving files
<html><body>
  <script src="text/javascript">
  // Function to download data to a file
  function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) {// IE10+
      window.navigator.msSaveOrOpenBlob(file, filename);
    }
    else { // Others
      var a = document.createElement("a"),
          url = URL.createObjectURL(file);
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      setTimeout(function() {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 0);
    }
  }
  </script>
</body></html>

A: You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
        var create = document.getElementById('create'),
        textbox = document.getElementById('textbox');
        create.addEventListener('click', function () {
        var link = document.createElement('a');
        link.setAttribute('download', 'info.txt');
        link.href = makeTextFile(textbox.value);
        document.body.appendChild(link);

          // wait for the link to be added to the document
          window.requestAnimationFrame(function () {
          var event = new MouseEvent('click');
          link.dispatchEvent(event);
           document.body.removeChild(link);
         });

          }, false);


text:
Q: Hangman Java Game Printing Both Wrong and Correct Guesses I'm doing my first programming language, Java, and I am having trouble getting correct guesses to print correctly. When a wrong letter is entered, it prints "wrong!" but when a correct letter is guessed, it prints both "Correct!" and "Wrong!"...any help is appreciated. Thanks. :)
The words are pulled from an array.
import java.util.Scanner;
import java.util.Random;
public static void main(String[] args) {
    System.out.println("Welcome to Hangman! Below you can find the rules of the game.");
    //Welcome message
    System.out.println();
    //Spacing
    System.out.println("How to play:");
    System.out.println();
    //Spacing
    System.out.println("Hangman is a word guessing game. Guess the word by suggesting letters within a certain number of guesses.");
    System.out.println("The word to guess is represented by a row of dashes, representing each letter of the word.");
    System.out.println("If you guess a letter correctly, it replaces a dash and you can continue to guess until the word is uncovered.");
    System.out.println("However, if you guess wrong you lose a try. You have a maximum of 5 tries. After guessing 10 words, you win! Good luck!");
    //Rules of game
    System.out.println();
    //Spacing
    Scanner in = new Scanner (System.in);
    //Scanner created
    String[] intro = {"after", "think", "could", "thank", "round", "clump", "plane", "beach", "towel", "tiger", "goat", "monkey", "house"};
    String[] beginner = {"around", "amount", "grown", "focus", "cedar", "flute", "unicorn", "fruit", "basket", "burger", "chips", "juice"};
    String[] intermediate = {"about", "bring", "clean", "mother", "locker", "hunter", "drink", "eight", "spray", "untie", "cents"};
    String name;
    int age;
    //Variables initialized
    System.out.println("Please enter your name:");
    //Prompt for name
    name = in.next();
    //Input for name
    System.out.println("Please enter your age:");
    //Prompt for age
    age = in.nextInt();
    //Input for age

    if (age >= 4 && age < 7){
    System.out.println("You have been placed in the Intro level!");
    Random rand = new Random();
    //Random created
    int randomWord = rand.nextInt(12)+0;
    //Stores the position of array
    String word2guess = intro[randomWord];
    //String is the value stored in the generated position of array
    char[] word2Char = word2guess.toCharArray();
    //Stores the word in a char array
    char[] wordLength = new char [word2Char.length];
    //Creates an array for word length
    for (int i = 0; i < word2Char.length; i++){
        wordLength[i] = '_';
    }
    //Replaces each letter of the word with an underscore
    for (int i = 0; i < word2Char.length; i++){
    System.out.print(wordLength[i] + " ");
    }
    //Prints the word in underscore format with a space between each letter
    int wrongGuesses = 0;
    int correctGuesses = 0;
    boolean letterFound = false;
    boolean nextWord = true;
    while (nextWord){
    while(correctGuesses != word2Char.length){
    System.out.println();
    //Spacing
    System.out.println("Please enter a letter:");
    char guess = in.next(".").charAt(0);
    //Input for only ONE letter
    for (int i = 0; i < word2Char.length; i++){
            if (guess == word2Char[i]){
               wordLength[i] = word2Char[i];
               letterFound = true;
               break;
            }else{
                letterFound = false;
            }
        }
           if(letterFound == false && wrongGuesses <= 4){
                wrongGuesses++;
                System.out.println("Wrong! You have "+ (5 - wrongGuesses)+" attempts remaining. Please try again.");
           }else{
               correctGuesses++;
               System.out.println("Correct!");
           }

    for (int i = 0; i < word2Char.length; i++){
        System.out.print(wordLength[i] + " ");
        }
    System.out.println();
    //Spacing
     if (correctGuesses == word2Char.length){
         System.out.println("Congratulations! You guessed the word. The word was: "+word2guess);
         nextWord = true;
     }
     if (wrongGuesses == 5){
       System.out.println();
       //Spacing
       System.out.println("Game Over! You have no attempts remaining. The word was: "+word2guess);
       nextWord = false;
       break;

      }

    }

}

A: This section of code:
for (int i = 0; i < word2Char.length; i++){
        if (guess == word2Char[i]){
           wordLength[i] = word2Char[i];
           letterFound = true;
           correctGuesses++;
           System.out.println("Correct!");
        }

    }
       if(!letterFound){
        wrongGuesses++;
    System.out.println("Wrong!");
       }

Needs to be this:
for (int i = 0; i < word2Char.length; i++){
                if (guess == word2Char[i]){
                   wordLength[i] = word2Char[i];
                   letterFound = true;
                   break;
                }else{
                    letterFound = false;
                }
            }
               if(letterFound == false){
                    wrongGuesses++;
                    System.out.println("Wrong!");
               }else{
                   correctGuesses++;
                   System.out.println("Correct!");
               }

The issue was that in the for loop, even if letterFound was true, the loop would keep on checking each char. It would've only worked if someone guessed the last char correctly. So what I did was add a break statement so that whenever letterFound is true, the for loop exits.

A: Notice that in java, this branch would never be used:
if (solved = false) {
    wrongGuesses++;
}

Please change that to
    if (solved == false) {
        wrongGuesses++;
        System.out.println("Wrong!");//And then add the wrong print out here
    }

I would like you to take a look here and here too


text:
Q: Laravel 5.5 unique validation rule on seperate table with different column name So I have users and companies. A user belongs to one company.
I want to validate a user registration so that the business_name field they use to register is unique in the companies table, the goal is to not allow users from creating duplicate companies.
Here is my register function:
public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'business_name' => 'required|unique:companies',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json(['error'=>$validator->messages()], 401);
        }

}

The field I want to compare against is the companies.name to check for uniqueness.
Is this possible? At the moment it is trying to look for business_name in the companies table.

A: Never mind, managed to figure it out. Just needed an extra parameter to specify the column name:
'business_name' => 'required|unique:companies,name',


text:
Q: can't add double forward slashes on exec function php Currently I have this problem in PHP, I am trying to make a simple webpage that executes some code in the shell and shows the proccess running
the code I am trying to execute is this
wmic -U User%Passwd //192.168.1.3 "select Caption from Win32_Process"

In the shell it executes correctly (Ubuntu 14.04 LTS) but in PHP those double slashes are taken as a comment, like in this code
exec('wmic -U User%Passwd //'.$IP.' "select Caption from Win32_Process"',$exit);

However, the double forward slashes (//) are commenting the rest of the code!
How can I rewrite that code in order for PHP to interpret those double slashes not as a comment but as part of the code?
Thank you in advance

A: You need to escape the slash / char with backslash char \, so your new code will be:
exec('wmic -U User%Passwd \/\/'.$IP.' "select Caption from Win32_Process"',$exit);

From PHP manual:

The backslash character has several uses. Firstly, if it is followed
  by a non-alphanumeric character, it takes away any special meaning
  that character may have. This use of backslash as an escape character
  applies both inside and outside character classes.
For example, if you want to match a "*" character, you write "*" in
  the pattern. This applies whether or not the following character would
  otherwise be interpreted as a meta-character, so it is always safe to
  precede a non-alphanumeric with "\" to specify that it stands for
  itself. In particular, if you want to match a backslash, you write
  "\".


text:
Q: moveit package following instructions provided but faced error after running in ros 2 [robot_state_publisher-3] [INFO] [1672396573.523060458] [robot_state_publisher]: got segment link6
[robot_state_publisher-3] [INFO] [1672396573.523065047] [robot_state_publisher]: got segment world
[ERROR] [robot_state_publisher-3]: process[robot_state_publisher-3] failed to terminate '5' seconds after receiving 'SIGINT', escalating to 'SIGTERM'
[INFO] [robot_state_publisher-3]: sending signal 'SIGTERM' to process[robot_state_publisher-3]
[ERROR] [robot_state_publisher-3]: process has died [pid 87783, exit code -15, cmd '/opt/ros/foxy/lib/robot_state_publisher/robot_state_publisher --ros-args -r __node:=robot_state_publisher --params-file /tmp/launch_params_7xb9pf6_'].

I tried to use your moveit package following instructions provided but faced error after running
$ ros2 launch moveit_config_m1013 m1013.launch.py


text:
Q: how to convert data before applying unique in search filter select in datatable I have question about the following code:
if (idx === 3) {
    dt.column(3, { search: 'applied' })
        .data()
        .unique()
        .sort()
        .each(function (d, j) {
            {
                if (renderFunction == null) {
                    select.append('<option value="' + d + '">' + d + '</option>');
                } else {
                    select.append('<option value="' + d + '">' + renderFunction(d, 'display', null) + '</option>');
                }
            }
        });
}

The issue is each cell value in column 3(column.data) is actually a list of string given by the view model. In this case, it is an array. According to other posts I know unique does not work for arrays. I tried to use tostring to convert the data before calling unique, but it's not working. I can't really figure this out. Could anyone help on that?
Thanks!


text:
Q: Can't access frontend Magento 2 I can't access the frontend of my website, and when I look at the error report it gives me the following message:
Session data file is not created by your uid

I can access the admin panel without issue.
Can anyone please advise troubleshooting steps/a solution?
I have copied all the website and db files from a site working on a subdomain. I have updated env.php and the core config data to include the new domain.

A: In believe this is caused by php-fpm not being able to write the session files. If you run the following
chown -r user:group /path/to/sessions
Replacing user and group with the ones that php-fpm uses and i cant remeber if path to sessions is under /var/lib/php/session or magento/var/sessions


text:
Q: What is the woman trying to say in the following context? A woman got pulled over for speeding by a California Highway Patrol motorcycle officer.
When he walked up to her window and opened his ticket book she said, "I bet you're going to sell me tickets to the Highway Patrol Ball."
He replied, "No, Ma'am, highway patrolmen don't have balls."
There followed a moment of silence while she smiled and he realized what he had said. Without saying another word, he closed his book, got back on his motorcycle and left."
Be clear and simple.

A: djechlin's answer here, and an interesting Snopes article explain the psychological and social dimensions of the double meaning in the punchline. But the basic situation, the underlying meaning of "buying tickets to the Policeman's Ball", rests on some cultural presuppositions which these don't explain.
From the end of the 19th century forward it became common to raise funds for the families of fallen police officers by selling tickets to an annual "Policeman's Ball", an evening of dancing and drinking.
Such tickets were of course sold by officers to residents and businesses on their individual beats; and where the police were corrupt, this became an instrument of extortion: police offered "protection" not only from criminals but also from legal prosecution in return for the purchase of tickets—and many simply pocketed the proceeds, or shared the proceeds among cooperating officers.
Eventually, when automobiles became common, this shake-down system was extended to traffic offenses: motorists could buy their way out of court appearances (and out of the associated 'points' which might lead to having their drivers licenses suspended, and would certainly lead to higher premiums for their automobile insurance) by paying the officer who stopped them, the whole being spoken of euphemistically as the innocent and indeed praiseworthy act of "buying a ticket to the Policeman's Ball."

I had seen Dad get nabbed […] when the family drove me to Cleveland to report to the Indians during my high school vacation in the summer of 1936. A cop pulled us over in Indiana for breaking the speed limit.
     He walked up to the car and asked Dad, "Would you like to buy a couple of tickets to the Policeman's Ball?" Dad said sure. He knew what he was doing. He rather have them instead of a speeding ticket.
     Dad bought the tickets and we headed to Cleveland, hundreds of miles from the site of the Policeman's Ball.
     —Now Pitching, Bob Feller

So when the lady says "I bet you're going to sell me tickets to the Highway Patrol Ball", she is in effect offering to bribe the patrolman.
The patrolman declines the bribe with the words "Highway patrolmen don't have balls"—meaning literally that the CHiPs don't sponsor such an annual fundraiser and figuratively that CHiPs are incorruptible.
Unfortunately (as the comments have told you) his words also bear a third sense: that highway patrolmen have no balls = "testicles". When he realizes what he has said the patrolman is so embarassed he simply closes his book (of 'tickets' or summons forms) and walks away.

A: A ball is a type of fancy party, and it's common that prestigious organizations, say all Los Angeles police officers, will hold one every year. The woman was just trying to get the man to say "Highway patrol officers don't have balls." There is some sarcasm in that being a highway patrol officer is not a prestigious job. The man chose to respond to this insult literally, as the woman baited. But mostly her line is just setting the man up for the punch line. It's more similar to the joke:

A: Can you get me an updog?
  B: What's updog?
  A: Not much, you?

He takes the bait and says

No, Ma'am, highway patrolmen don't have balls.

"Balls" is slang for "testicles," and implies both masculinity and bravery, i.e. "to have the balls to do something (scary)".
The man felt embarrassed for saying this and rather than write her a ticket, he chose to leave. I think the joke is misogynist in the sense that it's even more embarrassing or unusual for a woman to trick a man like this than if another man did it.
It is well-known that police officers have discretion to give the pulled over person a warning, a ticket, or just ignore the situation entirely. Some perceive this as corrupt, and there are many American jokes that take advantage of the fact that the police officer can somehow be "defeated" by a display of wit.


text:
Q: Easy XML Serializer for Java I'm looking for a way to serialize Java objects into XML for use by a RESTful web service.  I don't have an XSD.
I have looked at the following:

*

*JAXB - fairly heavy weight with annotations required on classes and also an ObjectFactory class and/or a jaxb.index file

*Simple - requires annotations but no other config classes/files.  Unfortunately it can't serialize Sets.

*XStream - no annotations etc. required, but doesn't support generics
Does anyone else have any suggestions?

A: import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;

public class XMLSerializer {
    public static void write(Object f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Object read(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        Object o = (Object)decoder.readObject();
        decoder.close();
        return o;
    }
}

A: JAXB is pretty painless, and comes with Java 6, and it has a low footprint.
You get this for the price of one annotation.
Order.java
package xxx;

import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Order {

    int custId;
    Date orderDate;
    String description;
    List<Item> items;

    public void setCustId(int custId) {
        this.custId = custId;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }

    public int getCustId() {
        return custId;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public String getDescription() {
        return description;
    }

    public List<Item> getItems() {
        return items;
    }

    public String toString() {
        return "Order: " + custId + " - " + orderDate + " - " + description + " - " + items;
    }
}

Item.java:
package xxx;

public class Item {

    String name;
    private int qty;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public String toString() {
        return "Item:" + name + " - " + qty;
    }
}

Test.java:
package xxx;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Test {

    public static void main(String args[]) throws Exception {
    Order o = new Order();
        o.setCustId(123);
        o.setDescription("New order");
        o.setOrderDate(new Date());

        List<Item> items = new ArrayList<Item>();

        Item i = new Item();
        i.setName("Duck Soup");
        i.setQty(10);
        items.add(i);

        i = new Item();
        i.setName("Carrots");
        i.setQty(4);

        items.add(i);

        o.setItems(items);

        //Write it
        JAXBContext ctx = JAXBContext.newInstance(Order.class);

        Marshaller m = ctx.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter sw = new StringWriter();
        m.marshal(o, sw);
        sw.close();
        System.out.println(sw.toString());

        // Read it back
        JAXBContext readCtx = JAXBContext.newInstance(Order.class);
        Unmarshaller um = readCtx.createUnmarshaller();

        Order newOrder = (Order) um.unmarshal(new StringReader(sw.toString()));
        System.out.println(newOrder);
    }
}

Results:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order>
    <custId>123</custId>
    <description>New order</description>
    <items>
        <name>Duck Soup</name>
        <qty>10</qty>
    </items>
    <items>
        <name>Carrots</name>
        <qty>4</qty>
    </items>
    <orderDate>2010-06-16T18:12:06.870-07:00</orderDate>
</order>

Order: 123 - Wed Jun 16 18:12:06 PDT 2010 - New order - [Item:Duck Soup - 10, Item:Carrots - 4]

A: My vote would be for XStream. The lack of generics support is a small price to pay for the amount of flexibility it offers. You can also easily implement generics by serializing the generic class type at serialization time, or build this into your domain objects. E.g.
   class Customer
   {
      List<Order> orders;

      public List<Order> getOrders()
      {
         return orders;
      }
   }

In the stream, the element type denotes the type of each object. When the type is an abstract type or interface, the element listed with the implementing class, unless that has been specified as the default for that interface type. (E.g. ArrayList as the default for instances of static type List.)
Generics are "rose coloured glasses" in java - they don't really change what you are seeing, just how you see it. The objects would be sent over the wire exactly the same if they were sent with generics support or not.

A: You can try JLibs XMLDocument. It uses SAX to create XML and thus light-weight and have complete control.


text:
Q: What are the squares in $\mathbb{R}((X))$? My attempt:
For an indeterminate $Y$ we know there exists $a_k \in \mathbb{R}$ with
$$\sqrt{1+Y} = \sum_{k=0}^{\infty} a_k Y^k.$$
If we would take an element $f(X) = \sum_{k=m}^{\infty} b_k X^k \in \mathbb{R}((X)$ for $b_k \in
\mathbb{R}$ and $m \in \mathbb{Z}$ we could substitute $f(X)$ for $Y$. Then we would get
$$ \sqrt{1+f(X)} = \sum_{k=0}^{\infty} a_k \left( f(X) \right)^k. $$
But the last sum is not an element in $\mathbb{R}((X))$ in general. If we would take $f(X) = X^{-1}$ for example then there exists no finite $n \in \mathbb{Z}$ and $c_k \in \mathbb{R}$ with
$\sum_{k=0}^{\infty} a_k \left( X^{-1} \right)^k = \sum_{k=n}^{\infty} c_k X^k$.
For $m \geq 0 $ otherwise we would get an element in $\mathbb{R}((X))$. But this would imply (for $f(X) = -1 + X$) that X is a square in $\mathbb{R}((X))$ which is false. Thus I think I cannot substitute simply $f(X)$ for $Y$. So my questions are:

*

*Why is this substitution not allowed?

*How can you find all the squares in $\mathbb{R}((X))$?

A: Nothing mysterious.
$$\Bbb{R}((X))^\times = X^\Bbb{Z}\ \times\ \Bbb{R}^\times\times\ 1\!+\!X \Bbb{R}[[X]]$$
$$\Bbb{R}((X))^{\times 2} = X^{2\Bbb{Z}}\ \times\ \Bbb{R}_{>0}\times\ 1\!+\!X \Bbb{R}[[X]]$$
In other words, an element of $\Bbb{R}((X))^\times$ is a square if and only if it leading term is of the form $a_kX^k$ where $k$ is an even integer (possibly negative) and $a_k>0$.


text:
Q: Some of my keys are automatically being pressed along with other keys History
The last time when my computer shutdown was a power failure. Now some keys are automatically being pressed when I type something.
The last thing I did to keyboard setting was adding a keyboard layout (on Ubuntu).
What is happening
Whenever I press c, xc is writeen
s gives me sd
d gives me sd
e gives me we
2 gives me 23, So when I want @ it gives me @#
3 gives me 23
Pressing CAPS Lock gives me F3 and vice-versa.
All other key are either working fine or I don't use them.
I have two operating system Ubuntu and Windows, I use Windows very less and found this problem on Ubuntu, but as soon as I logged in to Windows (for checking) then I found that Windows has the same problem.
Effects on my life

*

*This starts form the time of login, even I have problem in typing my password.

*Whenever I try to save any webpage, it is bookmarked automatically.

*Whenever I copy, it is cut automatically.

*I have to spend more than half of time correcting what I have typed.

Note: Typing thisd quwesdtion wasd rweally a big pain to mwe.

A: Looks like a broken keyboard.
You need to connect another keyboard to your computer and check if it works OR
connect this keyboard to another computer or laptop and check if it shows the same problem.

A: It seems like a hardware issue to me. I've had this several times in the past, and just replaced the keyboard. It could just be a piece of debris on one of the tracks. Do you have a spare around to check?

A: One thing I forgot to mention that a few months ago my drink was poured into the keyboard, after a 2-3 days my keyboard became home of a group of ants.
For getting rid from that I opened up my keyboard and cleaned it well, and finally sprayed an (liquid) ant repellent inside and outside of keyboard. I cleaned the excessive repellent as well, and screwed it up.
But I forgot that that transparent circuit board has three layers. And I just cleaned the outer layers leaving two layers wet which was doing short circuit.
In my case cleaning that liquid was the answer which was doing a short circuit I think. Now my keyboard it working fine like before. But one thing I'm still not getting is why it didn't just happened when I sprayed the repellent.

A: So I'm having the same issue recently. I thought problem was a bit of moisture underneath  the keys. So I've tried full dissassembly and cleaning on my keyboard but the problem was actually fixed but it was temporary. After couple hours RIP to my keyboard again. I think the only solution is to buy a new one

A: Encountered this problem with a Logitech K360 keyboard today. When I press some keyboard keys, one or multiple other keys are registering as being pressed as well. Basically multiple keys are being pressed at the same time, when I'm only actually pressing a single key. (For me it was: when I pressed D, B, Down or Asterisk, it would register as my having simultaneously also pressed Page Up.)
If you're seeing a consistent pattern like this, i.e. when you press certain keys it always registers as your having also pressed some specific other key(s), then you've almost certainly got a short circuit inside the keyboard hardware.
How to fix it
These kinds of short circuits can be fixed – you don't need to buy a new keyboard. Fixing it may be easier than you think.
Certainly in the case of Logitech's K360, the internal circuitry is nothing more than 3 sheets of plastic, which you can wipe clean. Many other keyboards use a similar system.

*

*Look up how to open your keyboard. Turn it off and remove batteries first.

*Carefully wipe down the plastic circuit layers. Look for signs where dirt has got in, or moisture has caused marks. Use a microfibre cloth with a very small amount of cleaning fluid to gently wipe these marks away. Use a dry cloth to give the whole thing a final clean wipe on all sides of all plastic layers.

*While you're at it, give the internals a bit of a clean.

*Put it back together.


text:
Q: How to filter nested object using lodash I have an object, which looks like this:
{
    'somename1':{
        status:'success',
        data:{
            key:'value1',
            field2:'',
            field3:'',
            field4:'',
            field5:'',
            recordSts:'done',
        }
    },
    'someOtherName':{
        status:'success',
        data:{
            key:'value2',
            field2:0,
            field3:'',
            recordSts:'progress',
            field5:'',
            field6:0,
        }
    }
}

In this object, I have two fields key and recordSts, which are not null if the status is success.
I want to filter this object using lodash and the output should look like this
{
    'somename1':{
        status:'success',
        data:{
            key:'value1',
            status:'value1',
        }
    },
    'someOtherName':{
        status:'success',
        data:{
            key:'value1',
            status:'value1',
        }
    }
}

Simply I want to delete the keys which having null or empty or 0 values.
I tried this:
_.map(records, 'key'); //records contains my input object

But it gives only the value of one field, instead, I want the name of the field and the second field also. Please help.
Thanks.

A: You can use _.pickBy with our custom predicate, like
_.forEach(records, function(record) {
  record.data = _.pickBy(record.data, function(val) {
      return !!val;
    }
  })

A: you can use _.omitBy to remove falsy values
let res = _.forOwn(records, o => {
    o.data = _.omitBy(o.data, v => {
    return !v;
  });
    return o;
});

A: You can use mapValues(), assign(), and pickBy():
_.mapValues(
  records,
  r => _.assign({}, r, { data: _.pickBy(r.data) })
);

This produces a new records object, without mutating the original. What I like about pickBy() is that by default, it'll only return properties with truthy values. Notice how we're not passing a predicate? This works because the default predicate is identity(), which simply uses the value as a truth test.


text:
Q: Como ler os microdados do ENEM no R? O INEP (Instituto Nacional de Estudos e Pesquisas Educacionais Anísio Teixeira) disponibiliza para download os microdados do ENEM (e outros) a partir deste link. Estes microdados são os dados crús do ENEM, com informações na granularidade de alunos.
Ao fazer o download dos microdados do ENEM 2014, por exemplo, você baixa um arquivo com extensão zip de aproximadamente 1,2Gb. Ao extrair o conteúdo deste arquivo há na estrutura de pastas toda a documentação deste conjunto de dados e também os microdados. Na pasta DADOS há o arquivo MICRODADOS_ENEM_2014.csv. Esse arquivo tem 6Gb de tamanho tal que comandos como:
dados <- read.csv('MICRODADOS_ENEM_2014.csv', header=T)

não funcionam na maioria dos PC's comuns em virtude da limitação da memória RAM.
Qual é a melhor alternativa para ler este conjunto de dados no R em um PC comum? Gostaria especialmente de métodos concretos para efetuar esta leitura com a ajuda de pacotes do R e TAMBÉM utilizando sistemas de gerenciamento de banco de dados.
OBS: Estou ciente com relação a pergunta Estratégias para analisar bases de dados muito grandes em R (que não caibam na memória RAM), tendo inclusive participado como um dos respondentes. ENTRETANTO, a pergunta teve um caráter mais genérico, não produzindo nas respostas nenhum código em R que pudesse resolver o problema específico desta questão.

A: Uma solução elegante e que pode ser praticamente independente de recursos computacionais é utilizar um software de pré-processamento linha a linha, filtrando apenas os registros desejados. A ferramenta mais conhecida e popular para esse tipo de tarefa é a AWK - uma linguagem de manipulação de textos -, cuja principal implementação é o gawk. O gawk possui implentações para Linux, Windows e MacOS.
Não tenho exatamente os dados do ENEM, mas suponha que você queira processar os arquivos do Censo Escolar 2015 (que, imagino, são bem semelhantes). A tabela TURMAS.CSV contém dados de todas as turmas de educação básica regular no Brasil. Há um campo nesta tabela, cujo cabeçalho indica o nome "CO_UF", que é o código da unidade da federação. Para filtrar somente os registros do Espírito Santo, por exemplo, cujo código de unidade da federação é 32 (conforme IBGE), eu chamaria o gawk da seguinte maneira:
gawk 'BEGIN {FS="|"} { if($73 == 32) print $0 }' TURMAS.CSV

Primeiramente (BEGIN) eu declaro o field separator (FS) como "|", que é o separador usado nestes arquivos do INEP. Depois eu verifico se o campo 73 (esta parte é chata, eu preciso contar os campos na descrição do CSV, ou na primeira linha que é o cabeçalho) é igual a 32 (código do ES). No gawk cada campo, divido pelo separador, é ordenado e identificado após o cifrão ($).
Se o teste for positivo, eu imprimo a linha inteira (o código $0 é especial e imprime toda a linha "recomposta", ou seja, os campos e os separadores). Para fazer uso desse filtro, eu redireciono o pipe para um arquivo:
gawk 'BEGIN {FS="|"} { if($73 == 32) print $0 }' TURMAS.CSV > filtrado_es.csv

O arquivo filtrado_es.csv contém, então, somente os registros que satisfizeram a condição de código de UF igual a 32, e portanto será menor, fazendo sofrer menos o R!
Se você tiver o gawk no seu PATH, pode chamar ele dentro do próprio R através do comando pipe(). Por exemplo:
read.csv(pipe("gawk 'BEGIN {FS=\"|\"} {if ($73 == 32) print $0}'
/caminho/para/TURMAS.CSV"))

Neste caso, o read.csv irá ler o arquivo já pré-processado pelo gawk.

A: Conceitos
Foram ótimas respostas até agora mas vou acrescentar aqui meus dois centavos. Eu diria que quando estamos trabalhando com conjuntos de dados que superam bastante o tamanho da memória RAM, para mim, o ideal é sempre trabalhar com sistemas de gerenciamento de banco de dados, como o PostgreSQL, o MySQL ou o MonetDB. Especialmente com microdados públicos, que em geral você só precisa ler uma vez e a partir daí só consultar, acredito que os SGBDs são a melhor abordagem. Além de permitir o armazenamento consistente dos dados, também é possível utilizar o pacote dplyr no R, com o backend de bancos de dados, tal que você pode utilizar as tabelas do banco utilizando praticamente a mesma sintaxe que utilizaria com um data.frame. É uma solução que é rápida, não tem as limitações que o R têm com RAM e que você pode utilizar depois por muito tempo.
Dos SGBDs disponíveis, dois que não dão nenhum trabalho de usar com R, não precisando ter que instalar nenhum outro software além do prórprio R são:

*

*SQLite3;

*MonetDB;

O primeiro pode ser utilizado facilmente a partir do R por meio do pacote RSQlite e o segundo por meio do pacote MonetDBLite. O meu preferido, e o que eu vou utilizar aqui como exemplo, é o MonetDB. Vou utilizá-lo porque dos dois é aquele que faz o armazenamento por colunas. ASSIM, a operação de escrita é um pouco mais cara, mas qualquer operação de consulta é muito mais barata. Se você trabalha com dados que não precisam ser escritos com frequência, mas precisam ser lidos com frequência, sistemas de gerenciamento de banco de dados colunares são superiores. Por outro lado, se além de ler você também precisa escrever no banco frequentemente, um banco como o SQLite (e outros) deve ser superior. Especificamente no caso de microdados, como Censo, ENEM ou Censo Escolar, que você deve carregar o banco uma vez e somente ler a partir daí, acredito que o MonetDB é a melhor opção disponível hoje.
Aplicação
Para utilizar a solução que vou propor aqui você deve ter o pacote MonetDBLite instalado no seu computador. No console do R digite:
install.packages('MonetDBLite', dependencies = TRUE)

A partir daí, o próximo passo será carregar os dados no banco. Felizmente o MonetDBLite é um pacote que permite fazer isso de forma automática utilizando a função monetdb.read.csv(). Supondo que você está com o conjunto de dados do ENEM, no meu caso o microdados_enem2014.csv, no mesmo diretório de trabalho onde você vai rodar o script, execute os seguintes comandos:
## Carregando os pacotes necessários
library(MonetDBLite)
library(DBI)

## Definindo um diretório
dbdir <- 'database/'

## Criando a conexão com um banco, criado na pasta database
con <- dbConnect( MonetDBLite::MonetDBLite() , dbdir )

## Fazendo a ingestao do csv no banco
monetdb.read.csv(conn = con, files = 'microdados_enem2014.csv', tablename = 'enem2014', header = TRUE, na.strings = '', delim = ',')

## Listando as tabelas no banco
dbListTables(con)

## Contanto o número de registros no banco
dbGetQuery(con, 'SELECT count(*) FROM enem2014')

## Consultando as 100 primeiras linhas
teste <- dbGetQuery(con, "SELECT * FROM enem2014 LIMIT 100")

O carregamento não demorou nem um minuto aqui na minha máquina, core i5 e 16Gb de RAM. Mas acredito que em uma máquina mais modesta deve demorar um pouco mais. Outro ponto fundamental é que o ideal é que o arquivo esteja em UTF-8 para o carregamento, e os csv's do ENEM estão em ISO-8859-1. Eu converti o arquivo facilmente por meio do comando iconv no terminal do Linux:
iconv -f ISO-8859-1 -t UTF-8 MICRODADOS_ENEM_2014.csv > microdados_enem2014.csv

mas no Windows você deve seguir o procedimento de instalação do iconv mostrado aqui. De fato há várias maneiras de mudar a codificação de arquivos no Windows e essa é somente uma sugestão.
Outro ponto a salientar é que como o banco e a tabela no banco já foram criados, você pode fazer consultas diretamente em SQL, como se estivesse no terminal do banco. Se você souber SQL seu problema está resolvido e basta gerar os dados necessários a partir da consulta e depois processá-los como data.frame no R.
Usando o dplyr
Naturalmente a melhor opção para usar bancos de dados com o R é utilizando o dplyr diretamente, o que permite ao usuário do R trabalhar com o banco sem escrever uma única linha de SQL. O mais legal dessa estratégia é que o dplyr converte os comandos em R para querys em SQL e até os resultados intermediários das consultas ficam dentro do banco de dados, tal que não há problemas de performance relacionados as limitações do R com a memória RAM.
Como um exemplo, vamos consultar a nota média dos alunos por estado e dependência administrativa, usando o dplyr.
## Carregando o pacote
library(dplyr)

## Ligando o dplyr na tabela
my_db <- MonetDBLite::src_monetdb(embedded=dbdir)
my_tbl <- tbl(my_db, "enem2014")

## Obtendo média de matemática por estado e dependência administrativa
consulta <- my_tbl %>% group_by(COD_UF_ESC, ID_DEPENDENCIA_ADM_ESC) %>% summarise(mean(NOTA_MT))

## Salvando a consulta como um data.frame
consulta <- collect(consulta)

o que resulta em:
  COD_UF_ESC ID_DEPENDENCIA_ADM_ESC       L1
        <int>                  <int>    <dbl>
1          NA                     NA 472.1223
2          26                      2 441.0514
3          32                      2 454.2741
4          35                      2 468.1310
5          11                      2 440.4378
6          33                      4 554.1954
7          33                      2 456.5003
8          23                      2 436.1984
9          29                      2 433.5961
10         53                      4 447.5004

Veja que será necessário converter os códigos das Unidades da Federação e da dependência administrativa para os respectivos nomes, que estão disponíveis no dicionário que vem com os dados do ENEM. Outro ponto é que ao final da consulta, para "salvar" o resultado da consulta como um data.frame no R você deve usar a função collect().
Por fim, ao terminar de utilizar o banco, você pode desconectar e desligar a instância do MonetDB que foi criada e está rodando na sua máquina:
## Desconectando do banco
dbDisconnect(con, shutdown=TRUE)

fique tranquilo que seus dados estão intactos. Se você precisar usar o banco depois basta reconectar como já fizemos anteriormente:
## Criando a conexão com um banco, criado na pasta database
con <- dbConnect( MonetDBLite::MonetDBLite() , dbdir )

A: Uma solução muito boa é usar a função read_csv_chunked() do pacote readr. Esta função permite a leitura e aplicação de uma função a cada chunk (número de linhas) iterativamente. Suponha que você quer apenas os dados do estado de São Paulo. Você pode limitar o número de linhas para importar de cada vez e filtrá-las por UF=="SP", antes de proceder ao seguinte chunk. Para tanto, basta  seguir o seguinte procedimento:
f<-function(x,pos) subset(x,UF=="SP")

df<-readr::read_csv_chunked("MICRODADOS_ENEM_2014.csv",DataFrameCallback$new(f),
chunk_size = 1000)

A: As funções do tipo read.csv que o R possui carregam na memória RAM o conteúdo dos arquivos que estão sendo lidos. Assim, há três maneiras principais de se trabalhar com dados grandes que não cabem na memória do R:

*

*Aumente a sua memória RAM

*Tome uma amostra dos seus dados

*Leia os dados a partir do disco, sem carregá-los na RAM
A solução 1 seria a ideal. Afinal, não seria preciso aprender nada novo, pois poderíamos trabalhar com os dados carregados diretamente na RAM, como se fosse um arquivo de tamanho normal. Entretanto, isto custa dinheiro.
A solução 2 não é ruim. Desde que se tome uma amostra representativa dos dados, não há porque imaginar que a análise feita deste jeito seja ruim. Mas nós estatísticos já trabalhamos com amostragem por tanto tempo. Por que não aproveitamos esta infinidade de dados que temos hoje em dia e não analisamos todos eles? Afinal, melhor do que cometer pequenos erros ao analisar uma amostra é não cometer erro nenhum, analisando a população inteira.
A solução 3 é a que mais me agrada. Ela implica em não carregar completamente os dados na memória RAM, e sim lê-los de maneira incremental a partir do disco. Felizmente, o R possui diversos pacotes que facilitam a nossa vida para fazer isto. Eu vou utilizar um deles aqui, chamado ff.
No exemplo abaixo eu carrego o pacote ff, leio os microdados do ENEM do ano de 2014 e crio uma tabela com o número de candidatos inscritos por estado brasileiro:
library(ff)
enem <- read.csv.ffdf(file="MICRODADOS_ENEM_2014.csv", header=TRUE)
table(enem[, 22])
             AC      AL      AM      AP      BA      CE      DF
  70096   65269  156393  172709   45553  720330  572238  143196
     ES      GO      MA      MG      MS      MT      PA      PB
 149299  218662  354018  987173  152758  155066  459417  233768
     PE      PI      PR      RJ      RN      RO      RR      RS
 441963  214878  409248  589757  196980   97263   19064  478792
     SC      SE      SP      TO
 143680  117885 1289458   67335

Note que utilizei o mesmo comando table que utilizamos normalmente para criar uma tabela de contagens no R. A única diferença está no comando read.csv.ffdf, que tem sintaxe idêntica do read.csv neste caso. Aliás, mesmo em outros casos, a sintaxe do read.csv.ffdf é bastante similar à sintaxe do read.csv.
Claro que esta solução tem problemas. O principal deles é a velocidade. Eu avaliei o tempo de execução dos dois comandos acima no meu PC e obtive o seguinte:
system.time(enem <- read.csv.ffdf(file="MICRODADOS_ENEM_2014.csv",
  header=TRUE))
    user   system  elapsed
3302.942  170.418 3596.523

system.time(table(enem[, 22]))
 user  system elapsed
0.550   0.185   0.945

Eu levei praticamente uma hora para ler os dados de um ano de ENEM. Só para título de comparação, fiz esta leitura em um laptop Intel i5 2.8GHz com 8GB de RAM e 512GB de SSD. A tabela, entretanto, foi feita bem rapidamente, levando menos de um segundo para ficar pronta.
Portanto, esta é uma maneira de ler grandes conjuntos de dados no R. Além do ff, o pacote bigmemory também é capaz disso. Imagino que hajam ainda mais pacotes, mas minha experiência se limita a estes dois.

Saindo um pouco do R, o que eu sugiro para ti, a fim de diminuir o tempo gasto na análise, é definir exatamente o que te interessa neste conjunto de dados. Ele tem 166 colunas. É muita coluna. Além disso, ele também tem 8.722.249 linhas. É muita linha. Claro que todas elas são importantes em nível nacional, mas talvez não sejam importantes para ti ou para a análise que tu pretende fazer. Eu recomendo fortemente aprender alguns comandos do bash, como grep, cut e awk, para fazer uma pré-filtragem destes dados.
Por exemplo, não há porque ler os resultados de todos os estados brasileiros na memória do R se apenas o Rio Grande do Sul te interessa. Talvez importar a chave de respostas de todos os alunos, com as colunas TX_RESPOSTAS_CN, TX_RESPOSTAS_CH, TX_RESPOSTAS_LC eTX_RESPOSTAS_MT, não seja interessante para ti. Pode ser ainda que todas as 76 colunas do questionário socioeconônico não importem para a tua análise. Não sei.
Mas, pela minha experiência, sugiro cortar tudo o que não te interessa antes de importar este conjunto de dados no R para poder facilitar a tua análise, principalmente se teu interesse for analisar os resultados de mais de um ano do ENEM. Imagine o tempo que vai ser gasto se tu precisar combinar os resultados de quase 20 anos do exame. Só a leitura dos dados vai levar 20 horas, assumindo que o tempo de leitura aumente de maneira linear, o que é uma suposição que não faz muito sentido.
Enfim, se eu estivesse fazendo uma análise deste tipo, eu excluiria as colunas e linhas que não me interessam, pois assim eu otimizaria meu código, fazendo com que ele executasse mais rapidamente, pois estaria tendo que gerenciar apenas os dados com os quais eu realmente me importo.


text:
Q: Reorganize full text catalog is offline or online? I need to schedule a Full Text Search Maintenance and I was reading this link: http://msdn.microsoft.com/en-us/library/ms176095.aspx. Reading this documentation I am supposing that I need to rebuild/reorganize the unique index used by the Full Text Search and then reorganize the Full Text Catalog. I am only concerning here, if this process of reorganize the Full Text Catalog is done online or offline? When the catalog reorganize is ocurring the users will still be able to query the full text data?
I appreciate any help here!
Regards,
Marcos Freccia

A: First of all, Welcome to stackexchange and thanks for your 1st Post.
To answer your questions :
if this process of reorganize the Full Text Catalog is done online or offline?
The reorganize process is Online, but is slower than Rebuild.
When the catalog reorganize is occurring the users will still be able to query the full text data?
Yes, but there might be blocking. Also you need to take account of below from BOL :
Depending on the amount of indexed data, a master merge may take some time to complete. Master merging a large amount of data can create a long running transaction, delaying truncation of the transaction log during checkpoint. In this case, the transaction log might grow significantly under the full recovery model.
Also, I would suggest you take a look at the fragmentation of the full text Indexes using :
I normally go for REORGANIZING if you have between 30-50 fragments per table
 -- for SQL Server 2008 and up
SELECT OBJECT_NAME([table_id]) AS TableName, COUNT([fragment_id]) AS Fragments
    FROM sys.fulltext_index_fragments
GROUP BY OBJECT_NAME([table_id])
HAVING COUNT([fragment_id]) >=30

Also, Improve the Performance of Full-Text Queries is a good reference along with this whitepaper.


text:
Q: How can I specify requirements for development separately from actual application dependencies? In a Python project and in general? We have dependencies required for local development that we'd like to specify in our project for the sake of other developers. These dependencies are not actually required by the application though. In python we specify dependencies that the app need in a requirements.txt.
What is the best practice for specifying/pinning development specific (not required by the app) dependencies and packages? In python projects?

A: I configure my projects with a requirements.txt file for the virtual environment.
I also have a requirements.dev.txt file where I put my special developer helpful libraries.
pip install -r requirememts.dev.txt

Where my requirements.dev.txt is like
-r requirements.txt
django-debug-toolbar>=1.7
ipython>=5.5
readline>=6.2
djangorestframework==3.8.2
djangorestframework-api-key==0.3.1

The first line cause the standard requirements.txt file to load


text:
Q: ZOL vs zfs-FUSE I run a server using 5 drives in a raidz2 through zfs-fuse, but sometimes encounter an issue where the pool becomes unavailable. The issue seems to co-inside with high levels of activity on the pool, and I suspect that this is causing zfs-fuse to crash and not be remountable without the -l arg. This may simply be due to the fact that zfs-fuse runs in user mode.
This brought up the question of using ZOL instead of zfs-fuse for performance or stability reasons.
My question is: which is better and why? Are they at the same levels of maturity and stability? Would there be any issues switching over, or can I simply follow the instructions here.
The last post I found about this was from 2008, and I would like a more recent answer.

A: ZOL still is in it's developing part, and sadly, this developing part isn't stable. You may achieve decent results when you just install ZOL and don't touch it from this point, but when you will try to do something that is routine in the ZFS-native OS (Solaris/FreeBSD), such as

*

*trying to grow a pool by send/receiving on larger disks or merey resizing them in a virtual environment

*trying to upgrade your kernel version while booting from zfs and/or having root there. Or when you even don't have root there.

you will get weird results, sometimes system-destructive.
So basically - don't use ZFS on Linux in your production until you're ready for those. "Ready" here means - you have standby servers, hot backups and so on. Otherwise use FreeBSD (yes, they switched their ZFS upstream to ZOL, but they also have injected a massive amount of FreeBSD-specific patches there and they still have loads of FreeBSD-code in their kernel that Linux just doesn't have) since Solaris sems to be already dead.
P.S. And don't use FUSE at all.


text:
Q: Matching with Regex in Javascript (Optional substring) String:
<p>[element title="Some title"]Some random text[/element]
[element]Some random text[/element]</p>

Need to extract:
1) Element title (optional) - 'Some title'
2) Element content - 'Some Random Text'
http://regex101.com/r/eB0jE6/1
How to make title in the element optional?

A: Put the title part inside a  non-capturing group and then make it as optional.
\[element(?:\stitle="([^"]+)")?]([^\[\]]*)\[\/element\]

DEMO


text:
Q: Не реализуется геттер? есть такой код. Не могу вызвать геттер из класса Flower. Понятно почему, потому что он не статический и на момент его вызова объекты класса Flower отсутствуют. Но фактически они есть, так как я выше создаю три массива из объектов наследуемых классов от Flowers(розы, тюльпаны и орхидеи) НО(!) внутри метода createFlowers. Как сделать так чтобы геттер "чувствовал" не явное создание объекта в методе мейн, а посредством метода класса этого объекта. Или
может я что то совсем делаю не так? Прошу не кидать палками учусь ровно месяц :)
public class FlowerShop {
public static void main(String[] args) {

....тут ничего важного и влияющего на проблему, далее
    if (viewAssortiment.equals("нет")) { // Клиент не зашел в магазин
        seller.SaysGoodBye();

    } else if (viewAssortiment.equals("да")) { // Клиент зашел в магазин
        Rose.createFlowers("Роза", 600, 15);
        Tulip.createFlowers("Тюльпан", 450, 25);
        Orchid.createFlowers("Орхидея", 400, 21);

        seller.ShowsAssortment(someFlowers.getFlowerName);} ЭТОТ ГЕТТЕР ГОРИТ КРАСНЫМ

public class Flower {

private String flowerName;
private int flowerCost;
private int currentNumberOfFlowers;

public String getFlowerName() {        ВОТ ЭТОТ ГЕТТЕР!
    return flowerName;
}

public int getFlowerCost() {
    return flowerCost;
}
public int getCurrentNumberOfFlowers(){
    return currentNumberOfFlowers;
}

public Flower(String flowerName, int flowerCost) { // конструктор
    this.flowerName = flowerName;
    this.flowerCost = flowerCost;

}

public static void createFlowers(String flowerName, int flowerCost, int currentNumberOfFlowers) { // массивы различных видов цветов в разном количестве
    int i;
    Flower[] someFlowers = new Flower[currentNumberOfFlowers];
    for (i = 0; i < someFlowers.length; i++) {
        someFlowers[i] = new Flower(flowerName, flowerCost);
    }

}
public class Seller { // Класс Продавец
public void ShowsAssortment (String x) {
    System.out.println("На текущий момент в магазине имеются: " + x );
}

}
Очень буду благодарен за помощь особенно если объясните подробней мою ошибку)

A: public static Flower[] createFlowers(String flowerName, int flowerCost, int currentNumberOfFlowers) { // массивы различных видов цветов в разном количестве
    int i;
    Flower[] someFlowers = new Flower[currentNumberOfFlowers];
    for (i = 0; i < someFlowers.length; i++) {
        someFlowers[i] = new Flower(flowerName, flowerCost);
    }
    return someFlowers;
}

public static void main(String[] args) {
  Flower[] someFlowers = Flower.createFlowers("Tulip", 5, 3);
  for (int i = 0; i < someFlowers.length; i++) {
    System.out.println(someFlowers[i].getFlowerName());
  }
}


text:
Q: Group of order $315$ has an order $5$ group in its center This question is based off of the Fall 2019 UCLA Algebra qualifying exam:
I am trying to show that any group $G$ of order $315=3^2\cdot5\cdot 7$ has a normal subgroup of order 5. Since the automorphism group of $\mathbb{Z}/5\mathbb{Z}$ is of order 4, which is prime to 315, this would prove that there is a group of order 5 in the center of $G$.
By the Sylow theorems, the number of 5-Sylow subgroups is $\equiv 1\mod{5}$, and by the orbit-stabilizer theorem, the number of 5-Sylow subgroups must divide $3^2\cdot 7$, which implies that the number of 5-Sylow subgroups $n_5$ is either 21 or 1. Using the same method, we see that $n_7$ is either 15 or 1 and $n_3$ is either 1 or 7.
I at least want to prove that one of the Sylow sugroups is normal. Using a counting argument doesn't help me here, since there are at most $21\cdot4=84$ elements of order 5 and there are at most $15\cdot 6=90$ elements or order 7. I am unsure of how to bound the elements of order 3 or 9, but adding the maximum number of elements of order 3 or 9 with $84+90$ won't get us a number higher than 315, so we won't get a contradiction.
Another possible way to prove there exists a normal sylow subgroup is by looking at their normalizers. Suppose that none of the Sylow groups are normal, so $n_5=21$, $n_7=15$, and $n_3=7$. Then there exists normalizers of certain Sylow groups of order $15$, $21$, and $45$. I am unsure how to use this fact to find a contradiction.
I am not looking for a detailed solution, but any small hints to this problem are appreciated!

A: If $n_3 = 7$ and $P \in {\rm Syl}_3(G)$, then $|N_G(P)|=45$.
Neither of the the two possible types of groups of order $9$ ($C_9$ and $C_3 \times C_3$) has an automorphism of order $5$, so there exists $Q \in {\rm Syl}_5(G)$ with $Q \le C_G(P)$, and hence $P \le N_G(Q)$, and now we can prove that $n_5=1$.
I will leave the case $n_3=1$ to you.


text:
Q: Create an new administrator level login in Azure SQL? I need to replace my old admin login/user with a new one. I tried the following:
CREATE LOGIN newDbAdmin WITH password='123isTheBestPasswordEver'
CREATE USER newDbAdmin

With this I'm then also able to log into Azure SQL via Microsoft SQL Server Management Studio. However it doesn't seem to be an admin level login+user. I'm unable to create tables and a few other things that admins can do. I suspect I need to GRANT permissions to certain schemas (dbo?) or something along those lines ...
So, what's the right way to create user+login on Azure SQL with the same level of privileges as the original admin (created when I create the DB via the Azure portal site).
On a related note, I assume the proper way to dispose off the old login is:
DROP USER oldAdmin
DROP LOGIN oldAdmin

?

A: You can only have one server-level admin. You can create as many other logins and users as you like but they need to be granted access to the individual databases separately. You can reset the password for the server-level admin via the azure portal.
There's no server role in Azure SQL Database that grants access to all databases. dbmanager lets you create databases, loginmanager lets you create logins, but the server-level principal login must be used to grant access to individual databases.
To create a new user and give dbo rights to one or more databases:
-- in master
create login [XXXX] with password = 'YYYYY'
create user [XXXX] from login [XXXX];

-- if you want the user to be able to create databases and logins
exec sp_addRoleMember 'dbmanager', 'XXXX';
exec sp_addRoleMember 'loginmanager', 'XXXX'

-- in each individual database, to grant dbo
create user [XXXX] from login [XXXX];
exec sp_addRoleMember 'db_owner', 'XXXX';

And yes, you drop users in the same way you would in on-premises sql.
If you wanted to make a new user as dbo on all databases on a server you can use a little powershell to make your life easier:
$newSqlUser = 'YOUR_NEW_LOGIN_HERE';
$serverName = 'YOUR-SERVER-NAME.database.windows.net'
$sqlAdminLogin = 'YOUR-ADMIN-SQL-LOGIN'
$createAdminUser = $TRUE;

# generate a nice long random password
Add-Type -Assembly System.Web
$newSqlPassword = [Web.Security.Membership]::GeneratePassword(25,3) -Replace '[%&+=;:/]', "!";

# prompt for your server admin password.
# Don't need the username param here but can be nice to avoid retyping
$sqlCreds = get-Credential -Username $sqlAdminLogin -Message 'Enter admin sql credentials'

# Create login and user in master db
$sql = "create login [$newSqlUser] with password = '$newSqlPassword'; create user [$newSqlUser] from login [$newSqlUser];"
invoke-sqlcmd -Query $sql -ServerInstance $serverName -Database 'master' -Username $sqlCreds.UserName -Password ( $sqlCreds.GetNetworkCredential().Password )
"new login: $newSqlUser"
"password: $newSqlPassword"

# sql to create user in each db
if ( $createAdminUser ) { `
    $createUserSql = "create user [$newSqlUser] from login [$newSqlUser]; exec sp_addRoleMember 'db_owner', '$newSqlUser'; "; `
} else { `
    $createUserSql = "create user [$newSqlUser] from login [$newSqlUser]; exec sp_addRoleMember 'db_datareader', '$newSqlUser'; exec sp_addRoleMember 'db_denydatawriter', '$newSqlUser';"; `
}

# can't have multiple Invoke-SQLCmd in a pipeline so get the dbnames first, then iterate
$sql = "select name from sys.databases where  name <> 'master';"
$dbNames = @()
invoke-sqlcmd -Query $sql -ServerInstance $serverName -Database 'master' -Username $sqlCreds.UserName -Password ( $sqlCreds.GetNetworkCredential().Password ) | `
   foreach { $dbNames += $_.name }
# iterate over the dbs and add user to each one
foreach ($db in $dbNames ) { `
       invoke-sqlcmd -Query $createUserSql -ServerInstance $serverName -Database $db -Username ($sqlCreds.UserName) -Password $( $sqlCreds.GetNetworkCredential().Password ); `
      "created user in $db database"; `
}

A: You can use Azure AD to manage the server. Create a DBA group - assign all DBAs to that group. Then assign the group as the AD Manager for the server - that allows you to have multiple DBAs
Anyone in that group will have full DBA permission over the server.
https://learn.microsoft.com/en-gb/azure/sql-database/sql-database-aad-authentication
Ideally, I think they expect you to use DB level contained users granted by a DBA. For us, we needed multiple admins as we have a lot of databases.

A: you just created a login and a corresponding user, you have to add the appropriate role memberships...
e.g.,
EXEC sp_addrolemember 'dbmanager', 'login1User';
EXEC sp_addrolemember 'loginmanager', 'login1User';
see: https://azure.microsoft.com/documentation/articles/sql-database-manage-logins/


text:
Q: Finding power of the given test Given that $X$ is a single observation from $f(x;\theta)=(2\theta x+1-\theta)I_{[0,1]}(x)$ where $-1\leq \theta \leq 1.$
The objective is to test the hypothesis $H_0:\theta\leq0$ Vs $H_1:\theta>0$ where $H_0$ is rejected when $X>\frac{1}{2}$.
I am a little confused about finding the power of the test. Power of this test is given as $1-\beta$, where $\beta=P(Accept\:H_0\:|\:H_1)$. Hence, $1-\beta=P(Reject\:H_0\:|\:H_1)$ i.e. $P(X>\frac{1}{2})$ under $H_1$.
Thus, $P(X>\frac{1}{2})=\int_{\frac{1}{2}}^{1}f(x;\theta)dx=\int_{\frac{1}{2}}^{1}(2\theta x+1-\theta)dx=(\theta x^2+x-\theta x)|_{\frac{1}{2}}^{1}=1-\frac{1}{4}[2-\theta]$.
Obviously this is a function of $\theta$ since under $H_1$, $\theta >0$ is unknown.
Now in general in hypothesis testing what we do is, we fix the size of the test i.e we fix $P(Reject\:H_0\:|\:H_0)$ and then maximize the power function $1-\beta$ or equivalently minimize $\beta$.
So if we maximize the power function obtained above for $-1\leq\theta \leq 1$, we obtain $(1-\frac{1}{4})=\frac{3}{4}$.
Is that correct ?
Also, can anyone provide a hint for finding a test for the given hypothesis that minimizes the largest of $\alpha$ and $\beta$. (For any general distribution).
$H_0:\theta = \theta_1$ Vs $H_1:\theta = \theta_2$
Are we supposed to follow that same technique i.e. fixing $\alpha$ first and then handling $\beta$ ? Or something else ?


text:
Q: read() and buffer size errors in (C Linux) //EDIT: I set the first handle's flag as O_WRONLY, it should be O_RDONLY and that was causing a problem.
I'm working on a simple program in Linux using C that would copy text from one file to another.
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>

...

int main(int argc, char * argv[])
{
    int cp_from = open(argv[1],O_WRONLY);
    int cp_to = open(argv[2],O_WRONLY|O_CREAT,0777);    //make a descriptor for each file
    int size = lseek(cp_from,0,SEEK_END);               //check the size of the first file
    lseek(cp_from,0,SEEK_SET)                           //return to the start of the file, don't know if that's needed
    char *buf = (char*) malloc (size*sizeof(char));     //allocate enough memory to fit all text from 1st file into char array
    read(cp_from,buf,sizeof(buf)-1);                    //read from the 1st file to the char array
    printf("%s",buf);                                   //print the buf
    close(cp_from);
    close(cp_to);
...

So, later I would write() the "buf" to "cp_to" and that would (hopefully) work. But, here's only half of the work because it stopped working at this point, "buf" is empty and I don't know why. Any ideas?

A: Here are some review points:

*

*Don't cast the return value of malloc() in C.

*Don't use sizeof on a heap pointer thinking it will return anything to do with the allocated buffer's size; it won't. You'll get the size of the pointer.

*Use proper types, not just int for everything. Types matter, and not all types are like int.

*Don't treat random data read from a file as a string.

*Don't do I/O and not check return values. I/O can fail.

*... so can memory allocations.

It's probably better to use a small (or smallish) fixed-size buffer, and read/write in a loop. That way your program uses a bounded amount of memory, regardless of the size of the file.

A: the following code:

*

*still has a warning about unused variable argc (see comments)

*is missing code to check for error indications returned from system function calls

*actually works

and now the code
//#include <sys/types.h>
//#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>

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

int main(int argc, char * argv[])
{

    int cp_from = open(argv[1], O_RDONLY);

    int cp_to = open(argv[2], O_WRONLY|O_CREAT,0777);

       //make a descriptor for each file

    size_t size = (size_t)lseek(cp_from,0,SEEK_END);               //check the size of the first file
    lseek(cp_from,0,SEEK_SET);
    //return to the start of the file, don't know if that's needed

    char *buf = malloc (size);     //allocate enough memory to fit all text from 1st file into char array
    read( cp_from, buf, size );                    //read from the 1st file to the char array
    write( cp_to, buf, size );                                   //print the buf
    close(cp_from);
    close(cp_to);
}


text:
Q: Repeat vector when its length is not a multiple of desired total length I have a data frame with 1666 rows.  I would like to add a column with a repeating sequence of 1:5 to use with cut() to do cross validation.  It would look like this:
   Y      x1       x2       Id1
   1      .15      3.6       1
   0      1.1      2.2       2
   0      .05      3.3       3
   0      .45      2.8       4
   1      .85      3.1       5
   1      1.01     2.9       1
  ...      ...     ...      ...

I've tried the following 2 ways but get an error message as it seems to only add numbers in increments of the full seq() argument:
>   tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2,  :
  replacement has 1665 rows, data has 1666
>   tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5) + (nrow(tr2)%%5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2,  :
  replacement has 1670 rows, data has 1666

Any suggestions?

A: Use the length.out argument of rep() or rep_len (a "faster simplified version" [of rep]):

length.out: non-negative integer. The desired length of the output vector

Here is an example using the built-in dataset cars.
str(cars)
'data.frame':   50 obs. of  2 variables:
 $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
 $ dist : num  2 10 4 22 16 10 18 26 34 17 ...

Add grouping column:
cars$group <- rep(1:3, length.out = 50L)

Inspect the result:
head(cars)
  speed dist group
1     4    2     1
2     4   10     2
3     7    4     3
4     7   22     1
5     8   16     2
6     9   10     3

tail(cars)
   speed dist group
45    23   54     3
46    24   70     1
47    24   92     2
48    24   93     3
49    24  120     1
50    25   85     2

A: Something, like this?
df <- data.frame(rnorm(1666))
df$cutter <- rep(1:5, length.out=1666)

tail(df)
     rnorm.1666. cutter
1661  0.11693169      1
1662 -1.12508091      2
1663  0.25441847      3
1664 -0.06045037      4
1665 -0.17242921      5
1666 -0.85366242      1