text:
Q: Table 'todoblog.users' doesn't exist I'm trying to create a small todo blog using sequelize. But I get stacked in this error. The table is not created. I created the database using SQL, then I used sequelize in the model and controller.
schema.sql
(here I created a database and run it manually in the terminal)
DROP DATABASE IF EXISTS toDoBlog;
CREATE DATABASE toDoBlog;
USE toDoBlog;

connection.js
(Here when I'm connecting to the database)
// connection
const sequelize = new Sequelize("toDoBlog", "name", "password", {
  host: "localhost",
  dialect: "mysql",
  host: "localhost",
});

// testing connection to database
sequelize
  .authenticate()
  .then(() => {
    console.log("Connection has been established successfully.");
  })
  .catch((err) => {
    console.error("Unable to connect to the database:", err);
  });
module.exports = sequelize;

userModel.js
(creating the table and define it)
const Sequelize = require("sequelize");
const connection = require("../connexion/connexion.js");

const User = connection.define("user", {
  user_id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: { type: Sequelize.STRING, allowNull: false },
  email: { type: Sequelize.STRING, allowNull: false },
  password: { type: Sequelize.STRING, allowNull: false },
  createdAt: Sequelize.DATE,
  updatedAt: Sequelize.DATE,
});

module.exports = User;

userController.js
(create/find/delete operations)
const UserModel = require("../database/Model/userModel.js");

module.exports.createOne = async (req, res) => {
  const info = req.body;
  console.log(info);
  const user = await UserModel.create({
    name: info.name,
    email: info.email,
    password: "hash(info.password)",
  });
};

userRouter.js
(router for the controllers)
const userController = require("../controllers/userController.js");
var express = require("express");
var router = express.Router();

router.post("/createOne", userController.createOne);

module.exports = router;

index.js
(main file)
const express = require("express");
const bodyParser = require("body-parser");

const connextion = require("./database/connexion/connexion.js");
const userRouter = require("./routers/userRouter.js");
// const blogRouter = require("./routers/blogRouter.js");

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("express working");
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// to link the front. I need to get more info about it.
app.use(express.static(__dirname + "/../react-client/dist"));

app.use("/api/user", userRouter);
// app.use("/api/blogs", blogRouter);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

this is the error
[nodemon] starting `node server/index.js`
Example app listening at http://localhost:3000
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
{ name: 'SEMER', email: 'semer', password: 'smeer' }
Executing (default): INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);
C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256
        return new sequelizeErrors.DatabaseError(err);
               ^

DatabaseError [SequelizeDatabaseError]: Table 'todoblog.users' doesn't exist
    at Query.formatError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:256:16)
    at Query.run (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\mysql\query.js:68:18)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at async C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\sequelize.js:619:16
    at async MySQLQueryInterface.insert (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\dialects\abstract\query-interface.js:748:21)
    at async model.save (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:3954:35)
    at async Function.create (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\sequelize\lib\model.js:2207:12)
    at async module.exports.createOne (C:\Users\semer\Desktop\testing skills\toDoBlog\server\controllers\userController.js:6:16) {
  parent: Error: Table 'todoblog.users' doesn't exist
      at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
      at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
      at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
      at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
      at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
      at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
      at Socket.emit (node:events:329:20)
      at addChunk (node:internal/streams/readable:304:12)
      at readableAddChunk (node:internal/streams/readable:279:9)
      at Socket.Readable.push (node:internal/streams/readable:218:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'todoblog.users' doesn't exist",
    sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
    parameters: [
      'SEMER',
      'semer',
      'hash(info.password)',
      '2021-03-04 16:57:41',
      '2021-03-04 16:57:41'
    ]
  },
  original: Error: Table 'todoblog.users' doesn't exist
      at Packet.asError (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packets\packet.js:712:17)
      at Prepare.execute (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\commands\command.js:28:26)
      at Connection.handlePacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:425:32)
      at PacketParser.onPacket (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:75:12)
      at PacketParser.executeStart (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\packet_parser.js:75:16)
      at Socket.<anonymous> (C:\Users\semer\Desktop\testing skills\toDoBlog\node_modules\mysql2\lib\connection.js:82:25)
      at Socket.emit (node:events:329:20)
      at addChunk (node:internal/streams/readable:304:12)
      at readableAddChunk (node:internal/streams/readable:279:9)
      at Socket.Readable.push (node:internal/streams/readable:218:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'todoblog.users' doesn't exist",
    sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
    parameters: [
      'SEMER',
      'semer',
      'hash(info.password)',
      '2021-03-04 16:57:41',
      '2021-03-04 16:57:41'
    ]
  },
  sql: 'INSERT INTO `users` (`user_id`,`name`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
  parameters: [
    'SEMER',
    'semer',
    'hash(info.password)',
    '2021-03-04 16:57:41',
    '2021-03-04 16:57:41'
  ]
}
[nodemon] app crashed - waiting for file changes before starting...


text:
Q: Problem with publishing feed with mp3 attachment Hey all, i have an app that works both in canvas and tab.
my problem is that on the tab the feed with the attachment works great but on the canvas the attachment wont show up..
any ideas on how can i fix it? or if its a known bug in the Javascript SDK?
this is my javascript code:
FB.ui({
  method: 'feed',
  display: 'iframe',
  attachment : {
    media : [{
      type : 'mp3',
      src : 'http://midias.toingboo.pmovil.com.br/cont_din/fixo/blaving_audio/encNgjLDO73WjIzxRHk43yIxbycPKcU-xLt/2515.mp3',
      title : 'title',
      artist : 'artist',
      album : 'Blaving.com'
    }]
  }
});

of course i first do a FB.login()...

A: To set the artist in the "new method", the mp3 should have the artist info in the id3 info

A: I have solved this using the 'source' attribute, apparently facebook no longer uses the attachment object with media inside.
the correct way to do this is as follow:
FB.ui({
  method: 'feed',
  display: 'iframe',
  source: 'http://midias.toingboo.pmovil.com.br/cont_din/fixo/blaving_audio/encNgjLDO73WjIzxRHk43yIxbycPKcU-xLt/2515.mp3',
  name: 'title',
  description: 'description'
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing form value as POST and getting JSON as response Hello guys here is my form setup:
<form class="form" id="getstat" name="getstat" method="post" action="stat101.php" />

Enter the Message ID and hit the submit button:

<textarea name="msgids" id="msgid" wrap="physical" cols="40" rows="10"></textarea>

<input type="submit" name="submit" value="Check Status">
</form>

My stat101.php looks like:
$user="101";
$pass="xxx";
extract($_POST);
$ids=$_POST['msgid'];
$url="http://url.com";

$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type:
application/json'));
curl_setopt($c, CURLOPT_URL, "$url".$user.'/'.$pass.'
/VALUEOFIDS');
$content = curl_exec($c);
curl_close($c);
print_r($content);

The above code works if I hard code the "VALUEOFIDS", but I do not know how to get it work by posting from the form's input "msgid". The URL with the json formatted response I need to emulate is: http://url.com/{key}/{secret}/{msgid}. I'm having a hard time getting the correct code.
What I need to emulate is: curl -H "Accept: application/json" https://api.url.com/server/search/$1/$2/$3
When I do it in bash, it works fine.
Thank you in advance!

A: Inputs and textareas pass their values to the $_POST array with their name as the key. Your code example is using the id and not the name to fetch the value from the request. Try using the following:
// trim whitespace and carriage returns made possible by the textarea.
$ids = trim($_POST['msgids']);

...

curl_setopt($c, CURLOPT_URL, "$url".$user.'/'.$pass.'/'.$ids);


text:
Q: Using JobExecutionDecider with spring boot batch I made a projet with Spring Batch few month ago.
This project is working fine and is including an implementation of JobExecutionDecider
public class BatchDecider implements JobExecutionDecider {
private static final Logger log = LoggerFactory.getLogger(BatchDecider.class);

@Autowired
ConfigurationServiceWs config;

public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) {

    if (codition) {

        return new FlowExecutionStatus("AGAIN");
    } else {

        return new FlowExecutionStatus("FINISH");
    }
}

This has working fini with just Spring Batch.
Now I have to use it with Spring Boot Batch.
All the process is working fine until the decider step.
Where I return the good FlowExecutionStatus, but I don't know why, the job is completed with a "FAILED" status.
2017-01-19 17:11:35.347 DEBUG 23056 --- [nio-8081-exec-1] o.s.b.core.job.flow.support.SimpleFlow   : Completed state=Global Job.decision0 with status=AGAIN
2017-01-19 17:11:39.074 DEBUG 23056 --- [nio-8081-exec-1] o.s.b.core.job.flow.support.SimpleFlow   : Handling state=Global Job.FAILED
2017-01-19 17:11:41.002 DEBUG 23056 --- [nio-8081-exec-1] o.s.b.core.job.flow.support.SimpleFlow   : Completed state=Global Job.FAILED with status=FAILED
2017-01-19 17:11:43.170 DEBUG 23056 --- [nio-8081-exec-1] o.s.batch.core.job.AbstractJob           : Job execution complete: JobExecution: id=0, version=1, startTime=Thu Jan 19 17:11:12 CET 2017, endTime=null, lastUpdated=Thu Jan 19 17:11:12 CET 2017, status=FAILED, exitStatus=exitCode=FAILED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[Global Job]], jobParameters=[{time=1484842272108}]

Someone have an idea why isn't working?
Thanks!

A: I found a solution.
I'm using the decider to make a loop on my Job.
I was using this :
@Bean(name = "myJob")
public Job importUserJob() {
    return jobBuilderFactory.get("Global Job")
            .incrementer(new RunIdIncrementer())
            .flow(getListeDocMiseADispo())
            .next(decider).on("FINISH").end()

            .next(boucle())
            .next(decider).on("AGAIN").to(boucle())

            .end()
            .build();
}

And work's with this :
@Bean(name = "myJob")
public Job importUserJob() {
    return jobBuilderFactory.get("Global Job")
            .incrementer(new RunIdIncrementer())
            .flow(getListeDocMiseADispo())
            .next(decider).on("AGAIN").to(boucle())
            .next(decider).on("FINISH").end()

            .next(boucle())
            .next(decider).on("AGAIN").to(boucle())

            .end()
            .build();
}

But I don't know why.
Maybe, Spring-boot-batch-starter update my batch version and break that?
someone knows something.


text:
Q: invalid operands to binary expression ('struct node ' and 'struct node ') I have made a header file in which I have declared a struct node and made an object as List of that struct.
Here is my header file link.h:
struct node
{
    void *data;  //Generic data
    struct node *next;
}List;

Driver.c:
#include "link.h"
int main()
{
    List list1;
    return 0;
}

When I am trying to write a statement like
List list1; //in the driver file

It throws up an error saying:

invalid operands to binary expression ('struct node' and 'struct node')
use of undeclared identifier 'list1'; did you mean 'List'?

What could be causing this?

A: Most probably your intention is to have List being an alias for struct node, so you need to use typedef, otherwise List is not a type but an instance variable of the struct.
typedef struct node
{
    void *data;  //Generic data
    struct node *next;
}List;


text:
Q: create .xlsx file and save it in a location via save as dialog with tkinter for example -python3 I´m relative new in programming and im facing a issue i cant solve after hours of searching and trying..
So what i would like to is.. i have a program which does do some measurement stuff.
What i want to do is to export these results into a excel file (.xlsx)
Creating the excel file is not a big problem with the xlswriter module.
If i don't choose a path for the .xlsx file it actually saves it in the directory where my scripts are. And if i want to choose a path i can add that very easily in my skript.
But now i want that the User that does do the meaurements can actually choose where the .xlsx file will be saved. This should be archived with the tkinter module i guess (im open for different solutions). So with the tkinter module i can open a Dialog where the User can choose the directory without editing/modifying the actual skript, which makes it User-frendly.
So i already have coded some lines which is actually close to work i think.
In the first part of my skript it creates a workbook and writes some stuff inside and closes it.
In the second part the Dialog to save the file will show up and i can choose the location where my .xlsx file will be saved.
But the Problem is, that the Dialog actually dont save the .xlsx file that was created in the first part.
It only saves a new .xlsx file which is empty and i cant even open.
So there must be a way.. where the tkinter Dialaog actually grabs the .xlsx file from the first part of my skript or from the actual workbook i created and put that into the tkinter Dialog so i can save the .xlsx file where the User wants to.
Does someone have any idea or can help me?
Oh and if you have any tipps regarding writing a question here it also appreciated, thanks! :)
skript:
#Import necessary Library
import xlsxwriter
from tkinter import *
from tkinter import filedialog

savelocation = r'\Path'

#Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook (saveloaction)
worksheet = workbook.add_worksheet()

#Some data we want to write to the worksheet.
expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)

#Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

#Iterate over the data and write it out row by row.
for item, cost in (expenses):
    worksheet.write(row, col,     item)
    worksheet.write(row, col + 1, cost)
    row += 1

#Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')

workbook.close()

#open file.

#win = Tk()
#win.withdraw()
#openfile = filedialog.askopenfile(initialfile='Results.xlsx', initialdir=r'C:\Users\Bikes\Desktop\Results.xlsx' , filetypes=(('Excel File', '.xlsx'),('All Files','*.*')) )

#save file with dialog.

win = Tk()
win.withdraw()
#fileopen = filedialog.Open = "Results.xlsx"
filename = filedialog.asksaveasfilename(initialfile='Results.xlsx', initialdir='/', title = 'Save File', filetypes=(('Excel File', '.xlsx'),('Text File','.txt'),('All Files','*.*')))


text:
Q: Update database using Flask, Bootstrap and Ajax I want to update my database (add opinion) and automatically show them on my site without refreshing. I use flask, bootstrap and I want to write script to send data in AJAX.
So, it's my site when I have details about book(detail_book.html):
{% extends "bootstrap/base.html" %}
{% block content %}
*Here I have jinja2 to display content sent by render_template, not necessery to add here*
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">
Add opinion
</button>

Your opinion about {{ book.title }}

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
    </button>

        <form>

            Message:
            <textarea class="form-control" id="message-text"></textarea>

        </form>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" href="#" data-role="add">Send opinion</button>

{% endblock %}

So after clicking on button the modal window is displayed. After filling the message and clicking another button, I want to send id of book, author id and opinion to database. My tables in database look like:
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(40), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Opinion', backref='author', lazy='dynamic')

class Opinion(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'))

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), index=True)
    description = db.Column(db.String(255))
    author = db.Column(db.String(255))
    pages = db.Column(db.Integer)
    opinions = db.relationship('Opinion', lazy='dynamic')

And in my *routes.py I have method:
@app.route('/detail_book/<title>')
def detail_book(title):
    book = Book.query.filter_by(title=title).first_or_404()
    result = db.session.query(Book.id, Opinion.body).filter(Opinion.book_id==book.id).filter(and_(Book.title == title)).all()
    return render_template('detail_book.html', book=book, result=result)

So to sum up, I want to get data from my modal, send it to 1 table in database(Opinion) and display this opinion in my endpoint.
I have never worked with AJAX, I tried diffrent scripts from web, but in the end I gave up. Can someone help me solve this problem?


text:
Q: Ways that Android can connect with a remote service I am trying to write an Android app to connect to an existing web service. I'm pretty new to web services in general, other than what I've done with this first web services (written with JSPs, Struts 1.x, and JAVA).
This web service is connected to a document storage database. The user would first login to the service, then using search parameters (document title, type, etc.) the user would be displayed a list of possibly relevant documents. The user would choose a specific document from that list, and the service would then stream the entire document (pdf file) to the user for viewing.
What methods are available to Android where I can make a request given some specific parameters, and be able to parse a response?
The only thing I know of is HTTP, but my project leader (I'm a summer intern) is hinting that there are others available. I'm not sure where to start looking.
Thank you.

A: Is it a web service or a web application? If it's a bona fide web service, it should support SOAP or REST, for which there are Java libraries, but none included in Android so far. If it's a web application (just a html based user interface), you're going to have to look at web scraping of some sort -- I hope not, for your sake and for future maintainability. Perhaps you should ask your project leader to be a bit more forthcoming!

A: You could also find that sending binary messages over socket connections is another option - more opaque and less bytes used. See Google Protocol Buffers for an example.

A: You should ask for an api document or specification for whatever it is you're going to connect to from the Android app.
For extra credit (I always like to see initiative from Engineering Interns), you may want to volunteer to write the document or to further edit it as necessary.
It is often the case that api docs are out of date or were never really used. (Especially if the same person or team wrote the existing server and client(s).)

A: I went with using the HttpClient class. It is working except now I'm struggling with getting my HTTP GET messages short enough. Base64 compression isn't doing quite enough. Thank y'all for your helpful answers.


text:
Q: Unity Рисование линий на UI Есть ли возможность в Unity рисовать стандартные фигуры на UI элементах, таких как Panel, Image и тд?

A: Возможностями компонента Line Renderer всё, в принципе, и ограничивается.


text:
Q: ViewPager Not Synched with TabLayout I have a ViewPager and Tablayout that shows nth number of items. The Tabs are populated with the correct page titles and the ViewPager contained Fragments display the correct fine except that the selected Tab is not synched with the ViewPager current item.
The selected Tab position is 1 less than the position of viewpager current item. Here is the Viewpager adapter.
 public class ViewPagerAdapter extends FragmentStatePagerAdapter {
        public ViewPagerAdapter(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Recipe selectedRecipe = getRecipeList().get(position);
            return RecipeDetailFragment.newInstance(selectedRecipe.getId);
        }

        @Override
        public int getCount() {
            return .getRecipeList().size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Recipe selectedRecipe = .getRecipeList().get(position);
            String title = selectedRecipe.getTitle();
            return title ;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }

Here is how I setup the ViewPager
private void setupViewPager() {
       ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

}
Here is what the output looks like

Edit 1:
I think the problem have to do with how the getItem method of the ViewPager is being called, here is log of left and right scroll for10 items

A: instead of using static variable in fragment you can use,
 public function in fragment like below.
add
    @Override
    public Fragment getItem(int position) {
        Recipe selectedRecipe = getRecipeList().get(position);
        RecipeDetailFragment receiptFRagment= new ReceiptFragment();
        receiptFragment.setData(selectedRecipe.getId);
        return receiptFragment;
    }

instead of this
    @Override
    public Fragment getItem(int position) {
        Recipe selectedRecipe = getRecipeList().get(position);
        return RecipeDetailFragment.newInstance(selectedRecipe.getId);
    }

Add public function in fragment,
  public void setData(int id){
   this.id= id;
  }

A: Finally, this is how I synched the ViewPager selected item with the Tablayout selected tab.
void selectPage(final int pageIndex){
        new Handler().postDelayed(
                new Runnable() {
                    @Override public void run() {
                        tabLayout.setSmoothScrollingEnabled(true);
                        tabLayout.setScrollPosition(pageIndex, 0f, true);
                    }
                }, 100);
    }

Then I called this method from two places, first when I setup Viewpager
 recipePosition = getIntent().getIntExtra(Constants.RECIPE_POSITION, 0);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        if (recipePosition > 0){
            recipePosition--;
        }
        viewPager.setCurrentItem(recipePosition,true);
        selectPage(recipePosition);

And then second in the setItem
Recipe selectedRecipe = getRecipeList().get(position);
RecipeDetailFragment receiptFRagment= new ReceiptFragment();
receiptFragment.setData(selectedRecipe.getId);
selectPage(position);
return receiptFragment;

Its works, I still could not understand why these are not synched by default!


text:
Q: 9's complement of a 4-bit binary number I don't understand how to calculate the 9's complement of a binary number.
I can apply it to decimal ones, example 15 = (9-1)(9-5) ) 84
then I thought to proceed with a binary -> decimal -> 9's complement -> binary conversion but I guess it's not the right way to act.
enter image description here

A: Not sure if you're still looking for help on this, I see it's been two months. But I couldn't find how to do the 9's compliment of a BCD (Binary-Coded Decimal, which is stored in 4 bits up to 1001) anywhere on the front page of google, without converting the binary to decimal. This doesn't work if you only work in binary, like in an ALU.
After a bit of scratching around with 9's compliment on paper in binary, I found the answer.
You need to take 9 (1001), and add the 2's compliment of the 4-bit binary number that you want the 9's compliment of:
To find the 9's compliment of 2 (0010) for example
1. 1's compliment of 0010 = 1101
2. Add 0001 to get the 2's compliment = 1110
3. Add this to 1001 (9) = (1) 0111

This  can be tested in decimal: 0111 = 7, and 9 - 2 = 7.

Note that there was a carry bit (1) to the left. This indicates that the final answer is positive. For every 9's compliment up to 9, this carry bit will be 1.
The 9's compliments for 10 and above requires an extra step: you need to calculate the two's compliment again on the result of step 3. In the following example, I work out the 9's compliment for 13:
1. 1's compliment of 1101 = 0010
2. Add 0001 to get the 2's compliment = 0011
3. Add this to 1001 (9) = (0) 1100 (note that the carry bit = 0)
4. 1's compliment of 1100 = 0011
5. Add 0001 to get 2's compliment = 0100

In decimal: 9 - 13 = -4.

Note that there was no carry bit to the left (0). This means that the final answer is a negative value: -4.
Whether or not there is a carry bit to the left, will determine whether you need to do a second 2's compliment calculation at step 3, and also whether the final answer is a positive or a negative value.


text:
Q: Java: Duplicate objects getting added to set? If I run the below code then the output is 2 which means that the set contains 2 elements. However I think that set should contain 1 since both the objects are equal based on hashcode() value as well as .equals() method.
Seems like some obvious mistake in my understanding ?
package HELLO;

import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void main(String[] args) throws Exception {
        Set<Alpha> s = new HashSet<Alpha>();
        Alpha a1 = new Alpha();
        Alpha a2 = new Alpha();
        s.add(a1);
        s.add(a2);
        System.out.println(s.size());
    }
}

class Alpha {
    int a = 10;

    public int hashcode() {
        return a;
    }

    public boolean equals(Object obj) {
        return (obj instanceof Alpha && ((Alpha) obj).a == this.a);
    }

    public String toString() {
        return "Alpha : " + a;
    }
}

A: The @Overrides annotation  is to override the method with the same name in the super class".
@Override
public int hashCode() {
    return a;
}

@Override
public boolean equals(Object obj) {
    return (obj instanceof Alpha && ((Alpha) obj).a == this.a);

}

@Override
public String toString() {
    return "Alpha : " + a;
}

A: your method hashcode should be named hashCode (capital letter "C").
If you plan on overriding methods you should use the @Override annotation.
If you had used that annotation, you'd have noticed the problem earlier as the code wouldn't have compiled.

A: Your hashcode method does not override the Object class's hashCode method and thus your equals method breaks contract since it doesn't agree with the hashCode results, and you can have objects that are "equal" but have different hashCodes.
Remember: You should always use the @Override annotation when overriding methods as this will help you catch this and similar errors.
@Override  // ** don't forget this annotation
public int hashCode() { // *** note capitalization of the "C"
  return a;
}

Also, you will want to improve your code formatting, especially when posting code here for our review. We will be able to better understand your code and help you if it conforms to standards (that's why standards exist). So try to keep your indentations consistent with all code lines that are in the same block indented at the same level, and you will want to be sure that base level code, including imports, outer class declarations and its end curly brace, is flush left:
import java.util.HashSet;
import java.util.Set;

public class Test {

   public static void main(String[] args) throws Exception {
      Set<Alpha> s = new HashSet<Alpha>();
      Alpha a1 = new Alpha();
      Alpha a2 = new Alpha();
      s.add(a1);
      s.add(a2);
      System.out.println(s.size());
   }
}

class Alpha {
   int a = 10;

   @Override
   public int hashCode() {
      return a;
   }

   public String toString() {
      return "Alpha : " + a;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      Alpha other = (Alpha) obj;
      if (a != other.a)
         return false;
      return true;
   }
}

For a beautiful review on this, please read: Overriding equals and hashCode in Java


text:
Q: Arrange numbers with multiple constraints you have the following string of numbers: $10,3,7,9,11$ and they are in their respective positions from left to right, so 10 is 1st, 3 is 2nd, 7 is third, 9 is fourth and 11 is 5th.
Now, how many ways are there to arrange these 5 numbers, considering that 10 must always be at the left of 7 (not necessarily next to each other) and 3 must always be at the left of 9 (not necessarily next to each other)?

my approach:
11 can stay in any position so 5 ways to arrange it.
10 can stay in 3 of the remaining 4 position, because at its right there must be the 7.
3 can stay in only 2 of the remaining 3 because at his right there must be the 9.
9 and 7 are obliged in their positions.
Number of ways: $5*3*2 = 30 $
What do you think?

A: Answer is correct , for another approach:
The probability for  $10$ must always be at the left of $7$ (not necessarily next to each other) is $1/2$ and  the probability for   $3$ must always be at the left of $9$ (not necessarily next to each other) is $1/2$
So , $1/2 \times 1/2 = 1/4$ gives us the probability in which $10$ must always be at the left of $7$ (not necessarily next to each other) and $3$ must always be at the left of $9$ (not necessarily next to each other) in all arrangements of these $5$ numbers.
Hence ,it can be concluded that $1/4$ of the arragenments satisfy it , so $1/4 \times 5! =30$

A: After placing $11$, you mention that $10$ can be put in three of the remaining four positions, and $3$ can be put in only two of the remaining three positions. You finally state that $9$ and $7$ are obliged in their positions. But take these two cases -
11 10 3 9 7 and 11 10 3 7 9
After placing $11, 10$ and $3$, we still have two choices for $7$ and $9$.
So while the overall count is correct, the reasoning is not.
One of my approaches would be to place $11$ first and then as you mentioned there are three choices for $10$ but we observe that for every position of $10$ starting from left, the number of choices for $7$ reduces by one. So if $10$ takes the leftmost position after $11$ is placed, there are three choices for $7$; for the next position of $10$, there are two choices for $7$ and so on. Once we place $11, 10$ and $7$, positions of $3$ and $9$ are fixed.
So that gives $5 \cdot (3 + 2 + 1) = 30$ valid arrangements.


text:
Q: @AspectJ pointcut for all methods of a class with specific annotation I want to monitor all public methods of all Classes with specified annotation (say @Monitor) (note: Annotation is at class level). What could be a possible pointcut for this?
Note: I am using @AspectJ style Spring AOP.

A: Using annotations, as described in the question.
Annotation: @Monitor
Annotation on class, app/PagesController.java:
package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:
package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:
package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:
package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:
<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:
<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

A: it should be enough to mark your aspect method like this:
@After("@annotation(com.marcot.CommitTransaction)")
    public void after() {

have a look at this for a step by step guide on this.

A: You can also define the pointcut as
public pointcut publicMethodInsideAClassMarkedWithAtMonitor() : execution(public * (@Monitor *).*(..));

A: The simplest way seems to be :
@Around("execution(@MyHandling * com.exemple.YourService.*(..))")
public Object aroundServiceMethodAdvice(final ProceedingJoinPoint pjp)
   throws Throwable {
   // perform actions before

   return pjp.proceed();

   // perform actions after
}

It will intercept execution of all methods specifically annotated with '@MyHandling' in 'YourService' class. To intercept all methods without exception, just put the annotation directly on the class.
No matter of the private / public scope here, but keep in mind that spring-aop cannot use aspect for method calls in same instance (typically private ones), because it doesn't use the proxy class in this case.
We use @Around advice here, but it's basically the same syntax with @Before, @After or any advice.
By the way, @MyHandling annotation must be configured like this :
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyHandling {

}

A: I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}

@Aspect
@Component
public class AnnotationLoggerAspect {

    @Autowired
    private Logger logger;

    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";

    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());

            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }

    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());

            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

A: You should combine a type pointcut with a method pointcut.
These pointcuts will do the work to find all public methods inside a class marked with an @Monitor annotation:
@Pointcut("within(@org.rejeev.Monitor *)")
public void beanAnnotatedWithMonitor() {}

@Pointcut("execution(public * *(..))")
public void publicMethod() {}

@Pointcut("publicMethod() && beanAnnotatedWithMonitor()")
public void publicMethodInsideAClassMarkedWithAtMonitor() {}

Advice the last pointcut that combines the first two and you're done!
If you're interested, I have written a cheat sheet with @AspectJ style here with a corresponding example document here.

A: From Spring's AnnotationTransactionAspect:
/**
 * Matches the execution of any public method in a type with the Transactional
 * annotation, or any subtype of a type with the Transactional annotation.
 */
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
    execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);

A: Something like that:
@Before("execution(* com.yourpackage..*.*(..))")
public void monitor(JoinPoint jp) {
    if (jp.getTarget().getClass().isAnnotationPresent(Monitor.class)) {
       // perform the monitoring actions
    }
}

Note that you must not have any other advice on the same class before this one, because the annotations will be lost after proxying.

A: Use
@Before("execution(* (@YourAnnotationAtClassLevel *).*(..))")
    public void beforeYourAnnotation(JoinPoint proceedingJoinPoint) throws Throwable {
}

A: You could use Spring's PerformanceMonitoringInterceptor and programmatically register the advice using a beanpostprocessor.
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Monitorable
{

}

public class PerformanceMonitorBeanPostProcessor extends ProxyConfig implements BeanPostProcessor, BeanClassLoaderAware, Ordered,
    InitializingBean
{

  private Class<? extends Annotation> annotationType = Monitorable.class;

  private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

  private Advisor advisor;

  public void setBeanClassLoader(ClassLoader classLoader)
  {
    this.beanClassLoader = classLoader;
  }

  public int getOrder()
  {
    return LOWEST_PRECEDENCE;
  }

  public void afterPropertiesSet()
  {
    Pointcut pointcut = new AnnotationMatchingPointcut(this.annotationType, true);
    Advice advice = getInterceptor();
    this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
  }

  private Advice getInterceptor()
  {
    return new PerformanceMonitoringInterceptor();
  }

  public Object postProcessBeforeInitialization(Object bean, String beanName)
  {
    return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName)
  {
    if(bean instanceof AopInfrastructureBean)
    {
      return bean;
    }
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    if(AopUtils.canApply(this.advisor, targetClass))
    {
      if(bean instanceof Advised)
      {
        ((Advised)bean).addAdvisor(this.advisor);
        return bean;
      }
      else
      {
        ProxyFactory proxyFactory = new ProxyFactory(bean);
        proxyFactory.copyFrom(this);
        proxyFactory.addAdvisor(this.advisor);
        return proxyFactory.getProxy(this.beanClassLoader);
      }
    }
    else
    {
      return bean;
    }
  }
}


text:
Q: Dynamically add rows of data to a *.rpt file (C#) I am using vs2008 with CrystalReports and I'm wandering how can i dynamically add rows of data to a *.rpt file?(using c#).
In more detail i want to create a a function that populates a *.rpt file with data that might contain lists(for example "FirstName", "LastName", List<"Friend"> ;..Friend beeing an object that contains multiple fields like "FriendNr", "Address",....).
the code that i used so far is:
ReportDocument rpt = new ReportDocument();
MemoryStream stream = new MemoryStream();
string filename = filepath + "/myRpt.rpt";
rpt.Load(filename);

rpt.SetParameterValue(0, myObject.FirstName);
rpt.SetParameterValue(1, myObject.LastName);

Inside the rpt file i have placed FieldObjects(Parameter Fields), and i populate the file with data by assigning the desired values to these objects (" rpt.SetParameterValue(0, myObject.FirstName);" )
Please help me find a way to populate the report with the rows of data contained in the List also.
Thanks a lot for your time.

A: I don't think it is possible to add data rows to a report this way. I suggest using a Typed DataSet as your report data source. The report can then display as many Friend objects as you require.

A: Dynamic 'rows' approaches:
1). You could add more items to the parameter's CurrentValues collection.  Not sure how you are using this in the report, but it may work for your purposes.  Look at the ParameterFieldDefinition class for more information.
2). Create a DataSet, modify as necessary, then assign it to the report.  Use the ReportDocument.SetDataSource() method to bind a report to data programmatically.
3). Another approach is to build a report that uses XML data, then programmatically modify the XML, then refresh the report.


text:
Q: check out form that would match zipcode to an email I need to create a check out form that would automatically select a zip code from the billing address on the form and match the zip code with an assigned email. Each email will have multiple zip codes assigned to them. The form that I currently have is in cgi and I am not sure if it can implement this since it doesn't actually run off a data base.
I am looking for any opinion on how to accomplish this with out creating a database.
I am familiar with java script, php and html (cgi), is there anyway to do this with out creating a database using java script?
If I cant come up with anything, I may have to re-do everything and use a SQL DB for it.
Thank you.

A: you can have a JSON object in the Form which will hold all the zip code and email. something like this -
<script type='text/javascript'>
var emails = [{zip:12345,email:'test@email.com'},{zip:12312,email:'test@email.com'},{zip:12123,email:'email@test.com'}];
</script>

then you can get the email address by iterating through the object array using javascript. if you use jquery then you would to something like this to iterate
$.each(emails,function(i,item){
    if(item.zip == zip_code_in_address)
        variable_to_hold_email = item.email;
});

check the JSFiddle here


text:
Q: Windows XP: Computer cannot not found in the network I have a group network: COMPANY, so for every computer I click in computer, properties, than in computer name tab I change the work group, so I click in change to COMPANY.
So far this been working for every computer in the company, but one of them is not working.
Do you guys know why this is happening ?
This is so weird to me as for you guys. I know it sounds pretty crazy, but this is what´s happening here.

A: I foun the solution for my problem, in properties of my connection the 'Client for Microsoft Network' was disable, I don't know why, but I enable it, then restart the computer, after that everyting works fine.
This link also help me: http://www.bleepingcomputer.com/forums/topic47775.html


text:
Q: Criar um contador regressivo (countdown) partir de input e memorizar no localStorage Como podem ver no meu exemplo abaixo, eu tenho um formulário que joga os dados escritos nas entradas (input) no html e os mesmos são armazenados no localStorage.
No input=date eu preciso que a data fornecida seja transformada em um contador regressivo (countdown), para os dias restantes.
<form id="form">
    Name:        <input type="text" id="name">

    Deadline:    <input type="date" id="deadline">

    Image:       <input type="file" id="pic">
    <input id="create" type="button" value="Create" />
</form>

versão de exemplo no jsfiddle: https://jsfiddle.net/7qtk9gyh/
Gostei bastante do puglin jquery.countdown.js, é bem simples, porém, como sou novo com scripts, não sei mesmo como fazê-lo funcionar partir de um input e combinado com o formulário. Qualquer ajuda é muuuito bem-vinda!

A: Você pode transformar seus inputs de data em milissegundos e calcular a diferença entre eles

const date1 = new Date('8/1/2019'); // M/d/yyyy
const date2 = new Date(new Date().toDateString()); // cria uma data desconsiderando os milisegundos
const diffTime = Math.abs(date2.getTime() - date1.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(`Data 1 = ${date1}`);
console.log(`Data 2 = ${date2}`);
console.log(`Diferença de tempo = ${diffTime}`);
console.log(`Diferença de dias = ${diffDays}`);

Então, como você quer armazenar no local storage o resultado da diferença, seria necessário apenas adicionar ao final do código
localStorage.setItem('countdown', diffDays)


text:
Q: background task timeline in windows phone 8.1 I am using the background task for a various features in the application. No where in the MSDN documentation, i see how long it runs.
For example in windows phone 8 sdk, periodic agents used to run for 25 seconds. is there a specific amount that the background task  runs for ?
StorageFolder folder = KnownFolders.PicturesLibrary;
StorageFile TimeLogFile = await folder.CreateFileAsync("TimeLog.txt", CreationCollisionOption.OpenIfExists);

await Windows.Storage.FileIO.AppendTextAsync(TimeLogFile, "Start Logging " + DateTime.Now.ToString() + Environment.NewLine);
await Windows.Storage.FileIO.AppendTextAsync(TimeLogFile, "Beginning of Background Task " + DateTime.Now.ToString() + Environment.NewLine);

for (int i=0;i<100000;i++)
{
    await Windows.Storage.FileIO.AppendTextAsync(TimeLogFile, "During Background Task Execution " + DateTime.Now.ToString() + Environment.NewLine);
    Debug.WriteLine(i);
}
await Windows.Storage.FileIO.AppendTextAsync(TimeLogFile, "End Logging " + DateTime.Now.ToString() + Environment.NewLine);

A: Here's the info you're looking for: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh977056(v=win.10).aspx.
Basically, a background task can only use the CPU for 2 seconds each time it's started. It can however be active for a longer period, if it doesn't do CPU intensive work. If you await something slow that does not use the CPU too much, you can get to several minutes of execution.


text:
Q: How to POST Data/Register a User to the Server API using Alamofire? I just begin in iOS. I'm facing problem in POST the Data to server side. Actually, I have to register a User using the API "https://xyz.php"(random).
here i use the Alamofire Code.
        let parameters: [String: AnyObject] = ["name" : nameTxt.text as AnyObject,
        "password" : passTxt.text as AnyObject,
        "school" : schoolTxt.text as AnyObject,
        "class" : classTxt.text as AnyObject,
        "email" : emailTxt.text as AnyObject,
        "mobileno" : mobileTxt.text as AnyObject,
    ]

    Alamofire.request("https://xyz.php", method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in

            print(response)

    }

but when I hit the Submit Button it giving me error message in Success Response. Can Any One help me out. To make the user Register. with the given parameter using Alamofire.

A:   //  Try this after your parameters, with your URL
 Alamofire.request(your URL, method: .post, parameters: parameters).responseJSON
                    {
                        response in
                        //printing response
                        print(response)

                        //getting the json value from the server
                        if let result = response.result.value {

                            //converting it as NSDictionary
                            let jsonData = result as! NSDictionary
                           UserDefaults.standard.set("password", forKey: "user_id")

                           let userName = UserDefaults.standard.string(forKey: "user_id")
                           }
                        }

               // view controller identifier for your next view controller
     let abcd = self.storyboard?.instantiateViewController(withIdentifier: "abcd") as! DetailsViewController

                self.present(abcd, animated: true)

                }


text:
Q: Relative links with htaccess How can i convert all links within html to a relative links using .htaccess?
For example:
http://www.mydomain.com/info.html to /info.html

A: .htaccess commands cannot change the content of your html files where those URLs live.
You will need to post process your html files on the server before they are sent to the client. How you do this depends on how you generate those html files.


text:
Q: unslider carousel or infinite do not work I have a blog  and I want to use an unslider script to make carousel and infinite slideshow such that the slideshow have such action (good situation is my wish):
slide1 slide2 slide3 slide4 slide5 slide6 slide7 slide8 slide1 slide2 ...

But slider currently (at the moment) action is:
slide1 slide2 slide3 slide4 slide5 slide6 slide7 slide8 ...doesn't continue to slide1 (dire situation)

It also  jumps to slide one (the start point).
The problem I have is that when slider arrives to last slide it jumps to first slide and starting all actions from the first.
Working with unslider is very hard but I think unslider has not infinite or carousel option to use.
Please visit my blog to see problem.
ardatradecenter.rozblog.com
Problem in bottom in brands holder

A: Same Problem here, The issue comes from version compatibility.
Please refer to the Git.
https://github.com/idiot/unslider/issues/218


text:
Q: Weekly Weights Calculations in R Using dplyr I have the following data and looking to create the "Final Col" shown below using dplyr in R.
Please note, the "Trees" main category has a value of 0 for week 1, 2017. In this case, I would like the final values for both weeks to be 0.
I would appreciate your ideas.
| Year  | Week    | MainCat|Qty    |Final Col     |
|:----: |:------: |:-----: |:-----:|:------------:|
| 2017  | 1       | Edible |69     |69/(69+12)    |
| 2017  | 2       | Edible |12     |12/(69+12)    |
| 2017  | 1       | Trees  |00     |00            |
| 2017  | 2       | Trees  |12     |00            |
| 2017  | 1       | Flowers|88     |88/(88+47)    |
| 2017  | 2       | Flowers|47     |47/(88+47)    |
| 2018  | 1       | Edible |90     |90/(90+35)    |
| 2018  | 2       | Edible |35     |35/(90+35)    |
| 2018  | 1       | Trees  |32     |32/(32+12)    |
| 2018  | 2       | Trees  |12     |12/(32+12)    |
| 2018  | 1       | Flowers|78     |78/(78+85)    |
| 2018  | 2       | Flowers|85     |85/(78+85)    |

A: For this, you can use a combination of grou_by and a regular if ... else clause
library(dplyr)
set.seed(0)

# dummy data
data <- tidyr::expand_grid(year = 2017:2018,
            quarter = 1:2,
            MainCat = LETTERS[1:3]) %>%
  mutate(Qty = sample(0:15, 3*2*2)) %>%
  arrange(year, MainCat, quarter)

data %>%
  group_by(year, MainCat) %>%
  mutate(finalCol = if(any(Qty == 0)){ 0 } else {Qty / sum(Qty)})
#> # A tibble: 12 x 5
#> # Groups:   year, MainCat [6]
#>     year quarter MainCat   Qty finalCol
#>    <int>   <int> <chr>   <int>    <dbl>
#>  1  2017       1 A          13    0.684
#>  2  2017       2 A           6    0.316
#>  3  2017       1 B           8    0
#>  4  2017       2 B           0    0
#>  5  2017       1 C           3    0.75
#>  6  2017       2 C           1    0.25
#>  7  2018       1 A          12    0.632
#>  8  2018       2 A           7    0.368
#>  9  2018       1 B          10    0.476
#> 10  2018       2 B          11    0.524
#> 11  2018       1 C           2    0.333
#> 12  2018       2 C           4    0.667


text:
Q: Is it possible to make migrations from db not from model? Suppose, we have a db's backup and a django program. The program do not have any migrations. First we restore db, that has created table and data. Now we want to make migrations from available db. Is it possible or not?

A: Yes, Django has the inspectdb method, which is described here.
But if the Django app already has the models defined that correspond to the backed up database, then you can just run makemigrations (follow @Shafikur's instructions).

A: Just go to your corresponding database terminals and delete all the records from you django_migrations table with
delete from django_migrations;

Go to terminal and run remove all files in migrations folder with
rm -rf <app>/migrations/

Reset all the migrations of the Django's built-in apps like admin with the command
python manage.py migrate --fake

Create initial migrations for each and every app:
python manage.py makemigrations <app>

To create initial fake migrations just run
python manage.py migrate --fake-initial


text:
Q: JS: Assignment within if statment doesn't work I have a twodimensional array and want to set a random elements value to 2.
My attempt is the following, but that didn't work..
If the random value is undefined, then set it to 2, if not repeat.
Thanks in advance!
var randomTileFunction = function (board) {
  var randomTile = board[Math.floor(Math.random() * 4)][Math.floor(Math.random() * 4)];
  if(randomTile === undefined) {
    randomTile = 2;
  } else {
    randomTileFunction(board);
  }
};

A: randomTile is a variable whose assigment does not affect another variable board[Math.floor(Math.random() * 4)][Math.floor(Math.random() * 4)].
var i = Math.floor(Math.random() * 4);
var j = Math.floor(Math.random() * 4);
if(board[i][j] === undefined) {
  board[i][j] = 2;


text:
Q: Determine clicked JPanel component in the MouseListener. Event handling I have a class whitch extends JPanel:
public class ButtonPanel extends JPanel {

    private label;

    public ButtonPanel() {
        label=new JLabel("waiting for click");
        add(label);
    }

    public void setButtonText() {
        label.setText("just clicked");
    }

}

I have several instances of that class which is added to JFrame. I want to create one instanse of MouseAdapter class and then add them as a mouse listener to all of the ButtonPanel components on my JFrame. I meen:
ButtonPanel butt1 = new ButtonPanel();
ButtonPanel butt2 = new ButtonPanel();
ButtonPanel butt3 = new ButtonPanel();
//... here goes code which add ButtonPanels to JFrame

MouseAdapterMod mam = new MouseAdapterMod();
butt1.addMouseListener(mam);
butt2.addMouseListener(mam);
butt3.addMouseListener(mam);

The MouseAdapterMod class I want to be separate from the other and locate in it's own package. It should looks like this:
public class MouseAdapterMod extends MouseAdapter {

    public void mouseClicked(MouseEvent e) {
        //here goes the code of calling setButtonText method of ButtonPanel component on which the event had occurred
    }
}

So the problem is that I don't know how to implement mouseClicked method to make it determine which of ButtonPanel generate the event and call the corresponding to that component setButtonText() method. Is anyone know how to do that?
I know that I can achieve this by including event handling functionality in the ButtonPanel class, but thats not appropriate way for me, cuz I want to keep the class structure as I described above and have only one instance of MouseAdapterMod class for handling all of the ButtonPanels.

A: The MouseEvent#getSource method will return which object has been clicked:
public class MouseAdapterMod extends MouseAdapter {

   // usually better off with mousePressed rather than clicked
   public void mousePressed(MouseEvent e) {
       ButtonPanel btnPanel = (ButtonPanel)e.getSource();
       btnPanel.setButtonText();
   }
}

As the comments note, you're often better off listening for mousePressed or mouseReleased rather than mouseClicked because for mouseClicked to work, the press and release must be from the same point, and if the mouse shifts even a slight amount, the click won't register.
My test program:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;

import javax.swing.*;

public class MainForButtonPanel extends JPanel {
   public MainForButtonPanel() {
      setLayout(new GridLayout(4, 4));

      MouseAdapter myMA = new MouseAdapterMod();

      for (int i = 0; i < 4; i++) {
         for (int j = 0; j < 4; j++) {
            ButtonPanel btnPanel = new ButtonPanel();
            btnPanel.addMouseListener(myMA);
            add(btnPanel);
         }
      }

   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MainForButtonPanel");
      frame.getContentPane().add(new MainForButtonPanel());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class ButtonPanel extends JPanel {

   private static final int TIMER_DELAY = 2000;
   private static final String JUST_CLICKED = "just clicked";
   private static final String WAITING_FOR_CLICK = "waiting for click";
   private static final Color CLICKED_COLOR = Color.pink;
   private JLabel label;

   public ButtonPanel() {
      label = new JLabel(WAITING_FOR_CLICK);
      add(label);
   }

   public void setButtonText() {
      label.setText(JUST_CLICKED);
      setBackground(CLICKED_COLOR);

      new Timer(TIMER_DELAY, new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            label.setText(WAITING_FOR_CLICK);
            setBackground(null);
            ((Timer)ae.getSource()).stop();
         }
      }).start();
   }

}

class MouseAdapterMod extends MouseAdapter {

   // usually better off with mousePressed rather than clicked
   public void mousePressed(MouseEvent e) {
       ButtonPanel btnPanel = (ButtonPanel)e.getSource();
       btnPanel.setButtonText();
   }
}


text:
Q: Curry in scala with parametric types The authors of Functional Programming in Scala give this as the definition of curry in scala:
def curry[A,B,C](f: (A, B) => C): A => (B => C) =
    a => b => f(a, b)

However, if we apply it to a function taking parametric types, e.g.:
def isSorted[A](as: Array[A], ordered:(A,A)=>Boolean) =
    if(as.size < 2)
        true else
           as.zip(as.drop(1)).map(ordered.tupled).reduce(_ && _)

Then the result wants A (in isSorted) to be nothing:
scala> curry(isSorted)
res29: Array[Nothing] => (((Nothing, Nothing) => Boolean) => Boolean) = <function1>

This is obviously not what is desired. Should curry be defined differently, or called differently, or is it not practical to implement curry in Scala?

A: It turns out I can call curry like this:
curry(isSorted[Int])

Which yields:
scala> curry(isSorted[Int])
res41: Array[Int] => (((Int, Int) => Boolean) => Boolean) = <function1>

See https://stackoverflow.com/a/4593509/21640

A: You're running into two separate problems here. The first is that isSorted when it is passed to curry is forced to become monomorphic. The second is that Scala's type inference is failing you here.
This is one of those times where the difference between a function and a method matters in Scala. isSorted is eta-expanded into a function which in turn is a Scala value, not a method. Scala values are always monomorphic, only methods can be polymorphic. For any method of types (A, B) C (this is the syntax for a method type and is different from (A, B) => C which is a function and therefore a value), the default eta-expansion is going to result in the superclass of all functions of that arity, namely (Nothing, Nothing) => Any. This is responsible for all the Nothings you see (you don't have any Anys because isSorted is monomorphic in its return value).
You might imagine despite the monomorphic nature of Scala values though, that you could ideally do something like
def first[A, B](x: A, y: B): A = x
curry(first)(5)(6) // This doesn't compile

This is Scala's local type inference biting you. It works on separate parameter lists from left to right first is the first thing to get a type inferred and as mentioned above, it gets inferred to be (Nothing, Nothing) => Any. This clashes with Ints that follow.
As you've realized, one way of getting around this is annotating your polymorphic method that you pass to curry so that it eta-expands into the correct type. This is almost certainly the way to go.
Another thing you could possibly do (although I'm don't think it'll serve anything except pedagogical purposes) is to curry curry itself and define it as follows:
def curryTwo[A, B, C](x: A)(y: B)(f: (A, B) => C): C = f(x, y)

On the one hand, the below works now because of the left-to-right type inference.
curryTwo(5)(6)(first) // 5

On the other hand, to use curryTwo in the scenarios where you'd want to use curry, you're going to need to need to provide types to Scala's type inference engine anyway.


text:
Q: WPF Xaml Designer is getting Out Of Memory due to Embedded Resources in the ModelVIew So I had this problem for a while, and the only way to go around is to change the build action of the embedded resources to none then build the MV. After that, I build the View and it works like a charm. However If the resources build action is embedded, the View build with no problem, but the designer Xaml throws out of memory exception and does not load. Has anyone experienced these issues? Any real fix, besides changing the build action of the resources to none?

A: Set the "Build Action" to "Content".
Indeed, if you set Build Action to resources, it will be embedded resource in an assembly, but if you set Build Action to content then it will be provided in the resulting file .xap, in this cas you can get you resource like: "/Resources/myResource.xyz".
hope it helps


text:
Q: Batch - edit single line in file I was searching for a batch script which edits a specific and known line in another batch-file.
I found this solution (Stackoverflow: Batch - edit specified line in text file) and it was almost workiing properly. The only problem I had with the script from Endoro is that it deletes the colons at the start of a line which I don't want to edit. Is there a way to avoid this from happening?
Help would be much appreciated! Thanks in advance!
@ECHO OFF &SETLOCAL

:Input
    set /p version=Please Enter Version:

:Replacement
    SET "file=test.bat"
    SET /a Line#ToSearch=4
    SET "Replacement=set jversion = %Version%_x86"

(FOR /f "tokens=1*delims=: " %%a IN ('findstr /n "^" "%file%"') DO (
        SET "Line=%%b"
        IF %%a equ %Line#ToSearch% SET "Line=%Replacement%"
        SETLOCAL ENABLEDELAYEDEXPANSION
        ECHO(!Line!
        ENDLOCAL
    ))>"%file%.new"
TYPE "%file%.new"
MOVE "%file%.new" "%file%"

A: for /F treats subsequent delimiters as one. findstr /N precedes every line with a line number and a colon. So for instance if the third line is :abcd ef, for /F receives 3::abcd ef. After parsing the two tokens, you will get 3 and abcd ef. That is why leading colons disappear.
To overcome this, use sub-string replacement syntax; supposing variable Line contains the entire line including the line number prefix (string 3::abcd ef from above), use SET "Line=!Line:*:=!" to remove everything up to and including the first colon (so the resulting string is :abcd ef).
To get the line number, use another for /F loop with : as delimiter, fetching the first token only.
Here is the fixed script:
@ECHO OFF &SETLOCAL

:Input
    set /p version=Please Enter Version:

:Replacement
    SET "file=test.bat"
    SET /a Line#ToSearch=4
    SET "Replacement=set jversion = %Version%_x86"

(FOR /f "delims=" %%a IN ('findstr /n "^" "%file%"') DO (
        SET "Line=%%a"
        rem // Use a `for /F` loop to extract the line number:
        for /F "delims=:" %%N in ("%%a") do set "LNum=%%N"
        SETLOCAL ENABLEDELAYEDEXPANSION
        rem // Use sub-string replacement to split off
        rem // the preceding line number and one colon:
        SET "Line=!Line:*:=!"
        IF !LNum! equ %Line#ToSearch% SET "Line=%Replacement%"
        ECHO(!Line!
        ENDLOCAL
    ))>"%file%.new"
TYPE "%file%.new"
MOVE "%file%.new" "%file%"


text:
Q: How to create banner in header my site is on WP and I using Hueman theme.
I want to add baner in right side of header. Now Im using header image, which have max. width and I dont know if I should add my banner on this header image or cut width header image and add banner next to it.
I searched a lot and I found a solution:
https://wordpress.org/support/topic/ads-11?replies=6#post-4906945
I have no idea where I can put divs with my banner, this is how looks header.php
<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>

    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php wp_title(''); ?></title>
    <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>">
    <?php wp_head(); ?>

<body <?php body_class(); ?>>

        <?php if ( has_nav_menu('topbar') ): ?>

<?php wp_nav_menu(array('theme_location'=>'topbar','menu_class'=>'nav container-inner group','container'=>'','menu_id' => '','fallback_cb'=> false)); ?>

                                <?php get_search_form(); ?>

        <?php endif; ?>

                <?php if (ot_get_option('header-image') == ''): ?>

                    <?php echo alx_site_title(); ?>
                    <?php if (ot_get_option('site-description') != 'off'): ?>
<?php bloginfo('description'); ?>
<?php endif; ?>

                <?php endif; ?>
                <?php if (ot_get_option('header-image')): ?>
                    <a href="<?php echo home_url('/'); ?>" rel="home">
                        <img class="site-image" src="<?php echo ot_get_option('header-image'); ?>" alt="<?php get_bloginfo('name'); ?>">

                <?php endif; ?>
                <?php if (has_nav_menu('header')): ?>

<?php wp_nav_menu(array('theme_location'=>'header','menu_class'=>'nav container-inner group','container'=>'','menu_id' => '','fallback_cb'=> false)); ?>

                <?php endif; ?>

And this is  my custom.css edited by me to hide this banner from mobile users
/*
Add your custom styles in this file instead of style.css so it
is easier to update the theme. Simply copy an existing style
from style.css to this file, and modify it to your liking.

When you update your theme, backup this file and re-add it after.
*/

/* Global */
.mystyle {}

.ads-header-desktop {
    display: block;
    float: right;
    margin-right: 5px;
    margin-top: -95px;
}

/* hide or display */
.ads-header-desktop { display: block; }

@media only screen and (max-width: 800px) {
.ads-header-desktop { display: none; }
}

/* Tablet - 800px, 768px & 720px */
@media only screen and (min-width: 720px) and (max-width: 800px) {
    .mystyle {}
}

/* Mobile - 480px & 320px */
@media only screen and (max-width: 719px) {
    .mystyle {}
}

/* Mobile - 320px */
@media only screen and (max-width: 479px) {
    .mystyle {}
}

Summa summarum:
This is my site: www.st-mobilny.pl and I want to do something like that: 1drv.ms/1RoUkIV

A: Your best bet is to add it with position absolute:

            <?php if (ot_get_option('header-image') == ''): ?>

In your CSS:
.container-inner {
      position: relative;
 }
.banner {
    position: absolute;
    top: 50px;
    right: 0px;
    z-index: 100;
}

@media screen and (max-width: 768px) { .banner { position: static;} }

Change the top and right to whatever you want. I added a sample media query to show how you could change it, so once you go into mobile, the banner goes above the logo. If you want the banner below the logo, move the div in the html to above the menu.


text:
Q: use existing login table with asp.net core identity service I have an existing live application with its own login table which has all the user info stored. Now we have decided to make a mobile app for part of the application. For that we have decided to use asp.net core identity service. What ever articles/blog/videos I have found they all show how to create a new DB and use identity tables. As for us, we cannot use the new identity tables and need to stick with our own login table as it has been used very much throughout the system and application is heavily dependent on it.
So, my question is, is there any way of using ASP.NET core identity with existing database system?
thanks heaps,
Maulik

A: I do use tables from Identity, however they do not have the same name as the default one. I guess if you customize the fields definitions you could map most of your fields.
Map of an entity property to a column:
b.Property<long>(u => u.Id).HasColumnName("MyIdColumn")

Below you will find extensions that you may use during the init of your builder.
Note the "ToTable" method, which is used to override default table names.
    /// <summary>
    /// Init MS.Identity tables + custom AppUser table
    /// </summary>
    public static void InitIdentity(this ModelBuilder builder, string tablesPrefix = "Identity_")
    {
        builder.InitBaseIdentity(tablesPrefix);
        builder.Entity<IdentityUserRole<long>>(b => b.ToTable($"{tablesPrefix}UserRoles"));
        builder.Entity<AppRole>(b => b.ToTable($"{tablesPrefix}Roles"));
        builder.Entity<IdentityRoleClaim<long>>(b => b.ToTable($"{tablesPrefix}RoleClaims"));

    }

    public static void InitBaseIdentity(this ModelBuilder builder, string tablesPrefix = "Identity_")
    {
        builder.Entity<IdentityUserLogin<long>>(b => b.ToTable($"{tablesPrefix}UserLogins"));
        builder.Entity<IdentityUserClaim<long>>(b => b.ToTable($"{tablesPrefix}UserClaims"));
        builder.Entity<AppUser>(b =>
        {
            b.ToTable($"{tablesPrefix}Users");
            b.Property<long>(u => u.Id).ValueGeneratedNever();
            b.Property<int>(u => u.AccessFailedCount);
            b.Property<string>(u => u.ConcurrencyStamp).IsConcurrencyToken();
            b.Property<string>(u => u.Email).HasAnnotation("MaxLength", 256);
            b.Property<bool>(u => u.EmailConfirmed);
            b.Property<bool>(u => u.LockoutEnabled);
            b.Property<DateTimeOffset?>(u => u.LockoutEnd);
            b.Property<string>(u => u.NormalizedEmail).HasAnnotation("MaxLength", 256);
            b.Property<string>(u => u.NormalizedUserName).HasAnnotation("MaxLength", 256);
            b.Property<string>(u => u.PasswordHash);
            b.Property<string>(u => u.PhoneNumber);
            b.Property<bool>(u => u.PhoneNumberConfirmed);
            b.Property<string>(u => u.SecurityStamp);
            b.Property<bool>(u => u.TwoFactorEnabled);
            b.Property<string>(u => u.UserName).HasAnnotation("MaxLength", 256);
            b.HasKey(u => u.Id);
            b.HasIndex(e => e.NormalizedEmail).HasName("EmailIndex");
            b.HasIndex(e => e.NormalizedUserName).HasName("UserNameIndex").IsUnique();
            b.Property(u => u.About).HasMaxLength(255);
            b.Property(u => u.Birthdate);
            b.Property(e => e.CountryCode).IsRequired().HasColumnType("char(2)");
            b.Property(u => u.Country).HasMaxLength(50);
            b.Property(u => u.FirstName).HasMaxLength(50);
            b.Property(u => u.LastName).HasMaxLength(50);
            b.Property(u => u.Gender);

            b.Property(e => e.CreationDate).HasColumnType("datetime").HasDefaultValueSql("getutcdate()");
            b.Property(e => e.LastUpdate).HasColumnType("datetime").HasDefaultValueSql("getutcdate()");
        });
        builder.Entity<IdentityUserToken<long>>(b =>
        {
            b.Property<long>(u => u.UserId);
            b.Property<string>(u => u.LoginProvider);
            b.Property<string>(u => u.Name);
            b.Property<string>(u => u.Value);
            b.HasKey(nameof(IdentityUserToken<long>.UserId), nameof(IdentityUserToken<long>.LoginProvider), nameof(IdentityUserToken<long>.Name));
            b.ToTable($"{tablesPrefix}UserTokens");
        });
    }

However this does not solve the authentication issue, just the mapping of tables. You will also need to customize the way the authentication is done (password check).
However I am not sure of which gain you will get with identity as it seems you would have duplicated/uncompatible login strategies. You may have to keep one or the other.

A: You can use the database frist way. You have to create your models which will match with the database tables and create your DbContext.
The following page demonstrates an example of how to implement it:
https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db


text:
Q: Expand RAID array I'm pretty new to RAID, so please forgive my silly question.
I have an Ubuntu Server 12.04 x64 installed on a pc having 4 hdds.
During RAID setup I selected RAID10 and (my ignorance) choose 2 active hdds and 2 spare hdds. I'm pretty sure it's not the optimal configuration and probably I should have selected 4 active hdds.
Running cat /proc/mdstat I get
md1 : active raid10 sdb2[1] sdd2[3](S) sdc2[2](S) sda2[0]
      948736 blocks super 1.2 2 near-copies [2/2] [UU]

md0 : active raid10 sdb1[1] sdd1[3](S) sdc1[2](S) sda1[0]
      311619072 blocks super 1.2 2 near-copies [2/2] [UU]

unused devices: <none>

Is there a way I can convert spare disks to active disks?
I tried using mdadm --grow /dev/md1 --raid-devices=4, but got this answer
mdadm: RAID10 can only be changed to RAID0

A: You cannot grow a RAID1+0 (it's not supported by mdadm).
From mdadm manpage:

Grow (or shrink) an array, or otherwise reshape it in some way.
  Currently supported growth options including changing the active size
  of component devices and changing the number of active devices in
  Linear and RAID levels 0/1/4/5/6, changing the RAID level between 0,
  1, 5, and 6, and between 0 and 10, changing the chunk size and layout
  for RAID 0,4,5,6, as well as adding or removing a write-intent bitmap.


text:
Q: Knitr HTML preview fails in RStudio, though render() successfully creates HTML file I'm getting started with rmarkdown and knitr. In the sample document provided by RStudio, I can successfully use render() to generate an HTML file that views fine in Chrome. However, when I click on the knit button, it generates a .markdown file and then returns the following error without rendering the preview:
Error generating HTML preview for ~/path/to/file/report.rmarkdown system error 2 (The system cannot find the file specified)
I think it's getting hung up at the pandoc stage. Is it possible that RStudio is looking for pandoc in the wrong place? Pandoc was already installed at C:\Program Files (x86)\Pandoc\pandoc.exe, but RStudio installed its own instance at C:\Program Files\RStudio\bin\pandoc\pandoc.exe, so maybe it's looking in the wrong place and/or confusing settings from one with the other?
Any help would be greatly appreciated. Thanks!
And just in case, here's the RMarkdown template I'm starting with:
---
title: "Monthly Report"
author: "Kris Shaffer"
date: "February 17, 2017"
output: html_document
---

```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

R version 3.3.2
RStudio 1.0.136
rmarkdown 1.3
knitr 1.15.1
pandoc 1.17.2 (both installations)

A: Turns out it was as simple as a file extension. I changed the filename from report.rmarkdown to report.Rmd. Knit works fine now.


text:
Q: AngularJS Carousel with multiple items and UN-equal width I am using AngularJS to build a carousel with multiple items :

Now,
Each item has different (random width), and also the list of the items is random. (getting it from server).
Ofcourse it needs to be responsive, which means - the width of the item will be fixed - and when you resize it should display more/less items each.
Any recommendations for an AngularJS directive for this scenario?
Appreciate your reading, thanks.

A: I'd recommend: https://github.com/devmark/angular-slick-carousel
The last demo is the one which you are asking for:
https://devmark.github.io/angular-slick-carousel/#/
In your view, would need:
<slick class="slider" settings="slickConfig4" ng-if="slickConfig4Loaded">

</slick>

The configuration in your controller:
 $scope.slickConfig4 = {
  method: {},
  dots: true,
  infinite: true,
  speed: 300,
  slidesToShow: 1,
  centerMode: true,
  variableWidth: true
};

And after loading your data
$scope.slickConfig4Loaded = true;


text:
Q: UDP large packet fragmentation in Python, PyCharm-Windows I am now studying networking and reading the book "Foundations of Python Network Programming". I am following the code of UDP packet fragmentation in the book and found that one of module (IN) is a default package in linux system while I am using PyCharm in windows to learn the process of socket and networking programming.
I want to ask that:

*

*what is the IN package is about

*what other parameter can be used to replace IN.IP_MTU_DISCOVER, IN.IP_PMTUDISC_DO, IN.IP_MTU ?
Here is the code provided by the book:
import IN, argparse, socket

if not hasattr(IN, 'IP_MTU'):
    raise RuntimeError('cannot perform MTU discovery on this combination of operating system and Python distribution')

def send_big_datagram(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.IPPROTO_IP, IN.IP_MTU_DISCOVER, IN.IP_PMTUDISC_DO)
    sock.connect((host,port))
    try:
        sock.send(b'#'*65000)
    except socket.error:
        print('Alas, the datagram did not make it')
        max_mtu = sock.getsockopt(socket.IPPROTO_IP, IN.IP_MTU)
        print('The big datagram was sent!')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Send UDP packet to get MTU')
    parser.add_argument('host', help='the host to which to target the packet')
    parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='UDP port (default 1060)')

    args = parser.parse_args()
    send_big_datagram(args.host, args.p)


text:
Q: What does command "suspend" do on Ubuntu 14? I have made an installation of Ubuntu 14 yesterday. Accidentally, I encountered the suspend command. When I enter it on the command line and press enter, the terminal hangs. Neither can I interrupt it via CTRL+C, nor is a process running with that name that I could kill. Obviously, this is not a script, because both which suspend and whereis suspend return an empty result:
void@wladiwostok ~ $ which suspend
void@wladiwostok ~ $ whereis suspend
suspend:

So I assume that suspend must be some sort of "built-in" command like exit or something. I'm just wondering, out of curiosity, what does it do?
I couldn't find any information on it via online, because most search requests gave me information on how to suspend the computer.

A: suspend is a shell builtin command:
HOw to know that?
Run the command type before any command to tell you what is this command:
$ type suspend

suspend is a shell builtin

To get help about shell builtin commands use help
help suspend
suspend: suspend [-f]
    Suspend shell execution.

    Suspend the execution of this shell until it receives a SIGCONT signal.
    Unless forced, login shells cannot be suspended.

    Options:
      -f    force the suspend, even if the shell is a login shell

    Exit Status:
    Returns success unless job control is not enabled or an error occurs.

To list all builtin commands, just run help command with no options.
help

output is:
job_spec [&]                            history [-c] [-d offset] [n] or hist>
 (( expression ))                        if COMMANDS; then COMMANDS; [ elif C>
 . filename [arguments]                  jobs [-lnprs] [jobspec ...] or jobs >
 :                                       kill [-s sigspec | -n signum | -sigs>
 [ arg... ]                              let arg [arg ...]
 [[ expression ]]                        local [option] name[=value] ...
 alias [-p] [name[=value] ... ]          logout [n]
 bg [job_spec ...]                       mapfile [-n count] [-O origin] [-s c>
 bind [-lpvsPVS] [-m keymap] [-f filen>  popd [-n] [+N | -N]
 break [n]                               printf [-v var] format [arguments]
 builtin [shell-builtin [arg ...]]       pushd [-n] [+N | -N | dir]
 caller [expr]                           pwd [-LP]
 case WORD in [PATTERN [| PATTERN]...)>  read [-ers] [-a array] [-d delim] [->
 cd [-L|[-P [-e]]] [dir]                 readarray [-n count] [-O origin] [-s>
 command [-pVv] command [arg ...]        readonly [-aAf] [name[=value] ...] o>
 compgen [-abcdefgjksuv] [-o option]  >  return [n]
 complete [-abcdefgjksuv] [-pr] [-DE] >  select NAME [in WORDS ... ;] do COMM>
 compopt [-o|+o option] [-DE] [name ..>  set [-abefhkmnptuvxBCHP] [-o option->
 continue [n]                            shift [n]
 coproc [NAME] command [redirections]    shopt [-pqsu] [-o] [optname ...]
 declare [-aAfFgilrtux] [-p] [name[=va>  source filename [arguments]
 dirs [-clpv] [+N] [-N]                  suspend [-f]
 disown [-h] [-ar] [jobspec ...]         test [expr]
 echo [-neE] [arg ...]                   time [-p] pipeline
 enable [-a] [-dnps] [-f filename] [na>  times
 eval [arg ...]                          trap [-lp] [[arg] signal_spec ...]
 exec [-cl] [-a name] [command [argume>  true
 exit [n]                                type [-afptP] name [name ...]
 export [-fn] [name[=value] ...] or ex>  typeset [-aAfFgilrtux] [-p] name[=va>
 false                                   ulimit [-SHacdefilmnpqrstuvx] [limit>
 fc [-e ename] [-lnr] [first] [last] o>  umask [-p] [-S] [mode]
 fg [job_spec]                           unalias [-a] name [name ...]
 for NAME [in WORDS ... ] ; do COMMAND>  unset [-f] [-v] [name ...]
 for (( exp1; exp2; exp3 )); do COMMAN>  until COMMANDS; do COMMANDS; done
 function name { COMMANDS ; } or name >  variables - Names and meanings of so>
 getopts optstring name [arg]            wait [id]
 hash [-lr] [-p pathname] [-dt] [name >  while COMMANDS; do COMMANDS; done
 help [-dms] [pattern ...]               { COMMANDS ; }


text:
Q: Detecting Android Malware using Support Vector Machines (SVM) I'm trying to develop an application capable to detect malicious application for Android platform using Support Vector Machines (SVM).
I can get many system information from "logcat" and "strace" tools but I don't now how to manage to detect real malicious applications.
Does anyone know how to stablish/record normal behavior use of the device using those tools, I mean, get information from the device and set a behaviour pattern.
Best regards

A: You will always have trouble determining malicious application behavior: Kymie M.C. Tan, Roy A. Maxion, ""Why 6?" Defining the Operational Limits of Stide, an Anomaly-Based Intrusion Detector," sp, pp.188, 2002 IEEE Symposium on Security and Privacy, 2002
But if you really want to try, perhaps the starting point is here: "Intrusion Detection Using Sequences of System Calls." S. Hofmeyr, S. Forrest, and A. Somayaji Journal of Computer Security Vol. 6, pp. 151-180 (1998)

A: I wonder, if this is possible ...
How do you want to rate whether a behavior is normal for an application? Do you plan a "learning phase" where everything a certain app does, is recorded (if that's possible without root access in the first place!) and then saved as the "profile" of "normal behavior" of that app?Say you record whatever behavior an application has, e.g. a tool to organize icons on the homescreen. Now say this application also offers the function to call one of your favorite contacts directly, it will need the permission to access your contacts and to make phonecalls. If this feature is hardly used, you would probably not record it during your "learning" period of this app and rate the app as malicious once it tries to make a phone call.And what if an app shows malicious behavior during the "learning phase" where you can't detect it because you haven't determined the "normal behavior" yet?
Sounds like the "normal behavior" has to be saved somewhere to rate an app before you install it and it starts acting weird or performs unwanted actions. But then again: what is anwanted for one user may be perfectly normal for another one ...
I'm interested in whatever fancy solutions people come up with, but I guess this will be a hard one ...

A: what if you use sets of malicious calls in Android first rather than profiling the normal ones.
Also, take note, if you're using unsupervised classification, it does not know what kind of data that it classifies

A: For Windows API usually people take a look on the sequence to determine their sets of actions.
You can find papers/researches done on that too for the Android platform.


text:
Q: Communicating via two bash scripts So I'm supposed to create two bash scripts for the game "guess my number." One script is for Dealer while the other one is for Player.
Each script should wait for the other to generate their response (via a file) before proceeding. So when the Player is started, it first needs to wait for a response from the Dealer. When it detects it, the player gets the Dealer's response and processes it. When the Player makes a guess, the Player communicates that to the Dealer via a file.
While the Player is making a guess, the Dealer is waiting for the Player's response (via a file). When the Dealer detects it, the Dealer gets the response from the file and proceeds.
Below is my bash script for executing "guess my number" in bash script, but this only works if it's one file.
Can someone show me how to split this into two scripts (player_response.bash dealer_response.bash) and make them communicate via files and run simultaneously depended on another to achieve the same result? Much help is appreciated it!

#!/bin/bash
# this program random numbers between 1 and 100.
clear
echo "Hello, "${USER}
date;
guess=1
## Start loop of game here
while true; do
n1=$(( ( RANDOM % 100 ) +1 ))
echo -n "I'm think of a number between 1 and 100. Guess: "

while read n2; do
    if [[ $n2 -eq $n1 ]]; then
        break;
    else
        if [[ $n2 -gt $n1 ]]; then
            echo -n "Sorry, your guess is too high. Guess again: "
        elif [[ $n2 -lt $n1 ]]; then
            echo -n "Sorry, your guess is too low. Guess again: "
        fi
    fi
    guess=$(( $guess + 1 ))
done
echo
echo "Congratulations! You win!"
if [[ $guess == 1 ]]; then
    echo "It took you $guess guess to get $n1."
else
    echo "It took you $guess guesses to get $n1."
fi
echo

read -p "Do you want to try again (y/n)? " choice
case $choice in
    [Yy]* ) guess=1;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no.";;
esac
## End loop of game here
done

A: There are special files for that purpose (i.e. IPC) called named pipes. You can create them using the mkfifo command. The following is a very basic example based on your code. dealer.sh has to be executed first since it is responsible for creating and removing the named pipes.
dealer.sh:
#!/bin/bash

dealerResponse=dealerResponse
playerResponse=playerResponse

mkfifo $dealerResponse
mkfifo $playerResponse

# delete the named pipes on exit
trap "rm $playerResponse $dealerResponse" EXIT

guess=1
n1=$(( ( RANDOM % 100 ) +1 ))

# this blocks until the player has read from the pipe
echo -n "Please make a guess: " > $dealerResponse

while read n2 < $playerResponse; do
    if [[ $n2 -eq $n1 ]]; then
        echo You win! > $dealerResponse
        break
    else
        if [[ $n2 -gt $n1 ]]; then
            echo -n "Sorry, your guess is too high. Guess again: " > $dealerResponse
        elif [[ $n2 -lt $n1 ]]; then
            echo -n "Sorry, your guess is too low. Guess again: " > $dealerResponse
        fi
    fi
    guess=$(( $guess + 1 ))
done

player.sh
#!/bin/bash

dealerResponse=dealerResponse
playerResponse=playerResponse

while true; do
    read line < $dealerResponse
    echo -n "$line "
    read guess
    echo $guess > $playerResponse
done


text:
Q: Should a reference to a null variable throw exception The query below consists of multiple INNER JOIN clauses.
The Student table has a lot of foreign keys which are substituted by names in the query. I am using LEFT OUTER JOIN query below. Please note MarkID in the Students can be null. That means marksGroup.DefaultifEmpty() may return null as well. Therefore if I put only m instead of m != null ? m.MarkName : "-- Not marked --" in the last line, the code IMO should throw an exception when m is null because I am referring to this variable but it didn't. On a example which I build this query on, a compiler thrown exception. Please see the code:
var result = from st in dbContext.Students where st.DepartmentID == 17
             join d in dbContext.Departments on st.DepartmentID equals d.DepartmentID
             join sv in dbContext.SoftwareVersions on st.SoftwareVersionID equals sv.SoftwareVersionID
             join stat in dbContext.Statuses on st.StatusID equals stat.StatusID
             join m in dbContext.Marks on st.MarkID equals m.MarkID into marksGroup
             from m in marksGroup.DefaultIfEmpty()
             select new
             {
                 student = st.StudentName,
                 department = p.DepartmentName,
                 software = sv.SoftwareVersionName,
                 status = st.StatusName,
                 marked = m != null ? m.MarkName : "-- Not marked --"
             };

What am I missing. I am still beginner in terms of C# and LINQ.

A: When you execute a LINQ statement against a SQL backend (I assume you have Entity Framework here) the whole statement is translated into SQL and executed by the database engine.
So this is what the .Net runtime does:

*

*Translate the statement (which is an Expression) into SQL

*Send the SQL to the database through ADO.Net.

*Receive the SQL result set (essentially an array of rows, where a row is itself an array of values).

*Create objects from these rows.

In your case, the objects to be created can safely be defined by the part
select new
{
    student = st.StudentName,
    department = p.DepartmentName,
    software = sv.SoftwareVersionName,
    status = st.StatusName,
    marked = m.MarkName
}

The only thing the .Net runtime is concerned with is to create an instance of an anonymous type and set its properties from one row in the result set. In some rows, the value for marked may be null, so marked will set to null in that particular object. The .Net runtime is not dealing with a MarksGroup object there.
Of course in LINQ to objects this would be totally different. There the null check is absolutely necessary to prevent null object references.


text:
Q: Telegram Bot sub menus in PHP I'm programming a telegram bot in php, and everything is working, except that now I want to add sub menus inside my cases of the switch. For example, the user puts '/insertcolour', then the bots sends a message "Insert your favourite colour" and then how could I read that colour without exiting the primary switch?
I tried with this code inside my case:
  do{
      $update2 = file_get_contents('php://input');
      $update2 = json_decode($update2, TRUE);
    }while($update2['message']['message_id']==$messageId);

But it just gets stuck and stops reading other commands...
Someone knows how to solve this?

A: You can't do like that, but you have an option if your using Switch case
$collors = array("green", "red", "Blue");

switch($text)
{
    case"/start":
        startmsg($msgID,$welcome);
        break;
    case"/insertcolour":
        insertcolour($msgID);
        break;
    default:
            if (in_array($text, $collors))
              {
              //you can add next function here
              }
            break;