text:
Q: derby embedded database does not take path from application.properties I want to make derby persistent but giving path at application.properties in spring batch but the derby is getting initialized as in memory without the recognizing the path .is there anyway i can specify the path in data source in embedded derby
here is the application.properties
spring.batch.initialize-schema=ALWAYS
spring.datasource.url=jdbc:derby:c:/new123/mydb;create=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DerbyTenSevenDialect
spring.jpa.hibernate.ddl-auto=create

here is the configuration class
package com.example.demo;

import java.io.FileNotFoundException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;
import javax.xml.stream.XMLStreamException;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.ItemPreparedStatementSetter;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.ConnectionProperties;
import org.springframework.jdbc.datasource.embedded.DataSourceFactory;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.oxm.xstream.XStreamMarshaller;

import com.example.demo.maintablelogic.XmlMainTable;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.thoughtworks.xstream.mapper.MapperWrapper;

@Configuration
@EnableBatchProcessing
@PropertySource("application.properties")
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private DataSource dataSource;

      @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new
      EmbeddedDatabaseBuilder(); EmbeddedDatabase db =
      builder.setType(EmbeddedDatabaseType.DERBY).addScript("test.sql").build();
      return db;

      }

    @Bean
    public StaxEventItemReader<MessageDto> reader() {
        StaxEventItemReader<MessageDto> reader = new StaxEventItemReader<MessageDto>();
        reader.setResource(new ClassPathResource("ssa_msg_list.xml"));
        reader.setFragmentRootElementName("Message");

        Map<String, String> aliases = new HashMap<String, String>();
        aliases.put("Message", "com.example.demo.MessageDto");
        CustomXStreamMarshaller xStreamMarshaller = new CustomXStreamMarshaller();
        xStreamMarshaller.setAliases(aliases);
        reader.setUnmarshaller(xStreamMarshaller);

        return reader;
    }

    @Bean
    public JdbcBatchItemWriter<MessageDto> writer() {
        JdbcBatchItemWriter<MessageDto> writer = new JdbcBatchItemWriter<MessageDto>();
        writer.setDataSource(dataSource);

        writer.setSql(
                "INSERT INTO ssa_msg_list (Uumid,UumidSuffix,BIC,Service, Status,FormatName,Message_Identifier, Date,Subformat, CreationDate, UETR,MURID) values (?,?,?,?,?,?,?,?,?,?,?,?)");
        writer.setItemPreparedStatementSetter(new UserItemPreparedStmSetter());

        return writer;
    }

    private class UserItemPreparedStmSetter implements ItemPreparedStatementSetter<MessageDto> {

        @Override
        public void setValues(MessageDto user, PreparedStatement ps) throws SQLException {
            XmlMainTable obj = new XmlMainTable();
            try {
                obj.createmaintable(user, ps);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (XMLStreamException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").<MessageDto, MessageDto>chunk(10).reader(reader()).writer(writer())
                .build();
    }

    @Bean
    public Job importUserJob() {
        return jobBuilderFactory.get("importUserJob").incrementer(new RunIdIncrementer()).flow(step1()).end().build();

    }
}

here is the console log
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.0)

2020-11-26 14:42:40.694  INFO 17552 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication using Java 15.0.1 on LAPTOP-RODPBL05 with PID 17552 (C:\Users\shanil\Desktop\demov4\demo\target\classes started by shanil in C:\Users\shanil\Desktop\demov4\demo)
2020-11-26 14:42:40.696  INFO 17552 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2020-11-26 14:42:41.586  INFO 17552 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:derby:memory:testdb;create=true', username='sa'
successsfullly
2020-11-26 14:42:42.525  INFO 17552 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: DERBY
2020-11-26 14:42:42.714  INFO 17552 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2020-11-26 14:42:42.824  INFO 17552 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 2.554 seconds (JVM running for 2.971)
2020-11-26 14:42:42.827  INFO 17552 --- [           main] o.s.b.a.b.JobLauncherApplicationRunner   : Running default command line with: []
2020-11-26 14:42:43.057  INFO 17552 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{run.id=1}]
2020-11-26 14:42:43.178  INFO 17552 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/shanil/.m2/repository/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar) to field java.util.TreeMap.comparator
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Security framework of XStream not initialized, XStream is probably vulnerable.
2020-11-26 14:42:44.070  INFO 17552 --- [           main] o.s.batch.core.step.AbstractStep         : Step: [step1] executed in 891ms
2020-11-26 14:42:44.085  INFO 17552 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED] in 1s1ms
2020-11-26 14:42:44.089  INFO 17552 --- [extShutdownHook] o.s.j.d.e.EmbeddedDatabaseFactory        : Shutting down embedded database: url='jdbc:derby:memory:testdb;create=true'

A: The reason for that is that you have defined the following embedded datasource:
  @Bean
  public DataSource dataSource() {
     EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
     EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.DERBY)
         .addScript("test.sql")
         .build();
     return db;
  }

You either need to remove that bean and let Spring Boot create the datasource for you from application.properties, or define a regular datasource (not an embedded one), something like:
@Bean
public DataSource datasource() {
    org.apache.commons.dbcp2.BasicDataSource dataSource = new org.apache.commons.dbcp2.BasicDataSource();
    // the following properties should be injected from application.properties
    dataSource.setDriverClassName("");
    dataSource.setUrl("url");
    dataSource.setUsername("");
    dataSource.setPassword("");
    return dataSource;
}


text:
Q: C# - convert any filetype to bitmap show in picturebox I want a OpenFileDialog to select any file-types and show the file bits in a bitmap image. I mean the selected file contain some 0/1 bits, I want to show them in black and white image. Any Idea?

A: If the file is a valid image file, you can simply read an image like this:
Image image = Image.FromFile(pathOfImage);

...and then assign it to a picture box.
You will need a reference to System.Drawing.dll and include a using using System.Drawing; at the top of your code.

If the bits in the file, however, represent the black and white pixels, you will need to draw the image yourself.
First create a Bitmap, then create a graphics object from it. You can then draw the pixels on it.
using (var image = new Bitmap(width, height))
using (var g = Graphics.FromImage(image)) {
    // TODO: Draw using the graphics object. (Insert code below)
}

You can use the answer from this answer to read the bits: BinaryReader - Reading a Single " BIT "?
In a double loop you can then iterate through the bits. Assuming that the bits are stored line by line:
using (var stream = new FileStream("file.dat", FileMode.Open)) {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            bool? bit = stream.ReadBit(true);
            if (bit == null) { // No more bits
                return;
            }
            if (bit.Value) {
                g.FillRectangle(Brushes.White, x, y, 1, 1);
            }
        }
    }
}

Finally assign the image to the picture box
pictureBox1.Image = image;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding averages timestamp based on two rows Basically i'm attempting to get an average based on two time stamps inside a database, let's say for example i have a product, I insert it into the database 10 times with an listed_time and a sell_time, I want to group all 10 rows together and find the average between both the listed_time and the sell_time to find on average on how long it took to sell.
EDIT : timestamps are inserted as time() not date()
The code in which i tried and failed to work was
$query = $db->runSQL("SELECT AVG(TIMESTAMPDIFF(SECOND, listed_time, sell_time)) from trade");
while($row = mysql_fetch_assoc($query)) {
    echo $row['AVG(TIMESTAMPDIFF(SECOND, listed_time, sell_time))']."</br>";
}

A: You can try this for that 10 rows:
SELECT AVG(TIMESTAMPDIFF(SECOND, listed_time, sell_time ) ) as za_avg ...

This will give you the average time (for those 10 rows) it took to sell the items


text:
Q: Run command multiple linux server One of my tasks at work is to check the health/status of multiple Linux servers everyday. I'm thinking of a way to automate this task (without having to login to each server everyday). I'm a newbie system admin by the way. Initially, my idea was to setup a cron job that would run scripts and email the output. Unfortunately, it's not possible to send mail from the servers as of the moment.
I was thinking of running the command in parallel, but I don't know how. For example, how can I see output of df -h without logging in to servers one by one.

A: You can run ssh with the -t flag to open a ssh session, run a command and then close the session. But to get this fully automated you should automate the login process to every server so that you don't need to type the password for every server.
So to run df -hon a remote server and then close the session you would run ssh -t root@server.com "df -h". Then you can process that output however you want.
One way of automating this could be to write a bash script that runs this command for every server and process the output to check the health of the server.
For further information about the -t flag or how you can automate the login process for ssh.
https://www.novell.com/coolsolutions/tip/16747.html
https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password

A: You can use ssh tunnels or just simply ssh for this purpose. With ssh tunnel you can redirect the outputs to your machine, or as an alternative, you can run the ssh with the  remote commands on your machine then get the ouput on your machine too.
Please check the following pages for further reading:
http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html
https://www.google.hu/amp/s/www.cyberciti.biz/faq/unix-linux-execute-command-using-ssh/amp/
If you want to avoid manual login, use ssh keys.

A: Create a file /etc/sxx/hosts
populate like so:
[grp_ips]
1.1.1.1
2.2.2.2
3.3.3.3

share ssh key on all machines.
Install sxx from package:
https://github.com/ericcurtin/sxx/releases
Then run command like so:
sxx username@grp_ips "whatever bash command"


text:
Q: Use Django Framework with Website and Stand-alone App I'm planning on writing a web crawler and a web-based front end for it (or, at least, the information it finds). I was wondering if it's possible to use the Django framework to let the web crawler use the same MySQL backend as the website (without making the web crawler a "website" in it's self).

A: Yes, you can use the same database.
Some people use Django on top of a PHP application for its admin functionality, or to build newer features with Django and its ORM.
What I'm trying to say is that if you're putting data from your crawl into the same place that you will let Django store its data, you can access them as long as you create Django models for each table.
However, I don't see why the crawler can't be written within Django itself. I've written some non web based apps (a crawler and an aggregator) in Django and it works quite well.

A: You can use Django ORM outside of an HTTP server.
Basically you need to set DJANGO_SETTINGS_MODULE environment variable. Then you can import and use your django code. Here's an article on stand-alone Django scripts.
Alternatively you can choose to interact with your Django server via custom management commands. This will be a bit more work. But in the end this method allows for a greater decoupling between the crawler and the controller (Django project).


text:
Q: Merge DataFrames With Condition I got two dataframes:
df1 = pd.DataFrame([['A', 'B', 'C'], ['D', 'E', 'F'], ['A', 'B', 'D']],
                   columns=['Key1', 'Key2', 'Key3'])
df2 = pd.DataFrame([['*', '*', '*', 100]], columns=['Key11', 'Key21', 'Key31', 'Value'])

That looks like:

*

*df1:

Key1
Key2
Key3

A
B
C

D
E
F

A
B
D

H
I
J

*

*df2:

Key11
Key21
Key31
Value

A
B
*
25

D
E
F
50

*
*
*
100

*

*Output expected:

Key1
Key2
Key3
Value

A
B
C
25

D
E
F
50

A
B
D
25

H
I
J
1OO

I want to merge the df1 with the df2 with conditions. I want you to search for the keys [A, B, C] but, if you do not find value for those values, to search for the same keys but with the values ['A' or *, 'B' or *, 'C' or *].
I have seen some examples using a query with a merge but dont really make it works. Could be something similar like:
query_line = "(Key1 == Key11 | Key11 == '*') & (Key2 == Key21 | Key21 == '*') & (Key3 == Key31| Key31 == '*')"
out = df1.merge(df2, left_on=['Key1', 'Key2', 'Key3'],
                ,right_on=['Key11', 'Key21', 'Key31'], how='left').query(query_line)

Thank you.


text:
Q: Efficiently update columns based on one of the columns split value So here is my code updating many column values based on a condition of split values of the column 'location'. The code works fine, but as its iterating by row it's not efficient enough. Can anyone help me to make this code work faster please?
for index, row in df.iterrows():
    print index
    location_split =row['location'].split(':')
    after_county=False
    after_province=False
    for l in location_split:

        if l.strip().endswith('ED'):
            df[index, 'electoral_district'] = l

        elif l.strip().startswith('County'):
            df[index, 'county'] = l
            after_county = True

        elif after_province ==True:
            if l.strip()!='Ireland':
                df[index, 'dublin_postal_district'] = l

        elif after_county==True:
            df[index, 'province'] = l.strip()
            after_province = True

A: 'map' was what I needed :)
def fill_county(column):
    res = ''
    location_split = column.split(':')

    for l in location_split:
        if l.strip().startswith('County'):
            res= l.strip()
            break
    return res

df['county'] = map(fill_county, df['location'])


text:
Q: Phaser 3 : Cannot read property '$' of undefined So I was in the middle of game development with Phaser 3 and this error showed up in the console:

Cannot read property 'startSystem' of undefined

Here is my HTML code
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        * {
            padding:0px;
            margin: 0px;
            overflow: hidden;
        }

    </style>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shoot'Em</title>
   <script src="phaser.min.js"></script>
   <script src="game.js"></script>
</head>
<body>
</body>
</html>

And here is my Javascipt/Phaser Code:
var config = {
    type: Phaser.AUTO,
    width: window.innerWidth,
    height:window.innerHeight,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 300 },
            debug: false
        }
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

var game = new Phaser.Game(config);
var platforms
function preload ()
{
    this.load.image('player1', 'Player.png')
    this.load.image('player2', 'Player2.png')
    this.load.image('platform', 'Platform.png')

}

function create ()
{
       ----➤game.physics.startSystem(Phaser.Physics.ARCADE);<---

    //Create Platforms
    platforms.create(400, 568, 'platform').setScale(2).refreshBody();
    platforms.create(600, 400, 'platform').setScale(0.1).refreshBody();
    platforms.create(50, 250, 'platform').setScale(0.1).refreshBody();
    platforms.create(750, 220, 'platform').setScale(0.1).refreshBody();

    //Player 1
    player1 = this.physics.add.sprite(100, -200, 'player1');
    player1.setBounce(0.95);
    player1.setCollideWorldBounds(true);
    player1.body.setGravityY(300);
    this.physics.add.collider(player1, platforms);

    //Player 2
    player2 = this.physics.add.sprite(300, -200, 'player2');
    player2.setBounce(0.95);
    player2.setCollideWorldBounds(true);
    player2.body.setGravityY(300);
    this.physics.add.collider(player2, platforms);

 emitter = game.add.emitter(0, 0, 100);

    emitter.makeParticles('player1');
    emitter.gravity = 0;

    game.input.onDown.add(particleBurst, this);

}

function particleBurst(pointer) {
    emitter.x = pointer.x;
    emitter.y = pointer.y;
    emitter.start(true, 2000, null, 10);
}

Where the stop signs are is where the program stops.
I'm running on a local host.
FYI ALL THE FILES USED IN THE CODE ARE IN THE SAME FOLDER
Any help will be welcomed!

A: There are some errors I found in your example, maybe these steps will help to fix it:

*

*You don't need to call  game.physics.startSystem(Phaser.Physics.ARCADE); at all. Just remove this line.

*Add update function

*platforms.create will fail since platforms are not initialized. Here is example about groups

*game.add will also fail -  you don't need game, use this to access current scene.

There are a lot of examples with Phaser 2 that uses game, but in Phaser 3 you can just access the scene from create and update to add new objects.


text:
Q: Is it possible to have multiple value-like attributes on a single html element? Here's my code:
function Component(props) {

  const [message, setMessage] = useState({
    type: "",
    text: "",
  });

  return (

       <select
        onChange={(ev) => {
          setMessage({ type: **CAN SOMETHING GO HERE???**, text: ev.target.value });
        }}
        required
      >
        <option value="Ask a question" **DIFFERENT ATTRIBUTE TO SET TYPE WITH???**>Question</option>
        <option value="Leave a comment">Comment</option>
        <option value="Voice a concern">Concern</option>
      </select>

  );
}

export default Component;

Is it possible to somehow have another value or something similar in my options so that I can set both the type and text from the same onChange function? I'm not sure how else to do it and I need both a type and a text for a message to work.

A: As @DCR's linked question notes, you can use data- attributes to store your data and read them with the dataset property, like this:
function Component(props) {

  const [message, setMessage] = useState({
    type: "",
    text: "",
  });

  return (

       <select
        onChange={(ev) => {
          let selected = ev.target[ev.target.selectedIndex];
          setMessage({ type: selected.dataset.type, text: ev.target.value });
        }}
        required
      >
        <option value="Ask a question" data-type="negative">Question</option>
        <option value="Leave a comment" data-type="positive">Comment</option>
        <option value="Voice a concern" data-type="negative">Concern</option>
      </select>

  );
}

export default Component;

You need the ev.target[ev.target.selectedIndex] part because ev.target is the <select> element but you need to get the selected <option> element from inside it.
(Since you did not say how you plan to use this type data, I made up an example that it will say whether the feedback is positive or negative. This is just an example.)


text:
Q: Aggregate Root Choice (for all Football/Soccer fans) I have been reading StackOverflow for weeks, but I still could not decide whether my DDD Aggregate Root choice is correct. Long story short -- here are the entities. It is about the football/soccer domain:
League, Team and Match
Each Team can participate in one or more Leagues by playing Matches (i.e. English Premier League, UEFA Champions League). Each team has HomeMatches and AwayMatches in a certain League. Each Match has a League, HomeTeam and AwayTeam.
Each League has many Matches.
I think I need to have two repositories -- LeagueRepository where I can get all the matches for a certain league for a certain period. Through this repository I will automatically update the database when a round of matches has been played and I will record the results accordingly.
I also need a TeamRepository, where I can get all the Matches for a certain team in different leagues for different periods of time. This is for statistical purposes, i.e. give me all Liverpool Home Matches in the English Premier League for the last 10 years. Yeah, you guessed right -- it is about betting chances and odds calculations :)
Long story short -- my Domain is the Football/Soccer World. Those of you who follow the sport know those details and what a League, Team and Match is.
Is it OK to have two separate aggregate roots -- League and Team. I can reach a given match through either one of them. Is this OK with the DDD design?
Or should I introduce a new Entity called Sport and make it the sole aggregate root. Then a Sport will have many Leagues and many Teams.
I am using EF code-first approach and I am trying to identify my Repositories and aggregate roots. If you were designing this database, how would you structure those three entities -- League, Team and Match. Of course we are over-simplifying things here.
All your thoughts and comments will be greatly appreciated.
Thanks in advance.

A: To me, Sport seems like a waste of a concept.  If you don't need to model, soccer, baseball, basketball, etc then I imagine the sport model would be mostly empty and a waste of space.  If you think of your program in terms of teams and leauges, then that is the two repositories I would stick with.  What advantage to a Sport repository do you see other then just having one root?

A: Three white papers that you should read to better understand how you should go about choosing your aggregates: http://dddcommunity.org/library/vernon_2011/


text:
Q: Image file validation in PHP (Size - Type) Im trying to check an image before uploading it. It's working fine with type but when i try to upload a picture of size larger than 2mb it returns the same error of type .. anyone can help !?
<?php
if ($_FILES)

{
    $imageName = date("hms").$_FILES['logo']['name'];

    if (empty($_FILES['logo']['name']))

    {
        echo "<script type='text/javascript'>alert('من فضلك اختار صورة')</script>";
    }

    elseif (!empty($_FILES['logo']['name']))
    {
        if($_FILES['logo']['type'] != 'image/jpeg'
        &&  $_FILES['logo']['type'] != 'image/JPEG'
        &&  $_FILES['logo']['type'] != 'image/jpg'
        &&  $_FILES['logo']['type'] != 'image/JPG'
        &&  $_FILES['logo']['type'] != 'image/gif'
        &&  $_FILES['logo']['type'] != 'image/GIF'
        && $_FILES['logo']['type'] != 'image/png'
        &&  $_FILES['logo']['type'] != 'image/PNG')
            {
                echo "<script type='text/javascript'>alert('يرجى إدخال صورة من امتداد jpeg, jpg, gif, png فقط')</script>";
            }

        elseif(($_FILES['logo']['size'] >2087152))
            {
                echo "<script type='text/javascript'>alert('اقصى حجم للصورة 2 ميجابايت')</script>";
            }

        else
            {
                move_uploaded_file($_FILES['logo']['tmp_name'], "styles/images/$imageName");
                mysql_query("UPDATE components SET path='$imageName' WHERE type='logo'");
                echo "<script type='text/javascript'>alert('تم رفع الصورة بنجاح')</script>";
            }
    }
}
?>

A: if it is your server
Open your php.ini (linux: /etc/php.ini, windows: C:\WINDOWS or C:\WINNT) and change or add the following piece of code:
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Maximum allowed size for uploaded files
upload_max_filesize = 4M

Save your php.ini and restart your server
OR
upload_max_filesize  (in php.ini or .htaccess only, won't work using ini_set())


text:
Q: Android : SharedPreferences not updated My 2 android applications communicate throught a AIDL file :

Application A  <== AIDL ==> Application B (service)

Application A calls methods of Application B (service) that returns some JSON information. However, If user is not logged in application B, null is returned.
(service in application B)
//first : get info
SharedPreferences mPrefs = getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
String userId = mPrefs.getString(Consts.PREFS_USER_ID, "");
String userPass = mPrefs.getString(Consts.PREFS_USER_PASS, "");

//then check is valid (remote server)
if (dao.exist (userId, userPass)){
 return "MY_JSON_INFO" ;
}else{
 return false;
}

If null is returned, "login" activity in Application B is launched from Application A.
(Aplication A)
if(json == null){
  Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
  startActivity(intent);
}

User log in (Application B), data are saved in SharedPreferences (Application B) and activity is closed (back to Application A).
SharedPreferences mPrefs = a.getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
prefsEditor.putString(Consts.PREFS_USER_ID, id);
prefsEditor.putString(Consts.PREFS_USER_PASS, pass);
prefsEditor.commit();

When re-trying to call methods of the Application B, login information saved few seconds ago are not available and null is returned.
I have tried without success with prefsEditor.apply() .
If I restart application B, login data will be loaded....
Please let me know if further information are needed.
Thank you

A: After a long struggle, I have at last managed to get my updated preferences.
When calling getSharedPreferences,  I use Context.MODE_MULTI_PROCESS flag.
MODE_MULTI_PROCESS
Thank you.

A: By reading your comment i can give you a quick solution:
The easier way is to simply terminate your activity (A) before calling the login activity inside your service.
if(json == null){
  Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
  startActivity(intent);
  this.finish();
}

So that, when you fill in the login form and call back the activity A it will read the new shared preferences!

A: Since you need to access the shared preference of other application.
You should try :: Android: Retrieving shared preferences of other application


text:
Q: r ggplot2 stacked bar not plotting all levels I am having a problem with ggplot2 not plotting a variable (Water) on a stacked bar chart.
Here is the data:
data <- structure(list(PARK_NON = structure(c(3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("apis", "indu", "miss",
"non_apis", "non_indu", "non_miss", "non_piro", "non_sacn", "non_slbe",
"piro", "sacn", "slbe"), class = "factor"), variable = structure(c(15L,
9L, 3L, 10L, 12L, 7L, 6L, 11L, 8L, 2L, 5L, 1L, 14L, 4L, 13L,
15L, 10L, 12L, 6L, 11L, 7L, 9L, 5L, 1L, 8L, 2L, 4L, 13L, 3L,
14L), .Label = c("Agriculture", "Barren land", "Developed - High intensity",
"Developed - Medium intensity", "Developed - Low intensity",
"Developed - Open space", "Evergreen forest", "Deciduous forest",
"Mixed forest", "Herbaceous", "Pasture", "Shrub", "Woody wetland",
"Herbaceous wetland", "Water"), class = "factor"), perc_veg = c(26.0239390821837,
0.0293350851750396, 6.90366110126389, 1.21719944965728, 1.57541802496374,
0.394990724328702, 5.82528684342088, 4.05485247757519, 16.4441745065715,
1.31842615202185, 9.09594225533093, 4.04411005201813, 4.73410430895216,
7.12470716561102, 11.213852770926, 7.66680361881418, 2.1247481894809,
1.30789300876845, 10.5308007720824, 12.723205663498, 0.713438751370985,
0.0478161985127231, 16.4578439049856, 11.5045071302907, 13.2759304844946,
0.0640865818499777, 10.2423233639193, 0.795200353968627, 5.43302045035016,
7.11238152761342), in_out = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Inside", "Outside"
), class = "factor")), class = "data.frame", row.names = c(NA,
-30L), .Names = c("PARK_NON", "variable", "perc_veg", "in_out"
))

I want data$variable stacked in a particular order, so I define the factor order...
data$variable <- factor(data$variable,
                          levels=c('Agriculture','Barren land','Developed - High intensity','Developed - Medium intensity','Developed - Low intensity',
                                   'Developed - Open space','Evergreen forest','Deciduous forest','Mixed forest','Herbaceous','Pasture','Shrub',
                                   'Woody wetland','Herbaceous wetland','Water'))

Then to plot...
library (ggplot2)
#colors to be used for NLCD classes
wa <- rgb(71/255,107/255,161/255,1)   #water
do <- rgb(222/255,202/255,202/255,1)  #developed-open
dl <- rgb(217/255,148/255,130/255,1)  #developed-low density
dm <- rgb(238/255,0/255,0/255,1)      #developed-medium density
dh <- rgb(171/255,0/255,0/255,1)      #developed-high density
bl <- rgb(179/255,174/255,163/255,1)  #barren land
df <- rgb(104/255,171/255,9/255,1)    #deciduous forest
ef <- rgb(28/255,99/255,48/255,1)     #evergreen forest
mf <- rgb(181/255,202/255,143/255,1)  #mixed forest
sh <- rgb(204/255,186/255,125/255,1)  #shrub/scrub
gr <- rgb(227/255,227/255,194/255,1)  #grassland/herbaceous
pa <- rgb(220/255,217/255,61/255,1)   #pasture/hay
ag <- rgb(171/255,112/255,40/255,1)   #cultivated crops
ww <- rgb(186/255,217/255,235/255,1)  #woody wetlands
hw <- rgb(112/255,163/255,186/255,1)  #emergent/herbaceous wetlands
#map colors defined above to particular factors (levels) w/in the data, then use this vector for the color fill
nlcd.colors <- c("Water"=wa,"Developed - Open space"=do,"Developed - Low intensity"=dl,"Developed - Medium intensity"=dm,"Developed - High intensity"=dh,
       "Barren land"=bl,"Deciduous forest"=df,"Evergreen forest"=ef,"Mixed forest"=mf,"Shrub"=sh,"Herbaceous"=gr,"Pasture"=pa,"Agriculture"=ag,
       "Woody wetland"=ww,"Herbaceous wetland"=hw)

p <- ggplot () + geom_bar(data=data,aes(x=in_out,y=perc_veg,fill=variable,order=variable,width=0.6),stat='identity')
p <- p + scale_fill_manual("Vegetation type",values=nlcd.colors,
                           labels=c('Agriculture','Barren land','Developed - High intensity','Developed - Medium intensity','Developed - Low intensity',
                                    'Developed - Open space','Evergreen forest','Deciduous forest','Mixed forest','Herbaceous','Pasture','Shrub',
                                    'Woody wetland','Herbaceous wetland','Water'))
p <- p + guides(fill=guide_legend(reverse=TRUE))
p <- p + ylab('Percent of location')
p <- p + theme(axis.text=element_text(color="black"), axis.ticks.x = element_blank(), axis.title.x = element_blank())
p <- p + scale_y_continuous(expand=c(0,0),limits=c(0,100)) #to remove buffer on either side of 0 and 100

Producing this graph....

Which has 'Water' on the legend, but not in the two bars.
Any ideas?
Thanks
-cherrytree

A: So when you included:
scale_y_continuous(expand=c(0,0),limits=c(0,100))

ggplot doesn't quite have room to fit that last bar. This seems debatable to me, though. Setting expand to 0 and setting the limits seems like a reasonable thing to do. If you just do:
scale_y_continuous(expand=c(0,0))

you remove the padding without the truncation. That seems like an unintended result to me. I haven't pored over the source code yet, but I think setting limits is being a little too strict at the boundary.

A: It is your last call to
p <- p + scale_y_continuous(expand=c(0,0),limits=c(0,100))

This is actually working on the original data rather than merely clipping the graph at 0 and 100
If you still want to remove the whitespace, maybe try
p<-p+coord_cartesian(ylim=c(0,100)).

This will simply clip the graph at the y limits provided
Also, as an aside, it's always helpful to step back through your code. I find this particularly helpful in ggplot. Strip it back to the bare minimum code needed to get a similar chart (i.e. without colour formatting and label changes etc). You'll then quickly find the offending function call. Then it is easier to target a question.


text:
Q: ant multiple target to execute I have few target that I need to execute.  I create a target naming all of them but I think it's not the way to do it ? Here is the target run that call all other target :
<target name="test.all" depends="build
echolaunching agent /echo
antcall target="RunJtfTests" /
antcall target="launchOpenAgent" /
antcall target="run.test" //target
target name="run.test" depends="build, launchOpenAgent, runJtfTests"
echo Launching test/echo
echo message="${toString:iControlSilk4J.classpath}" /
  <java classname="com.miranda.icontrol.silk4j.installation.AdministrationCtrl"
classpath><fileset dir="${lib.dir}"
include name="**/*.jar" />
/fileset
pathelement path="${iControlSilk4J.classpath}" /
pathelement location="${jarPath}/Admin.jar" /
/classpath
  </java>
</target>

It doesn't run and I do it to get the report and I get nothing ?  What is wrong ? From what I read, antcall is like a goto loop which is not good.  I want to call tests instead.
-> Here are all the tests I want to execute :

*

*init

*clean

*AdministrationCtrl.Rollback

*AdministrationCtrl.LatestInstallation

*AdministrationCtrl.BackupiControl,

*AdministrationCtrl.ChangeService

*AdministrationCtrl.DefaultSetting

*AdministrationCtrl.InitFailOver

*AdministrationCtrl.RunDensite2Service

*AdministrationCtrl.RunDensiteService

*AdministrationCtrl.RunGSMService

*AdministrationCtrl.RunLoudnessAnalyzerService

*AdministrationCtrl.RunLoudnessLoggerService

*AdministrationCtrl.RunRouterManagerService

*AdministrationCtrl.RunttyR0Service

*AdministrationCtrl.RunVirtualService

*AdministrationCtrl.RestoreBkp

but this can be more general (regarding tests I will add in Silk4J).  Is there a way to be more generic ?

A: Repeat after me:

Ant is not a programming language. It's a dependency matrix language.

This is an important distinction. You don't tell Ant what to execute. You tell Ant what you need, and Ant will figure out what to do.
I can tell you're having problems understanding Ant with all of those <antcall/>. That is a no-no because it could make you execute tasks more than once. Your build file also makes no sense.
Use the target's dependency parameter. For example, here's a skeleton build.xml file:
<project>
    <target name="clean"/>

    <target name="prepare"/>

    <target name="compile"
        depends="prepare"/>

    <target name="package"
         depends="compile"/>

    <target name="test-compile
         depends="compile"/>

    <target name="test"
         depends="test-compile"/>

    <target name="deploy"
         depends="package"/>

    <target name="post-test-results"
         depends="test"/>

    <target name="all"
         depends="clean,post-test-results,deploy"/>
</project>

When I want to run my target all, I mainly mean I want to do a clean build, post my test results, and deploy the build. This is true with Makefiles too. I don't list all of my tasks. Why do I care if I do my prep work for compilation? It's not my concern.
So I call, all, and that will call clean, post-test-results, and deploy. I have no idea what Ant will do beyond calling these three targets.
Wait... What do I need to do in order to post my test results? Well, I may need to run my tests. Therefore, I have a dependency to test for my post-test-results target.  But, in order to run my tests, I may have to compile them. So, there's a dependency to test-compile on my test target.
In order to compile my tests, I have dependencies on the regular Java code. So, test-compile will depend upon compile. In order to compile, I have to prepare. Maybe that's building the necessary structure, or downloading the required jars. That's called before compile. Now, I can deploy. However, before I can deploy, I need to package my deployment. So, deploy depends upon package.
Package itself depends upon compile, but so did my compile-test. Since I've already called compile, my package target doesn't have to do that. All it has to do is package up the already compiled class files.
Thus, I'll probably execute the following targets in this order:

*

*clean

*prepare

*compile

*test-compile

*post-test-results

*package

*deploy

My all target does hit all of my other targets, but I didn't have to list them all as dependencies or force them to build via <antcall/>s.
It looks like you need to learn about Ant and how it works. Your sample Ant file is simply not valid. Ant uses an XML style structure. All tasks are XML style entities.
Fortunately, there are a lot of good books on Ant. I would recommend Manning's Ant in Action as a good starting point.
One of the things you will find out is that you can specify batches of junit tests in a single <junit> task. This can be done via one or more <batchtest> sub-entities on the <junit> task. The <batchtest> will run all classifies that match a particular criteria. You can also use the <test> sub-entity on the <junit> task. The <test> sub-entity allows you to specify individual classfiles to run. Many times, these classfiles may simply call a specified set of other Junit classifies. This way, the developer can specify what tests to run and what tests to skip.
You can control what tests to run or not run by using properties and not by creating dozens of testing tasks. This allows you to specify sets of tests without having to spawn multiple JUnit processes.


text:
Q: Uniform Grid inside a ListBox I'm in the development of a program that requires its own custom file manager/explorer.
It's pretty typical: I have a user-control (named FileItem) and it includes an Image (thumbnail) and a Label (file name).
The problem I'm experiencing is with the layout; I need it in a grid layout (so I'm using Uniform Grid which nails it), exactly like Windows Explorer when you're on icon view:

I also need to be able to select file, or multiple files etc. which ListBox does perfectly.
The problem is that I can't use both.
So I tried to insert a Uniform Grid inside a ListBox. The layout was great, but I couldn't select the files (as if the ListBox wasn't there).
A quick Google search suggested to just use a ListView, but it doesn't do a good job since it has fixed columns and rows (and at the program I'm working on the size will change).
So how can I exactly achieve both of the functionality of ListBox and Uniform Grid?
Edit (Important):
If you also need this look and want an answer I actually recommend WrapPanel and not Uniform Grid. It will automatically allow you to dynamically change the number of the rows according to the content.

A: To set the ListBox's ItemsPanel to a UniformGrid you can do this:
<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid IsItemsHost="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem Content="Grid Item 1" />
    <ListBoxItem Content="Grid Item 2" />
    <ListBoxItem Content="Grid Item 3" />
    <ListBoxItem Content="Grid Item 4" />
    <ListBoxItem Content="Grid Item 5" />
    <ListBoxItem Content="Grid Item 6" />
    <ListBoxItem Content="Grid Item 7" />
    <ListBoxItem Content="Grid Item 8" />
    <ListBoxItem Content="Grid Item 9" />
    <ListBoxItem Content="Grid Item 10" />
</ListBox>

You shouldn't have selection issues with this and the items will be displayed as you wanted.


text:
Q: Python init class with __enter__ I have four variables email, first_name, last_name, password in my User class and I'm trying to init my class using this method:
with User(email, first_name, last_name, password) as user:

and here is the __enter__ method:
def __enter__(self):
    return

now when I debug the return statement in the __enter__ method I can see that the variables were sent successfully but when I debug the user instance I get None

Any help is appreciated.

A: with User(email, first_name, last_name, password) as user: is (roughly) equivalent to
u = User(email, first_name, last_name, password)
user = u.__enter__()

Since __enter__ returns None, that's what user is bound to.
If you want user to be the instance u, __enter__ needs to return self.
def __enter__(self):
    return self


text:
Q: Wubi on Windows 10 ..yes I managed that. It works just by some magic I suppose.
I would like to try something else now: multiple wubi installation side by side..
By this I would have multiple entries in BCD. But I need to know how the wubildr and wubildr.mbr are generated. I seem to have found the source for wubildr from grub-mkimage in lupin-support but cannot find where wubildr.mbr is generated. Can someone provide insight to that?
In particular, the wubildr that is shipped when Ubuntu is installed via the CD and not the pre-packaged disk image.
[edit]
To clarify, I think I would have to modify wubildr.mbr to search for a different wubildr.

A:
To clarify, I think I would have to modify wubildr.mbr to search for a
  different wubildr.

It is easy to create a wubildr.mbr which searches for a different wubildr. see Makefile of Wubi
/usr/lib/grub/i386-pc/grub-ntldr-img --grub2 --boot-file=wubildr -o build/winboot/wubildr.mbr

/usr/lib/grub/i386-pc/grub-ntldr-img is part of the package grub-pc-bin and it is really easy to change parameters. e.g.:
/usr/lib/grub/i386-pc/grub-ntldr-img --grub2 --boot-file=xxxxldr -o xxxxldr.mbr

This creates a xxxxldr.mbr which searches for xxxxldr .
But note: xxxxldr.mbr works in legacy BIOS mode (non-UEFI mode) only and you need a xxxxldr with different configuration files. If you just copy wubildr to xxxxldr it loads the same Wubi installation.

Wubi on Windows 10

If you intend to use Windows 10 in UEFI mode, better to use a customized GRUB2 loader for UEFI. see Makefile of a Wubi for UEFI
grub-mkimage -O x86_64-efi -c build/winboot/wubildr-bootstrap.cfg -m build/winboot/wubildr.tar -o build/winboot/EFI/grubx64.efi \
        loadenv part_msdos part_gpt fat ntfs ext2 ntfscomp iso9660 loopback search linux linuxefi boot minicmd cat cpuid chain halt help ls reboot \
        echo test configfile gzio normal sleep memdisk tar font gfxterm gettext true efi_gop efi_uga video_bochs video_cirrus probe efifwsetup \
        all_video gfxterm_background png gfxmenu


text:
Q: Custom MS-DOS / FreeDOS Goal : Build a custom DOS to boot into. To automate tasks like formating a drive, or doing recovery.
I've been using Grub4DOS to boot into these images.
So far I've looking into taking a windows repair disk ISO and extracting. I can't seem to find the autoexec.bat in the disk. I really don't know where to look for the startup configuration file to change or how to add an autoexec.bat.
I've tried MS-DOS 6.22. But it lacks the diskpart tool I require. I've tried extracting the images and adding it. Then I got a boot failed. I assume that after i added it. All the files when to lower case names and I assume that the OS is case sensitive.
Then I've looking into using FreeDOS. But I don't know how it works at all. Partially because I can't seem to grasp the help/wiki's information. I looked into getting a bearbones release with just the kernel and I think it's the config.sys file. But I don't have any idea on how the packaging system works to incorporate diskpart into it.
So really I'm in general looking for a small bootable DOS to where I can incorporate diskpart and setup an autoexec.bat for the actual function to carry out and to boot into.
This is just for personal use also.

A: You'll need a Windows 9x installation, a floppy, and a XP or later installation. (have a floppy drive on both computers):
9X PC: My Computer > Put in a Blank Floppy > Right Click Floppy Drive > Format > Check 'Copy System Files' > Format it
XP or later PC: My Computer > Put in the formatted 9X floppy > Open the floppy > Copy those files wherever you want your Custom-DOS to boot in > Open Notepad > write an autoexec, should start with:
@echo off
cls
echo (boot message here)
and now, after you are done, save it as "autoexec.bat" in your bootable device.
So now, choose a language to write your commands in.
I prefer Batch, so i use Advanced BAT to EXE Converter,
and if you use that application, make sure to compile it as an "MS-DOS 6.22" application,
and save it to the bootable device.
This is the best I can do.


text:
Q: debug a gridview object like you can with a datatable Is it possible to debug a gridview object like you can with a datatable. By this I mean adding a watch to the object then see the data visually?
Thnaks for the help.

A: Yes you can debug your GridView, you use RowDataBound Event
  <asp:gridview id="GridView1"
    datasourceid="...."
    autogeneratecolumns="true"
    onrowdatabound="GridView1_RowDataBound"
    runat="server">
  </asp:gridview>

void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        Console.Write(e.Row.Cells[1].Text);
        .....
    }

  }

Link : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx


text:
Q: Django format DecimalField in query / annotation Is it possible to format a DecimalField in an annotation similar to intcomma template tag?
class Product(models.Model):
    plu = models.CharField(max_length=8)
    description = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=9, decimal_places=2, default=D('0'))

For example if instance.price = Decimal('1000') the annotated attribute would return the number formatted with a comma separator (1,000.00)
I'm creating PDF reports in ReportLab and table data is a list of lists. If the queryset could return the comma separated number there would be speed improvements rather than having to iterate over each object in the queryset to apply the formatting.
from django.contrib.humanize.templatetags.humanize import intcomma

products = Product.objects.all()
table_data = [['PLU', 'Description', 'Price']]
for product in products:
    table_data.append([product.plu, product.description, intcomma(product.price)])

Could be simplified to
table_data = [['PLU', 'Description', 'Price']] + list(
    Product.objects.all()
    .annotate(comma_sep_price=...)
    .values_list('plu', 'descripton', 'comma_sep_price')
)

A: I was able to solve this using the PostgreSQL data type formatting function TO_CHAR.
Using an ExpressionWrapper:
from django.db.models import CharField, ExpressionWrapper, Func, F, Value

data = (
    Product.objects
    .annotate(
        formatted_price=ExpressionWrapper(
            Func(F('price'), Value('FM999,999,999.00'), function='TO_CHAR'),
            output_field=CharField()
        )
    )
    .values_list('plu', 'description', 'formatted_price')
)

Or as a reusable custom query expression:
class CommaSeparated(Func):
    function = 'TO_CHAR'
    template = "%(function)s(%(expressions)s, 'FM999,999,999.00')"

data = (
    Product.objects
    .annotate(formatted_price=CommaSeparated(F('price'), output_field=CharField()))
    .values('plu', 'description', 'formatted_price')
)


text:
Q: After installation of NGenuity keyboard software the media keys do not work anymore I bought a new keyboard HyperX Alloy FPS RGB and my media keys don't work. But always one after the other. I connected the keyboard to my freshly installed Windows. On a USB port which sits directly on the motherboard. Everything works fine, even the media keys. I can do louder, quieter and so on. But as soon as I install the software for my keyboard the media keys don't work anymore. When I then stop and close the suite (latest version of HyperX NGenuity) which manages my keyboard, unplug my keyboard and reinsert it. Everything works again! If I start NGenuity again, the media keys are deactivated again as soon as the software is loaded.

What I have tried so far:

*

*i don't have the Google Music extension in Google Chrome

*human interface is active and set to automatic

*i have the latest software from NGenuity as well as the drivers for my keyboard in the Device Manager

*my Bios has no entry for the function of the FN key (Media keys with or without FN key)

*i have completely reinstalled Windows 10, including deleting my data

*keyboard reset to factory setting by FN + ESC until keyboard flashes

I have the feeling that windows is messing something with the drivers. I'm not so windows affine that I could locate the problem. I hope someone has an idea.


text:
Q: How can I use Japanese language characters in variable naming? I'm trying to use Japanese words in variable naming but C language doesn't appear to be work this way. Is there any way to fix this?
See my code below.
#include <stdio.h>

struct 忍び/* Shinobi */
{
    char 名前/* Namae */[50];
    char 血液型/* Ketsuekigata */[3];
    char 性別/* Seibetsu */[10];
    char 星占い/* Hoshi uranai*/[10];
    int 年齢/* Nenrei */;
};

int main(void)
{
    struct 忍び Uchiha_Itachi;
    Uchiha_Itachi.年齢 = 21;
    printf("the age of itachi > %d", Uchiha_Itachi.年齢);
}

A:
C language doesn't appear to be work this way. Is there any way to fix this?

Support for such characters is implementation defined.  Many compilers will not support this, a few might.

An identifier may contain non-digits (a-z, A-Z, _), digits (0-9), universal-character-name or other implementation-defined characters.  C17 6.4.2 1

Alternative
Since C99, code could use universal-character-name via \Unnnnnnnn or \unnnn - a not so pretty possibility.
An application would be to convert source code struct 忍び (that worked on one compiler) to struct \u5fcd\u3073 for other compilers.
https://www.branah.com/unicode-converter
忍び --> \u5fcd\u3073
#include <stdio.h>

struct \u5fcd\u3073/* Shinobi */ {
    char \u540d\u524d /* Namae */[50];
    char \u8840\u6db2\u578b /* Ketsuekigata */[3];
    char \u6027\u5225/* Seibetsu */[10];
    char \u661f\u5360\u3044/* Hoshi uranai*/[10];
    int \u5e74\u9f62/* Nenrei */;
};

int main(void) {
    struct \u5fcd\u3073 Uchiha_Itachi;
    Uchiha_Itachi.\u5e74\u9f62 = 21;
    printf("the age of itachi > %d", Uchiha_Itachi.\u5e74\u9f62);
}

Note: using defines like below, are not specified to work either.  Support for such is implementation defined.
// not certain to work
#define 忍び \u5fcd\u3073

If a strong need exists to "any way to fix this?", write your source code as a .wheldrake file and translate it to standard .c one.

Soapbox
One character I would like to use: ≠, the not_equal sign.

A: It's not possible, at least there's no portable way (some compilers may allow it nonetheless, while others won't). According to this:

An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).

It might however work using macros. To try that, add this line before you first use "忍び":
#define 忍び Shinobi

However, I wouldn't recommend it. It also isn't portable and some compilers might allow certain symbols while others won't.


text:
Q: jQuery: Plugin Validation, how do I validate a dozen or so different fields? I'm using this: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension
I'm trying to alert the user to only upload PNGs, Jpgs, JPEGS and PDFs. On the server end if they do attempt, it will not work. On the user end I want to alert them what they are doing is false. Try a different file type. Maybe even prevent them from submitting the form.
How do I get this to work with 1 dozen file fields?
code:
$("#fileForm").validate({
          rules: {
            yourFileFieldNameHere: {
              required: false,
              accept: "png,jpg,jpeg,pdf"
            }
          }
        });

I'm assuming the yourFileFieldNameHere is the "name=" of the input field as thats the only parameter that works. I've tried to use the ID name.
Any suggestions?

A: Revised the answer, i missed the info about a dozen fields. Try adding a rule for the dozen fields like this:
    $("#fileForm").validate({
              rules: {
                //any other rules go here
              }
            });

$('.your-dozen-fields-selector').rules("add", {
 required: false,
 accept: "png,jpg,jpeg,pdf"
});


text:
Q: Setting automationIDs for dataitems in a WPF Grid for automation with UI Automation Framework I've got an application that's written in C# using .NET Framework 3.5 and want to automate the UI using Microsoft UI Automation Framework. I'm not allowed to show everything here, because it's a software from my company.
In this application I'm generating a grid that displays my data items.
I've tried to set the automationIDs for every data item in the grid through XAML, but the problem is, that I can't see the dataitems there. They are dynamically generated during runtime of my application. Only the grid that contains the data items is defined in the XAML. I will post a snippet of my XAML below.
I've also tried to set the automationIDs through the Code of the program, but I only managed to get the AutomationElement of every data item. There I'm stuck. I don't know how to set the automationIds for every AutomationElement there.
To sum it up I am either looking for:

*

*Setting the automationID for data items in a WPF grid through XAML

*Setting the automationID for data item AutomationElement through Code

Screenshot of my Inspect Tool:
Inspect Tool
Snippet of my XAML Code:
    <ListView IsEnabled="{Binding TestSelectorEnabled}" x:Name="ListView1" ItemsSource="{Binding TestsViewModel.TestsDataTable}" SelectedValue="{Binding TestsViewModel.SelectedTest}" SelectedValuePath="TestName" Height="180" View="{Binding TestsViewModel.GridView}"  TabIndex="0" MinWidth="1" Focusable="False"/>
            <Grid  Visibility="Collapsed" IsSharedSizeScope="False">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="200"></ColumnDefinition>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="40"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="25"></RowDefinition>
                    <RowDefinition Height="20"></RowDefinition>
                </Grid.RowDefinitions>
            </Grid>

A: Try to specify ItemTemplate explicitly, it will let you set ids.
It should be an automation API to iterate though ListView children as well.

A: Thanks @Viktor Syromiatnikov this got me on the right track. I now managed to set a static automationId for every ListViewItem.
Does anyone know how I can set the automationID dynamic for every ListViewItem so it looks like dataitem1, dataitem2, dataitem3 for every new ListViewItem?
My XAML looks like this now:
<ListView IsEnabled="{Binding TestSelectorEnabled}" x:Name="ListView1" ItemsSource="{Binding TestsViewModel.TestsDataTable}" SelectedValue="{Binding TestsViewModel.SelectedTest}" SelectedValuePath="TestName" Height="180" View="{Binding TestsViewModel.GridView}"  TabIndex="0" MinWidth="1" Focusable="False">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem">
                        <Setter Property="AutomationProperties.AutomationId" Value="dataitem"/>
                    </Style>
                </ListView.ItemContainerStyle>
            </ListView>


text:
Q: How many integer solutions there are for this equation $\sum_{k=1}^r |x_k| =n$? Using a proper generating function I need to evaluate the number of integer solutions to this equation :
$\sum_{k=1}^r |x_k| =n$
Can I assume that
$\sum_{k=1}^r x_k =n$
and
$\sum_{k=1}^r -x_k =n$
has the same amount of integer solutions and that the answer is actually $2*p$
for p equals the number of integer solutions to the following equation $\sum_{k=1}^r x_k =n$ ?

A: For $r=1$ the generating function for the number of solutions is
$$1+2x+2x^2+\dots=\frac{1+x}{1-x}$$
as every value of $n\ne0$ has two possible solutions namely $x_1=\pm n$ with the same absolute values and $n=0$ has only one solution namely $x_1=0$. Then, for $r\ge1$, it follows that the generating function for the number of solutions is
$$(1+2x+2x^2+\dots)^r=\left(\frac{1+x}{1-x}\right)^r$$
as each tuple of absolute values $(|x_1|,\dots,|x_r|)$ which produces a valid solution corresponds to a number of tuples of $r$ integers $(x_1,\dots,x_r)$ given by multiplying the coefficients of the monomials in each bracket with the powers $|x_1|,\dots,|x_r|$ respectively.

A: If $r=2$, then $(0,n)$ for natural numbers becomes two solutions $(0,\pm n)$, but $(m,n-m)$ becomes four solutions $(\pm m,\pm(n-m))$


text:
Q: IE break with problem delegate.iterator.return Webpack create bundle and in console I saw error:

Expected identifier

if (delegate.iterator.return) {...}

Why my bundle is different for Chrome and IE11 ?And this part of code is absent for Chrome bundle?
I have file .browserlistrc
# Browsers that we support

IE 11
> 1%

I found this similar question but it didn't helped for me.
Error in IE11 caused by babel polyfill - delegate.iterator.return


text:
Q: Webpack - How to bundle/require all files of a folder (subfolder) I am trying to see if there is a shorter way of running webpack bundles, and also why my loaders do not work.
Here is my code:
module.exports = {
context: path.join(__dirname, 'dist'),
entry: ['./ES6bundle.js', './jQuery.js'],
output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'dist')
}
};
// module: {
//     loaders: [{
//         test: /\.js?$/,
//         exclude: /node_modules/,
//         loader: 'babel-loader',
//         query: {
//             presets: ['env']
//         }
//     }]
// };

The module.exports works but when I run the loaders I get errors.
My other question is about consolidating multiple entries into one file.
The project I am working on has many JS files, and I was wondering if there was a shortcut for multiple entries. Instead of typing out multiple entries' filenames, can I grab all JS files in the same folder or have a JS file to require them all?
Let me know if this makes sense or not. I am relatively new to programming. Thanks!

A: Regarding the second part of your question:

can I grab all JS files in the same folder or have a JS file to
  require them all

You can have one entry file and in there you do:
module.exports = {
    context: path.join(__dirname, 'dist'),
    entry: ['./jQuery.js', './allJsFilesOfFolder.js'],

allJsFilesOfFolder.js:
require.context("../scripts/", true, /\.js$/);

This will bundle all scripts inside scripts and all its subfolders.
You need to install @types/webpack-env to have context at your hand.
Specify false if you want to bundle only the scripts in the scripts folder.
You can do the same with other resources like images, you only have to adapt the regex

A: Copy @Legends comment as answer here.

have no experience with vue files, but as I said you can bundle not only js files, but also image files, for example the regex for image files would be: /.(png|ico|svg|jpg|gif)$/.


text:
Q: How to use my index.htm in this location? I need http://suporte.ok.org.br redirecting to its index.htm (see root directive), not rewriting it to Github... How to do it? All are in production, is a concrete case.

I was testing many variations of location = / { try_files ...} but no one works. Using a UBUNTU 16 LTS server.
/etc/nginx/sites-available/ok.org.br
server {
        server_name  suporte.ok.org.br;

        root   /var/www/suporte.ok.org.br;
        index  index.html index.htm;

        #?? location =/ {...} is not working!

    location / {
            rewrite
              ^/?git$
              http://github.com/okfn-brasil/suporte
              break;
            rewrite
              ^/?([vV][\.\d]+)$
              http://github.com/okfn-brasil/suporte/tree/$1
              break;
            rewrite
              ^/?tickets$
              http://github.com/okfn-brasil/suporte/issues
              break;
            rewrite
              ^/?(?:(?:tic|ticket)/)?(\d+)$
              http://github.com/okfn-brasil/suporte/issues/$1
              break;
            rewrite
              ^/?(.+)$
              http://github.com/okfn-brasil/suporte/$1
              break;
    }

}


text:
Q: How to make custom_header_setup() image as background image? I have created a function that enables Header Image in Wordpress (5.0.3) ACP. My HTML code treats that image as normal image (not background).
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />

How can I make my custom header as background image?

A: Because you have used it as an image.

This code is used to display images, not background images.
Use it with text:

Example of a DIV element with a background image:

Or without text:

Source is enter link description here
I tried it with the header tag...

Your text here.


text:
Q: EXECUTE format COPY. Не работают переменные Создал в БД postgres функцию, которая при вызове должна выгружать данные в файл на сервере.
Если подставляются переменные, то файл создается, НО внутри только одна строка с HEADER'м, а данных нет... при этом никаких ошибок не выдается.
Вот сама функция:
CREATE OR REPLACE FUNCTION public.gidro5
(
  IN  tms1  timestamp without time zone = '2019-01-01 00:00:00'::timestamp without time zone,
  IN  tms2  timestamp without time zone = '2020-01-01 00:00:00'::timestamp without time zone
)
RETURNS void AS
$$

begin

EXECUTE format('COPY(
        SELECT
        sensor.id as "NST",
        measurement.timestamp_ as "time_stamp",
        measurement.number as "h"
FROM
  public.measurement
  INNER JOIN public.sensor ON (public.measurement.sensor = public.sensor.id)
WHERE
  measurement.timestamp_ BETWEEN %L AND %L
ORDER BY
  measurement.timestamp_) TO ''/tmp/1.csv'' with (FORMAT csv, HEADER true, delimiter '','');', tms1, tms2);

end
$$
LANGUAGE 'plpgsql';

ALTER FUNCTION public.gidro5(timestamp without time zone, timestamp without time zone)
  OWNER TO postgres;

Однако, если заместо tms1 и tms2 подставить даты напрямую, вот так:
measurement.timestamp_) TO ''/tmp/1.csv'' with (FORMAT csv, HEADER true, delimiter '','');', '2021-01-01', '2022-01-01');

то все прекрасно работает. Подскажите пожалуйста что тут не так с переменными?


text:
Q: Referring to resources named with variables in Terraform I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax ("${aws_ecs_task_definition[var.name].arn}") but I just guessed at that.
(Caveat: I might be going about this in completely the wrong way)
Here's my module's (simplified) main.tf file:
variable "name" {}

resource "aws_ecs_service" "${var.name}" {
    name = "${var.name}_service"
    cluster = ""
    task_definition = "${aws_ecs_task_definition[var.name].arn}"
    desired_count = 1
}

resource "aws_ecs_task_definition" "${var.name}" {
    family = "ecs-family-${var.name}"
    container_definitions = "${template_file[var.name].rendered}"
}

resource "template_file" "${var.name}_task" {
    template = "${file("task-definition.json")}"

    vars {
        name = "${var.name}"
    }
}

I'm getting the following error:
Error loading Terraform: Error downloading modules: module foo: Error loading .terraform/modules/af13a92c4edda294822b341862422ba5/main.tf: Error reading config for aws_ecs_service[${var.name}]: parse error: syntax error

A: The picture below shows what is going on.
The terraform documentation does not make their use of "NAME" clear versus the "name" values that are used for the actual resources created by the infrastructure vender (like, AWS or Google Cloud).
Additionally, it isn't always "name=, but sometimes, say, "endpoint= or even "resource_group_name= or whatever.
And there are a couple of ways to generate multiple "name" values -- using count, variables, etc., or inside tfvar files and running terraform apply -var-file=foo.tfvars

A: I was fundamentally misunderstanding how modules worked.
Terraform does not support interpolation in resource names (see the relevant issues), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the module system already handles that.


text:
Q: How many rows of data can karate "read(file.csv)" can read? I am trying to read and print the data from a csv file using below karate scenario outline code snippet. the CSV file contains more than 350 rows of data with 2 columns "Description" and "Expression". But when I execute the below code snippet its running for more than 1hr and not generating any cucumber reports.
Note: the same code snippet works fine when the CSV file contains 50-100 rows
Scenario Outline: <Description>
And def result = {"items":{"name":'#(Description)',"expression":'#(Expression)'}}
Then def rule_description =  result.items.name
Then print rule_description
Then def rule_expression =  result.items.expression
Then print rule_expression

Examples:
  | data_file |

Can someone please help and guide me what am I missing here.


text:
Q: SHA1 does not match I am using SMF. In SMF passwords saved in mysql like:
sha1(usernamepassword);

Some of hashes works fine. But other hashes which includes special chars like "öüşığ" and space etc. does not match.
For example "aksak temüraga" should be converted to sha1 as "4b4eb0eed79356eb56eb9058e6dea20d71e48e3c" but it is converted to sha1 as "c4aa8328bf5ec76cfc0416fd7ec40f8dea7f3d62"

A: Since you are trying to create an external login to SMF forum, then you have to stay with hashing provided by SMF.
About your problem, you should take a look at Sources\LogInOut.php file of SMF installation, to check how SMF creates the login.
Then you can use the same technique for your external login.


text:
Q: Which is the best way to retrieve data from a remote server using concurrent calls? I'm working on retrieving data like Products, Orders eCommerce platforms such as BigCommerce, Shopify, etc., and save it in our own databases. To improve the data retrieval speed from their APIs, we're planning to use the Bluebird library.
Earlier, the data retrieval logic was like retrieving one page at a time. Since we're planning to make concurrent calls "n" number of pages will be retrieved concurrently.
For example, Bicommerce allows us to make up to 3 concurrent calls at a time. So, we need to make the concurrent calls so that we will not retrieve the same page more than once, and in case if a request failed then a request for that page will be resent.
What's the best way to implement this? One idea that strikes my mind is,
One Possible Solution - Keep an index of ongoing requests in the database and update it on the API completion, so we will know which are unsuccessful.
Is there a better way of doing this? Any suggestions/ideas on this would be highly appreciated.


text:
Q: How to re-assign jQueryUI Dialog close button event Basically I am showing and hiding the Dialog manually via positioning so something like 'swfupload' works (dont ask hehe, the multi-upload flash control i use cannot be hidden or Flash does something funky... so I am using positioning to show/hide the Dialog).
So i set autoOpen: to true so when the page loads its not prehidden... and I just use jquery css to hide it with positioning and then hide its overlay with display:none; (versus a css file since i need to override style="" elements) ...
and now i want to hide it...
but the Dialog auto-created close button automatically calls its own close functionality and sets 'display: none'. I want to override this to do my positioning ...
Any idea how to reassign it? I was thinking of somehow unbinding the click event on it and reassigning it. i dunno what is best way really to do it.
Thanks for any ideas :)

A: You can bind to the close event and do your logic in there:
$('#dialogID')
        .dialog({
            autoOpen: true
        }).bind('dialogclose', function(event, ui) { /* Do position logic here */ });

I didn't test this code so not sure if you will manually have to call close in order to hide the dialog.  If so just add in this line:
$('#dialogID').dialog("close");

Also remember that this close function will be called if the 'X' in the upper right corner of the dialog is clicked as well.

A: This kinda helped me get on track:
i did:
my html:

    Please upload the files you want associated with this payment below:

    Attach
    ....
    Attach
    ...
    Attach

my css:
  .ui-widget-overlay{
    display: none;
  }
  .ui-dialog{ /*need to override style="" with jquery. this is just for reference */
    top: -5000px;
  }

my js:
function closeDialog(){
  $('.ui-dialog').css('top', -5000);
  $('.ui-widget-overlay').css('display','none');
}

var swfu;
var dialog;
var orig_top_css;

$(document).ready (function()
{

    dialog = $('#popup').dialog({
      closeOnEscape: false,
      modal: true,
      title: 'Upload File(s) related to this row'

    }).bind('dialogbeforeclose', function(event, ui) {
      closeDialog();
      return false;
    });

    orig_top_css = $('.ui-dialog').css('top'); //get after dialog created, possibly see if oncomplete function. but this stores origial 'centered' value

    var settings =
    {
        flash_url: 'scripts/swfupload/Flash/swfupload.swf?'+Math.random(),
        ...

      upload_success_handler: function() { console.log ('success'); alert('You have successfully uploaded the file(s).'); dialog.dialog('close'); }, //catches close and doesnt really close in my dialogbeforeclose event
      upload_progress_handler: function(file, complete, total) { console.log ('progress' + file + " " + complete + " " + total); }

      ,prevent_swf_caching : true
      ,post_params: {payment_id: 'value1'}

    };

    swfu = new SWFUpload (settings);

    $('.upload_file').click(function() {
      orig_top_css_wopx = parseInt( orig_top_css.replace('px','') ,10);

      $('.ui-dialog').css('top', orig_top_css_wopx);
      $('.ui-widget-overlay').css('display','block');

      // prevent the default action, e.g., following a link
      return false;
    });

     $('.ui-dialog').css('top', -5000); //hide the dialog when the page loads, the popup also is hidden via css
});

Just need to add setPostParams to customize upload for each row and a progress bar and I'll be set :).

A: I replaced my click function with something like so to get setPostParams working:
  $('.upload_file').click(function() {
      orig_top_css_wopx = parseInt( orig_top_css.replace('px','') ,10);

      $('.ui-dialog').css('top', orig_top_css_wopx);
      $('.ui-widget-overlay').css('display','block');

      var row_id = $(this).attr('id').replace('attach_','');
      row_id = parseInt(row_id,10);

      //alert(row_id);

      if(row_id && row_id > 0) {
        swfu.setPostParams({row_id_key: row_id}); //think this should dynamically set the post param
      } else {
        alert('Error getting id');
      }

      // prevent the default action, e.g., following a link
      return false;
    });

and my bind event to reset the customparam:
.bind('dialogbeforeclose', function(event, ui) {
          closeDialog();
          swfu.setPostParams({});
          return false;
        });

and to get progress working, i added handlers.js and fileprogress.js to my page (from their simpledemo example).
then changed the callbacks to their settings:
  custom_settings : {
    progressTarget : "fsUploadProgress",
    cancelButtonId : "btnCancel"
  },
  file_queued_handler : fileQueued,
  file_queue_error_handler : fileQueueError,
  file_dialog_complete_handler : fileDialogComplete,
  upload_start_handler : uploadStart,
  upload_progress_handler : uploadProgress,
  upload_error_handler : uploadError,
  upload_success_handler : uploadSuccess,
  upload_complete_handler : uploadComplete,
  queue_complete_handler : queueComplete    // Queue plugin event

and added the html to get that to work:

  Please upload the files you want associated with this row below:

  <input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" />

            Upload Queue

0 Files Uploaded


text:
Q: Connect to MSSQL database with period in the name, using ODBC If I have a database named something like "foo4.3" and I attempt to connect to it using odbc it looks for a database named "foo4". The period works fine in any other string (for instance puts "foo4.3" outputs "foo4.3" so I'm a little confused as to why it is attempting to look for a database named "foo4". I've already tried the literal string version (single quotes) as well as the escape enabled string (double quotes) and attempted to escape the period but I get the same results.

A: Wrap the database name in brackets: [foo4.3]


text:
Q: Header and footer for AutoCompleteTextView in android I have AutoCompleteTextView attached to my view, and used ArrayAdapter to populate for list of items. But I am unaware of how to add header and footer view for AutocompleteTextView drop down's item.
I know we can add header and footer in listview.
Any suggestions ?

A: On an AutoCompleteTextView, you don't have direct access to the DropDownListView, that's why you cannot add header and footer views there.
A solution to your problem will be to use 2 types of views in your list, and set the first/last row to have the header's/footer's layout. This can be done on the adapter, which you create yourself.
Here's some info about how to provide different layouts for different rows in a list view:
Android ListView with different layouts for each row

A: Android provided methods like addHeaderView(View v) and addFooterView(View v) to define headers and footers for the ListViews.
To find an answer on your question, I can refer you to Android: Adding static header to the top of a ListActivity.
Good luck!

A: private class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    private ArrayList<String> resultList;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

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

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }};
        return filter;
    }
}

where autocomplete function should return the arraylist of string


text:
Q: ListView displays data twice I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView

This is a code of AddBook activity.

package training.android.com.librarycard;

import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;

public class AddBook extends AppCompatActivity
        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int EXISTING_BOOK_LOADER = 0;
    Spinner mBookType;
    EditText mBookTitle, mBookAuthor, mBookPublishYear;
    String bookType;
    int position;
    private boolean bookHasChanged = false;

    private Uri currentBookUri;

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            bookHasChanged = true;
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_book);

        Intent intent = getIntent();
        if (intent != null) {
            currentBookUri = intent.getData();

            if (currentBookUri == null) {
                setTitle("Add a book");
                invalidateOptionsMenu();
            } else {
                setTitle("Edit a book");
                getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
            }

        }

        mBookType = findViewById(R.id.spinner);
        mBookTitle = findViewById(R.id.book_title);
        mBookAuthor = findViewById(R.id.book_author);
        mBookPublishYear = findViewById(R.id.publish_year);

        mBookType.setOnTouchListener(touchListener);
        mBookAuthor.setOnTouchListener(touchListener);
        mBookTitle.setOnTouchListener(touchListener);
        mBookPublishYear.setOnTouchListener(touchListener);

        setupBookTypeSpinner();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (currentBookUri == null) {
            MenuItem menuItem = menu.findItem(R.id.action_delete);
            menuItem.setVisible(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.action_save:
                setBook();
                finish();
                return true;
            case R.id.action_delete:
                showDeleteConfirmationDialog();
                return true;
            case android.R.id.home:
                if (!bookHasChanged) {
                    NavUtils.navigateUpFromSameTask(AddBook.this);
                    return true;
                }
                DialogInterface.OnClickListener discardButtonClickListener
                        = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        NavUtils.navigateUpFromSameTask(AddBook.this);
                    }
                };

                showUnsavedChangeDialog(discardButtonClickListener);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Discard your changes and quit editing?");
        builder.setPositiveButton("Discard", discardButtonClickListener);
        builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (dialog != null)
                    dialog.dismiss();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    private void showDeleteConfirmationDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Delete this book ?");
        builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteBook();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (dialog != null)
                    dialog.dismiss();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void deleteBook() {
        if (currentBookUri != null) {
            int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
            if (rowDeleted == 0)
                Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();

        }

        finish();

    }

    public void setupBookTypeSpinner() {
        final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
                this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
        bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        mBookType.setAdapter(bookTypeAdapter);

        mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                bookType = parent.getSelectedItem().toString();
                position = parent.getSelectedItemPosition();
                Log.i("BookTypeSelection", bookType+"");

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    public void setBook() {
        String bookTitle = mBookTitle.getText().toString().trim();
        String bookAuthor = mBookAuthor.getText().toString().trim();
        String publishYear = mBookPublishYear.getText().toString().trim();

        if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
                 && TextUtils.isEmpty(publishYear))
            return;

        Database database = new Database(this);
        SQLiteDatabase db = database.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
        values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
        values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
        values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);

        if (currentBookUri == null) {
            Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
            if (uri == null) {
                Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
            }
        } else {
            int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
            if (rowAffected == 0) {
                Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
            }
        }

        db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
        Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String [] projection = {
                LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
                LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
                LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
                LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
        return new CursorLoader(this,currentBookUri,projection,
                null,null,null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if(data.moveToFirst()){
            String title = data.getString(
                    data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
            String type = data.getString(
                    data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
            String publishYear = data.getString(
                    data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
            String author = data.getString(
                    data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));

            mBookTitle.setText(title);
            mBookAuthor.setText(author);
            mBookType.setSelection(position);
            mBookPublishYear.setText(publishYear);

        }

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mBookTitle.setText("");
        mBookType.setSelection(position);
        mBookAuthor.setText("");
        mBookPublishYear.setText("");

    }

    @Override
    public void onBackPressed() {
        if(!bookHasChanged){
            super.onBackPressed();
            return;
        }

        DialogInterface.OnClickListener discardButtonClickListener =
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                };

        showUnsavedChangeDialog(discardButtonClickListener);
    }

}

And this is a code of Home activity that contains a listView to
  display the data.

   package training.android.com.librarycard;

    import android.app.LoaderManager;
    import android.content.ContentUris;
    import android.content.CursorLoader;
    import android.content.Intent;
    import android.content.Loader;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.NavigationView;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;

    import java.util.ArrayList;
    import java.util.List;

    import training.android.com.librarycard.Database.Database;
    import training.android.com.librarycard.Database.LibraryCardContract;
    import training.android.com.librarycard.Models.BookCursorAdapter;
    import training.android.com.librarycard.Models.BookDetail;

    public class Home extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {

        private static final int BOOK_LOADER = 0;
        private ListView mBookList;
        private BookCursorAdapter cursorAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            mBookList = findViewById(R.id.books_rv);

            cursorAdapter = new BookCursorAdapter(this, null);
            mBookList.setAdapter(cursorAdapter);

            mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(Home.this, AddBook.class);
                    Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
                    intent.setData(currentPetUri);
                    startActivity(intent);
                }
            });

            getLoaderManager().initLoader(BOOK_LOADER, null, this);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getBaseContext(), AddBook.class);
                    startActivity(intent);
                }
            });

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.addDrawerListener(toggle);
            toggle.syncState();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);
        }

        @Override
        public void onBackPressed() {
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                super.onBackPressed();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            switch (id) {
                case R.id.delete_all_books:
                    deleteAllBooks();
                    return true;
            }

            //noinspection SimplifiableIfStatement

            return super.onOptionsItemSelected(item);
        }

        private void deleteAllBooks() {
            int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
                    null, null);
        }

        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            String[] projection = {
                    LibraryCardContract.LibraryCard._ID,
                    LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
                    LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
                    LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
                    LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};

            return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
                    projection,
                    null,
                    null,
                    null);

        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            cursorAdapter.swapCursor(data);

        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            cursorAdapter.swapCursor(null);

        }

    }

> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;

/**
 * Created by Hassan on 4/9/2018.
 */

public class BookCursorAdapter extends CursorAdapter {
    public BookCursorAdapter(Context context, Cursor c) {
        super(context, c, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context)
                .inflate(R.layout.book_list,parent,false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView bookTitle = view.findViewById(R.id.book_name_tv);
        TextView bookAuthor = view.findViewById(R.id.author_tv);
        TextView bookType = view.findViewById(R.id.book_type_tv);
        TextView publishYear = view.findViewById(R.id.publish_year_tv);

        String title = cursor.getString(
                cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
        String type = cursor.getString(
                cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
        String year = cursor.getString(
                cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
        String author = cursor.getString(
                cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));

        bookAuthor.setText(author);
        bookTitle.setText(title);
        bookType.setText(type);
        publishYear.setText(year);

    }

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

Screenshot of the application
  enter image description here


text:
Q: How can I get LSDV estimator of a two-way dynamic panel model? I am now trying to explain a dynamic panel data model as follow:
$y_{it} = \alpha y_{i,t-1} + x_{it}'\beta + \mu_i + \lambda_t + \nu_{it}$
Here I want to compute its LSDV estimator $\tilde\beta$, regardless the biasness. I searched many papers and only see the LSDV estimator for one-way error component dynamic panel data model. Now I am stuck with this calculation. I knew that a transform matrix Q or something is needed but what does it look like here? Does it look the same as Q in static two-way error component panel data model?