text:
Q: Refactoring if statements and other code in python Whats the best way to refactor this code to clean it up:
1) Selects from the db adding a column for the percentage difference between two columns
2) Loops through the values of the columns
3) If the date is in the past
4) If the price is greater than 500 and the percentage difference is less than 1st argument set flag to 1
5) Else if the price is less than 500 and the percentage difference is less than
2nd argument set flag to 1
6) Otherwise keep the flag as 0
def calculateEmployeeSpend(read_cursor, flag_higher_amount, flag_lower_budget):

    read_cursor.execute("SELECT distinct b.employee_id, b.amount, "
                "s.spend, b.date, b.amount - s.spend as spend_left,  "
                "100.0*(b.amount - s.spend) / b.amount As PercentDiff FROM employee_budget_upload "
                "As b JOIN employee_budget_spent As s ON  b.employee_id = s.employee_id where b.amount != 0")

    for employee_id, amount, spend, date, spend_left, percent_diff in read_cursor:
        flag=0
        date_of_amount = dt.strptime(date, "%d/%m/%Y")
        if date_of_amount <= dt.now():
            if amount > 500 and percent_diff < int(flag_higher_amount):
                flag=1

            if amount < 500 and percent_diff < int(flag_lower_amount):
                flag=1

Edit:
I have changed the ifs to one if:
if amount > 500 and percent_diff < int(flag_higher_amount) or amount < 500 and percent_diff < int(flag_lower_amount):
                    flag=1

A: *

*Extract out the SQL command into a file.sql. Give the function either the path to the sql file or the text of the sql file.

*Rename the flag to its purpose.

*your if and elif both sets the flag to 1 so why the differences? Combine it to one condition

*'500' should be a variable of the function.

*Write a short description of what the function does in """ """. You can specify what every parameter is if you want.

A: Since there seems to be several instances of keeping track of state, it might help in the long run to decouple the logic into classes and methods.

A: First of all the definition of 'best' depend on your goal, like: readability, efficiency, performance and so on.
In many cases I wold prefer to solve task like this by reading the whole dataset in pandas DataFrame and utilise one (or set off) convenient and expressive pandas idioms.
Or, by writing more sophisticated SQL statement which allow to solve the end to end task on database side.
As for common best practice for refactoring, I would recommend externalise the magic values like "500" or "%d/%m/%Y" to a constant or method parameter.
Give a "flag" more self-spoken name.
If case with amount exactly equal to 500 is purposely should lead to flag equal to zero, then it should be better explicitly reflected in comments.
In order to avoid code duplication (flag=1) it is better to combine the if statements, like this:
if amount > 500 and percent_diff < int(flag_higher_amount) or \
   amount < 500 and percent_diff < int(flag_lower_amount):
    flag=1

You also can create a function with self-spoken name, and move whole condition inside such a function:
if is_percent_inside_amount_bounds(
     percent_diff, amount, flag_lower_amount, flag_higher_amount):
    flag = 1

or just
flag = is_percent_inside_amount_bounds(
     percent_diff, amount, flag_lower_amount, flag_higher_amount)

In case of amount equal exactly 500 could be interpreted like amount<=500 the condition could be transformed to more laconic:
flag = percent_diff < int(
    flag_lower_amount if amount>500 else flag_higher_amount)

but I would not recommend to use ternary operator in production code in cases like this, because it usually reduce readability.


text:
Q: StreamZip only showing the first order stream I'm trying to use StreamZip, to combining 2 stream. Here is what i do
StreamZip([stream1, stream2]).listen((data){
  _queryController.sink.add(data);
});

it will send the first stream (stream1) only, but when i change the order to
StreamZip([stream2, stream1]).listen((data){
  _queryController.sink.add(data);
});

it will show the result of stream2. How can i fix it ? did i miss something?
here is the stream
   stream1 = databaseReference
        .collection("userChat")
        .where("from", isEqualTo: userId)
        .orderBy("messageDate", descending: true)
        .snapshots();

    stream2 = databaseReference
        .collection("userChat")
        .where('to', isEqualTo: userId)
        .orderBy("messageDate", descending: true)
        .snapshots();

My data

A: Zip only emits a new value when there's a new pair of values from two streams (if there's a new value in the first stream, it waits for a new value in the second stream). You probably want to use combineLatest. It will combine values from both streams when any of them sends a new value:
final combinedStream = stream1.transform(combineLatest(stream2, (obj1, obj2) {
  // Combine both objects and return a new one
  return CombinedData(obj1, obj2);
}));

class CombinedData {
  final List to;
  final List from;

  CombinedData(this.to, this.from);
}

dependencies:
  stream_transform: ^0.0.2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable not updating passed ByRef I am using Option Explicit in all modules, this one has me scratching my head, perhaps it is in the call method that things get lost.
Reading worksheets and combining particular data into a new workbook, single worksheet, the variable colData should increment the column and it will be updated and passed back in as many times as there are worksheets (ex. copy months 1-12 for a given year in cols 1-12, then the next year copy months 1-12 in cols 13-24, etc.)
Call to Function returns a Boolean (this is an error check directly afterwards):
  'Attempt to load Total Revenue for the Import Sheet
  TotRevLoaded = Application.Run("modGetDataHelpers.loadTotRev", wsImport, rng, colData)

Here are the parts of the Function that matter:
'Sub to load total revenue from selected file across the worksheets
Private Function loadTotRev(ByRef wsImport As Worksheet, ByRef rng As Range, ByRef colData As Long) As Boolean

'matchRow is called above and works

Dim k As Integer

    For k = 1 To 12
        'sets headers for the sheet
        wsData.Cells(1, colData) = strYear
        wsData.Cells(2, colData) = k
        'Copy Total Revenue in to row 3
        wsData.Cells(3, colData) = wsImport.Cells(matchRow, 2 + k).Value
        colData = colData + 1
    Next k
    loadTotRev = True 'Success in loading the total rev on sheet

End Function

colData updates in the function as one would expect 1-13, but when leaving the function and coming back for the next worksheet import it is always 1, so the value of colData is not changing at its reference address.
This one should be easy.  The variable is being converted to ByVal and once you leave the scope of the function the modifications are lost.
I thought this might be because of the arg wrap in (), Nope. Change to a sub and without assignment you can drop these.
I thought it might be due to the assignment =, Nope. Changed to Sub.
Because it is getting passed to a function, Nope. Changed to a Sub Public and Private.
Because the caller and the modifier are in different modules, Nope
Working on the solution, I don't want a global variable or to bring all helper functions into the same module scope (module global variable).

A: Great feedback from experienced VBA users, leading to good information.
1) @TimWilliams: Avoid the use of Application.Run to call Private Functions/Subs if you intend to pass parameters ByRef, it will caste these as ByVal.
http://www.tushar-mehta.com/publish_train/xl_vba_cases/1022_ByRef_Argument_with_the_Application_Run_method.shtml
2) @MathieuGuindon: Avoid the use of Application.Run altogether, making the Functions/Subs Public, or investigate the implementation of a class to encapsulate and protect, if truly required look at Option Private Module
I did in fact hit upon the make Public solution through trial and error, thereby dropping the Application.Run call, but the reasoning came later.


text:
Q: HMACSHA256 in C# vs node.js I am generating a hash string in C# and node.js but keep getting two different results...
In C#:
byte[] secretKeyBytes = Convert.FromBase64String('some_secret_key');
byte[] requestValuesSignature = Encoding.UTF8.GetBytes('teststring');
HMACSHA256 testHash = new HMACSHA256(secretKeyBytes);

byte[] = hashedBytes = testHash.ComputeHash(requestValuesSignature);
string hash1 = Convert.ToBAse64String(hashedBytes);

Console.WriteLine(hash1);

In Node.js:
var hash2 = crypto.createHmac('SHA256', 'some_secret_key').update('teststring', 'utf8').digest('base64');

Can someone help?
Thanks in advance!

A: Try it this way
byte[] secretKeyBytes = Encoding.UTF8.GetBytes('some_secret_key');

because the JS implementation does the same, it just gets the bytes from the key string, which does not need to be a base64 string but can be any string.
EDIT:
As you can't change C# side, you have to do the same (possibly wrong) behaviour on the nodejs side, i.e. decode the base64 string before it is used as secret.
var mykey = new Buffer('some_secret_key', 'base64').toString();
var hash2 = crypto.createHmac('SHA256', mykey).update('teststring', 'utf8').digest('base64');

Be aware, both sides will fail, if the secret is not a valid base64 string (which is allowed!)

A: Answer - on the C# side, change utf8 to ASCIIEncoding!


text:
Q: How to create Chrome-style program self-updating in Windows? Google's Chrome browser has a super-slick updating system on Windows. It doesn't require administrative privileges, and it updates in place without requiring user interaction.
I'm trying to create something similar to this, and would appreciate any advice on how to do it.
The first part of their trick is they don't install into Program Files like most Windows programs do, instead they install into C:\Users\USER_NAME\AppData\Local\Google\Chrome\Application. This enables their program file to modify itself without administrative privileges.
Looking inside that directory, I see that there is not only a chrome.exe but also an old_chrome.exe. Searching around online, I've found that chrome backs itself up as old_chrome in case the update goes bad, it can still run something.
So is the way to do this to create a helper application that comes as part of the install package, that you transfer execution into (I assume that's somehow doable), and that helper application does the file renaming and relaunches chrome.exe when it's done? (If so, assumedly this helper application is in turn deleted by chrome.exe on launch, explaining why I don't see it sitting around.) There's no way to simply have chrome.exe rename itself to old_chrome.exe and copy in and launch the new chrome.exe is there?
If this is the best way to make something like this work, are there any pre-built solutions to do this that I could just roll into my project, given that this seems like fairly generic functionality, or would I have to roll something like this myself?
Alternatively, if there's a better way, what is it? (For what it's worth, Chrome's approach strikes me as much more elegant and straightforward than Mozilla's new approach using services)

A: Okay, got this working, here's how it works.
There's no need for a helper application. At least on Windows, a program can be renamed in place, it just can't be deleted. Therefore, I added an updater routine to my program, and it downloads the new file. After download is complete, it renames the old executable, and moves the new executable into its spot.
Then, you can simply execute the new executable from inside the old one's running process, and then quit the old one.
Voila, no-escalation swap of a new version for the old.


text:
Q: Navigating to another page dynamically using href using node js and express ejs I am creating a sample blog website in which homepage contains blogs in order of the day it is posted.
The layout of the blog is like below :
Day 1
some paragraph text.....Read More
Day 2
some paragraph text.....Read More
Now how do route/redirect the page to particular post page using Day as Id and using anchor tag when clicking Read More

A: EJS Code:
...

<% for (var i = 0; i < day.length; i++) { %>
    <a href="<%= 'example/'+day[i].id %>">Read More
    <a href="<%= 'https:www.example.com/example/'+day[i].id %>">Read More
<%}%>
...

I hope this should work!
In the above code the dynamic url will work for both the codes
Dynamic Routing with Express.js
app.get('example/:id', function(req , res){
  res.render('Day' + req.params.id);
});


text:
Q: How can you create a pop-up window in Discord that accepts an input from the user? It's my first time seeing this feature from a Discord bot. I tried looking everywhere but it seems that I have failed. There's this feature from Captcha.bot Discord bot where you can accept input from a pop-up window inside Discord.
There's a button in an embedded message made by Captcha.bot where you will have to answer a Captcha test. After pressing the button, it creates a pop-up window like this.

After placing the right answer on the captcha bot, here's the aftermath of the experience.

All I want to learn is how to summon that pop-up window using Discord.js if it's even possible or at least learn how they did it.

A: Those are called modals, and they will be available in the next major discord.js version, v14. There is already a pull request for this.
Update 2022-07-19: Modals in v14.0.0
There are some changes in v14. If you try to update your code from v13.7, there are a few differences:

*

*Modal is now ModalBuilder

*MessageActionRow is now ActionRowBuilder

*TextInputComponent is now TextInputBuilder

*you need to use enums like TextInputStyle.Short, ButtonStyle.Primary, etc. instead of strings (i.e. "SHORT", or "PRIMARY")

*interaction no longer has a isModalSubmit type guard. You'll need to check its type against the InteractionType.ModalSubmit enum

You can find the full code below that you can use with discord.js v14:
// discord.js version v14.0.0+
const {
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  Client,
  Events,
  GatewayIntentBits,
  InteractionType,
  ModalBuilder,
  TextInputBuilder,
  TextInputStyle,
} = require('discord.js');

const TOKEN = 'YOUR TOKEN HERE';
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
  ],
});

client.on(Events.MessageCreate, (message) => {
  if (message.author.bot) return;

  let button = new ActionRowBuilder();
  button.addComponents(
    new ButtonBuilder()
      .setCustomId('verification-button')
      .setStyle(ButtonStyle.Primary)
      .setLabel('Open modal dialog'),
  );
  message.reply({
    components: [button],
  });
});

client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isButton()) {
    if (interaction.customId === 'verification-button') {
      const modal = new ModalBuilder()
        .setCustomId('verification-modal')
        .setTitle('Verify yourself')
        .addComponents([
          new ActionRowBuilder().addComponents(
            new TextInputBuilder()
              .setCustomId('verification-input')
              .setLabel('Answer')
              .setStyle(TextInputStyle.Short)
              .setMinLength(4)
              .setMaxLength(12)
              .setPlaceholder('ABCDEF')
              .setRequired(true),
          ),
        ]);

      await interaction.showModal(modal);
    }
  }

  if (interaction.type === InteractionType.ModalSubmit) {
    if (interaction.customId === 'verification-modal') {
      const response =
        interaction.fields.getTextInputValue('verification-input');
      interaction.reply(`Yay, your answer is submitted: "${response}"`);
    }
  }
});

client.once('ready', () => {
  console.log('Bot v14 is connected...');
});

client.login(TOKEN);

Previous answer 2022-06-28: Modals in v13.7.0
Modals are available since v13.7.0. If you try to update your code from discord-modals, there are a few differences:

*

*you'll need to import Modal and TextInputComponent from discord.js

*TextInputComponents must be inside a MessageActionRows

*the interaction has a showModal() method that opens the modal

*the interaction has an isModalSubmit() method that checks if it's a ModalSubmitInteraction

*there is no modalSubmit event

*to get the response you need to use interaction.fields.getTextInputValue()
You can find the full code below that you can use in v13.7:
// discord.js version v13.7.0+
const {
  Client,
  Intents,
  MessageActionRow,
  MessageButton,
  Modal,
  TextInputComponent,
} = require('discord.js');

const TOKEN = 'YOUR TOKEN HERE';
const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES],
});

client.on('messageCreate', (message) => {
  if (message.author.bot) return;

  let button = new MessageActionRow();
  button.addComponents(
    new MessageButton()
      .setCustomId('verification-button')
      .setStyle('PRIMARY')
      .setLabel('Open modal dialog'),
  );
  message.reply({
    components: [button],
  });
});

client.on('interactionCreate', async (interaction) => {
  if (interaction.isButton()) {
    if (interaction.customId === 'verification-button') {
      const modal = new Modal()
        .setCustomId('verification-modal')
        .setTitle('Verify yourself')
        .addComponents([
          new MessageActionRow().addComponents(
            new TextInputComponent()
              .setCustomId('verification-input')
              .setLabel('Answer')
              .setStyle('SHORT')
              .setMinLength(4)
              .setMaxLength(12)
              .setPlaceholder('ABCDEF')
              .setRequired(true),
          ),
        ]);

      await interaction.showModal(modal);
    }
  }

  if (interaction.isModalSubmit()) {
    if (interaction.customId === 'verification-modal') {
      const response =
        interaction.fields.getTextInputValue('verification-input');
      interaction.reply(`Yay, your answer is submitted: "${response}"`);
    }
  }
});

client.once('ready', () => {
  console.log('Bot v13 is connected...');
});

client.login(TOKEN);

First answer 2022-03-30: Using the discord-modals package
In the meantime, you can use an npm package like discord-modals or discordjs-modal.
You can find a working example with the discord-modals package below. Don't forget to install it first using npm i discord-modals.
// discord-modals
const {
  Client,
  Intents,
  MessageActionRow,
  MessageButton,
} = require('discord.js');
const discordModals = require('discord-modals');
const { Modal, TextInputComponent, showModal } = discordModals;

const TOKEN = 'YOUR TOKEN HERE';
const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES],
});
discordModals(client);

client.on('messageCreate', (message) => {
  if (message.author.bot) return;

  let button = new MessageActionRow();
  button.addComponents(
    new MessageButton()
      .setCustomId('verification-button')
      .setStyle('PRIMARY')
      .setLabel('Open modal dialog'),
  );
  message.reply({
    components: [button],
  });
});

client.on('interactionCreate', async (interaction) => {
  if (interaction.isButton()) {
    if (interaction.customId === 'verification-button') {
      const modal = new Modal() // We create a Modal
        .setCustomId('verification-modal')
        .setTitle('Verify yourself')
        .addComponents([
          new TextInputComponent()
            .setCustomId('verification-input')
            .setLabel('Answer')
            .setStyle('SHORT')
            .setMinLength(4)
            .setMaxLength(12)
            .setPlaceholder('ABCDEF')
            .setRequired(true),
        ]);

      showModal(modal, {
        client,
        interaction,
      });
    }
  }
});

client.on('modalSubmit', async (modal) => {
  if (modal.customId === 'verification-modal') {
    const response = modal.getTextInputValue('verification-input');
    modal.reply(`Yay, your answer is submitted: "${response}"`);
  }
});

client.once('ready', () => {
  console.log('Bot v13 is connected...');
});

client.login(TOKEN);


text:
Q: How to prove : If $a,b,c$ are in H.P. in $\Delta ABC$ then $\frac{(\sum ab-2bc ) ( \sum ab-2ca)}{(abc)^2} = \frac{\sin A}{\Delta} -\frac{1}{b^2} $ How to prove : If $a,b,c$ are in H.P. in $\Delta ABC$ then $$\frac{(\sum ab-2bc ) ( \sum ab-2ca)}{(abc)^2}=\frac{\sin A}{\Delta} -\frac{1}{b^2} $$
Please guide how to proceed , will be of great help. Thanks.

A: As $$\triangle=\dfrac{bc\sin A}2$$
So,we need $$\dfrac{(ab+ca-bc)(ab+bc-ca)}{(abc)^2}=\dfrac{2b-c}{b^2c}$$
$$\iff(ab)^2-(bc-ca)^2=a^2c(2b-c)$$
$$\iff a^2b^2-b^2c^2=2a^2bc-2abc^2$$
$$\iff b(a^2-c^2)=2ca(a-c)$$
As  in general, $a-c\ne0$ unless $a=b=c$ $$b(a+c)=2ca\iff\dfrac1a+\dfrac1c=\dfrac2b$$


text:
Q: A 'name' attribute is required for  This error keeps on poping up in my code:
<resources
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <string name="app_name">Commen Games</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <color android:layout_width="wrap_content" />
    <color android:layout_height="wrap_content" android:id="@+id/color1" />
    <string name="action_settings" tools:ignore="DuplicateDefinition">TODO</string>

</resources>

A: <color name="black">#000000</color>

Is an example of how you create a color in your strings.xml in your values folder. You can then reference the color in your xml layouts by using "@color/black". What you are doing here is completely wrong. I suggest you do some more tutorials in android development.


text:
Q: How to use Nodejs build in production mode using babel for my DockerImage i Have a nodejs application and its working fine but in my structure i dont have a src folder i just have all other files and am using MVC but am having the error
here is my script
    "scripts": {
    "start": "babel-node server.js",
    "dev": "nodemon --exec npm start",
    "build-babel": "babel -d ./build ./server.js -s",
    "build": "babel ./Myfolder --out-dir dist --copy-files",
    "serve": "node dist/index.js",
    "sequelize": "sequelize"


text:
Q: (Background-size: Cover) overlaying padding I'm looking for help towards background-size: cover;
So the problem I'm having is that I've got padding on my image box's but having the background image set in CSS seems to have the image covering the image box padding instead of having inside the padding.
I was wondering if there is any way of doing it through background: url() and background-size and having it inside the padding instead of overlaying the padding.
What i have so far:

.image-container {
  background: #eee;
  width: 100%;
  height: 120px;
}

.image-container div.image {
  background: #ee1;
  height: 100%;
  width: 50%;
  display: inline-block;
  float: left;
  padding: 4px 0px;
  background: url("https://static.pexels.com/photos/14621/Warsaw-at-night-free-license-CC0.jpg");
  background-size: cover;
}

A: You could use a border instead of padding.
Something like:
.image-container div.image {
  padding: 4px 0px; /* remove this */
  ...
  border-top: 4px solid transparent; /* or whatever color */
  border-bottom: 4px solid transparent; /* or whatever color */
  box-sizing: border-box;
  background-size: cover;
}

.image-container {
  background: #eee;
  width: 100%;
  height: 120px;
}

.image-container div.image {
  background: #ee1;
  height: 100%;
  width: 50%;
  display: inline-block;
  float: left;
  border-top: 4px solid green; /* using a color just for demo. */
  border-bottom: 4px solid green; /* using a color just for demo. */
  box-sizing: border-box;
  background: url("https://static.pexels.com/photos/14621/Warsaw-at-night-free-license-CC0.jpg");
  background-size: cover;
}

From the above demo snippet you can see that the border is above the image.


text:
Q: How to search list of dictionary in mysql column(datatype is JSON) My data format looks like as below in a column in mysql db:
|column1| column2 |
| -------- | -------------- |
| 1| [{"id": 1, "name": "American"}, {"id": 2, "name": "Indian"}]|
| 2| [{"id": 2, "name": "Indian"}, {"id": 3, "name": "Britain"}]|
| 3| [{"id": 4, "name": "Indian"}, {"id": 5, "name": "Britain"}]|

Search by id's (2,3) in column2 should give the expected output as below.
|column1| column2 |
| -------- | -------------- |
| 1| [{"id": 1, "name": "American"}, {"id": 2, "name": "Indian"}]|
| 2| [{"id": 2, "name": "Indian"}, {"id": 3, "name": "Britain"}]|


text:
Q: Reverse pusher - secret needed to receive, not send Pusher service works as illustrated here:

Does it make sense to use it in reverse direction (and switched data channels)? My use case is as follows:

*

*end users (actually mobile, not browser) send messages to Pusher via HTTP-based REST API

*my firewalled machine is connected to Pusher via WebSockets API, subscribes channel and receives messages in realtime

This way I can work with Sandbox plan (only 1 persistent connection is used) but mobile app must contain Puser app key.
From what I understand, anyone can use this key to register subscribe same message stream via websockets. Is there a reverse mode, where receiving messages requires knowing the secret? Maybe other service would suit better?

A: A more secure solution would be for the mobile clients to use client events. Client events can only be triggered on private channels where the subscription to the channel has to be authenticated.The authentication requests should got to an HTTP endpoint that you control so that you can validate the subscription request.
You firewalled machine can either then have a WebSocket connection and receive the client events over that connection. Or it could receive the client events via client event WebHooks if it exposes an HTTP endpoint.


text:
Q: How to set mutiple UIView in centre I have tried these solutions:
First solution
ansview.center = CGPointMake(viewAnswer.frame.size.width  / 2,
                viewAnswer.frame.size.height / 2);
    ansview.center = CGPointMake(viewAnswer., viewAnswer.height/2)

Second solution
self.ansview.center = CGPointMake(CGRectGetMidX(self.viewAnswer.bounds),
                CGRectGetMidY(self.viewAnswer.bounds));

I have already tried this code. But only one view is set to center. How to set multiple views in center?

A: viewDidLayoutSubviews is called to notify the view controller that its view has just laid out its subviews.
override func viewDidLayoutSubviews() {
        self.ansview.center = CGPointMake(self.viewAnswer.bounds.size.width / 2, self.viewAnswer.bounds.size.height / 2)
    }

You should use the bounds and not the frame, as the frame is undefined if the view has a transform.

A: You can also try this
[ansview setCenterX:self.view.centerX];
[ansview setCenterY:self.view.centerY];


text:
Q: Regex; backreferencing a character that was NOT matched in a character set I want to construct a regex, that matches either ' or " and then matches other characters, ending when a ' or an " respectively is matched, depending on what was encountered right at the start. So this problem appears simple enough to solve with the use of a backreference at the end; here is some regex code below (it's in Java so mind the extra escape chars such as the \ before the "):
private static String seekerTwo = "(['\"])([a-zA-Z])([a-zA-Z0-9():;/`\\=\\.\\,\\- ]+)(\\1)";

This code will successfully deal with things such as:
"hello my name is bob"
'i live in bethnal green'

The trouble comes when I have a String like this:
"hello this seat 'may be taken' already"

Using the above regex on it will fail on the initial part upon encountering ' then it would continue and successfully match 'may be taken'... but this is obviously insufficient, I need the whole String to be matched.
What I'm thinking, is that I need a way to ignore the type of quotation mark, which was NOT matched in the very first group, by including it as a character in the character set of the 3rd group. However, I know of no way to do this. Is there some sort of sneaky NOT backreference function or something? Something I can use to reference the character in the 1st group that was NOT matched?? Or otherwise some kind of solution to my predicament?

A: Tim's solution works fairly well if you can use lookaround (which Java does support). But if you should find yourself using a language or tool that does not support lookaround, you could simply match both cases (double quoted strings and single quoted strings) separately:
"(\\"|[^"])*"|'(\\'|[^'])*'

matches each case separately, but returns either case as the whole match

HOWEVER
Both cases can fall prey to at least one eventuality. If you don't look closely, you may think there should be two matches in this excerpt:

He turned to get on his bike. "I'll see you later, when I'm done with all this" he said, looking back for a moment before starting his journey. As he entered the street, one of the city's trolleys collided with Mike's bicycle. "Oh my!" exclaimed an onlooker.

...but there are three matches, not two:
"I'll see you later, when I'm done with all this"
's trolleys collided with Mike'
"Oh my!"

and this excerpt contains only ONE match:

The fight wasn't over yet, though. "Hey!" yelled Bob. "What do you want?" I retorted. "I hate your guts!" "Why would I care?" "Because I love you!" "You do?" Bob paused for a moment before whispering "No, I couldn't love you!"

can you find that one? :D
't over yet, though. "Hey!" yelled Bob. "What do you want?" I retorted. "I hate your guts!" "Why would I care?" "Because I love you!" "You do?" Bob paused for a moment before whispering "No, I couldn'

I would recommend (if you are up for using lookaround), that you consider doing some extra checking (such as a positive lookbehind for whitespace or similar before the first quote) to make sure you don't match things like 's trolleys collided with Mike' - though I wouldn't put much money on any solution without a lot of testing first. Adding (?<=\s|^) to the beginning of either expression will avoid the above cases... i.e.:
(?<=\s|^)(["'])(?:\\.|(?!\1).)*\1                    #based on Tim's

or
(?<=\s|^)("(\\"|[^"])*"|'(\\'|[^'])*')               #based on my alternative

I'm not sure how efficient lookaround is compared to non-lookaround, so the two above may be equivalent, or one may be more efficient than the other (?)

A: This can be done using negative lookahead assertions. The following solution even takes into account that you could escape a quote inside a string:
(["'])(?:\\.|(?!\1).)*\1

Explanation:
(["'])    # Match and remember a quote.
(?:       # Either match...
 \\.      # an escaped character
|         # or
 (?!\1)   # (unless that character is identical to the quote character in \1)
 .        # any character
)*        # any number of times.
\1        # Match the corresponding quote.

This correctly matches "hello this seat 'may be taken' already" or "hello this seat \"may be taken\" already".
In Java, with all the backslashes:
Pattern regex = Pattern.compile(
    "([\"'])   # Match and remember a quote.\n" +
    "(?:       # Either match...\n" +
    " \\\\.    # an escaped character\n" +
    "|         # or\n" +
    " (?!\\1)  # (unless that character is identical to the matched quote char)\n" +
    " .        # any character\n" +
    ")*        # any number of times.\n" +
    "\\1       # Match the corresponding quote",
    Pattern.COMMENTS);


text:
Q: How can I skip the CellValueChanging state of DevExpress ColumnView? There are 2 distinct UI concept:  CellValueChanging vs CellValueChanged.
Quoted from DevExpress Documentation:

The CellValueChanging event is raised each time the edited value is being changed (the user types or deletes a character, chooses a value from the dropdown list, etc.).

On the other hand, CellValueChanged is raised when user had done cell editing by hitting enter or clicking outside of the active cell.
Now my problem is, I have a combobox type column, and I want to always skip the CellValueChanging and make the change final. The current behavior is when user select an item from the combobox, the change doesn't take effect immediately(e.g, the view will not be resorted as per the change). The change is not accepted until user hit enter or click outside of the cell.
---------------07/26/2013 2:25PM update---------------
Sorry that my previous question description misled everybody, so I'll rephrase it.
Here is the current behavior:
Pic1: beginning state. Rows are sorted alphabetically by Target.

Pic2: Change the 2nd row value from B to D

Pic3: After a single mouse left click on item D, the dropdown disappears and the cell value changes to D. However, the rows are not resorted

Pic4: After clicking outside the cell or hitting enter, the rows are resorted.

What I want to achieve is to skip the step in Pic3. In other word, I want any changes committed immediately, without having to make an extra kepboard or mouse click.
What I am showing here is a simplified example of my application. I can't move my CellValueChanged event handler logic to CellValueChanging or EditValueChanged because it would cause some errors.

A: You want to make some UI change once user edit the cell value, right? I think generally you have to give up handling the CellValueChanged event, but use the CellValueChanging Event instead:
pseudocode:
HandleCellValueChanging(object sender, CellValueChangingEventArgs e)
{
   // Get underlying object
   // and write the value direct into the object
   var rowObj = (YourType)gridview.GetRow(gridView.FocusedRowHandle);
   rowObj.TargetField = e.NewValue; // e.Value or e.NewValue, not sure

   // Then Do your UI effect
}

Another option is to use RepositoryItemEditor and handle the key-up and/or Mouse-up event instead.

A: If you want to to catch the moment when an end-user changes some value in gridview's cell editor (e.g. select item in combobox), please handle the EditValueChanged  event of a corresponding RepositoryItem. To immediately post this value (make the changes final), you need to call the PostEditor  method of a corresponding container:
repositoryItemComboBox1.EditValueChanged += repositoryItemComboBox1_EditValueChanged;
//...
void repositoryItemComboBox1_EditValueChanged(object sender, EventArgs e) {
    gridView1.PostEditor();
    // do something else if it needed
}

Related example: E3234 - How to update a row's style immediately after a an inplace editor's value is changed


text:
Q: CSS overflow character not pushing down  I have a
 called bigbox which contain a
called wrapper . The wrapper contain 2
 called textbox and checkbox. If the characters inside textbox overflow , it doesn't push the other wrapper below . How can I make the below wrapper go down ?
here is the jsfiddle : http://jsfiddle.net/WA63P/

<title>Page</title>

background background background background background background background background background background background background background background background background background background background background background background

A: .bigbox  {
    background-color: #F5E49C;
    color: #000;
    padding: 0 5px;
    width:280px;
    height:500px;
    position: absolute;
    text-align: center;content: "";display: block;
}

.box   {
    background-color: #272822;
    color: #9C5A3C;
    width:260px;
    margin-bottom: 10px;
    position: relative; top:10px;
}
.textbox
{
    background-color: #FFFFFF;
    color: #272822;
    min-height:100px;
    width:160px;
    text-align: left;
}
.checkbox
{
background-color: #FFFFFF;
width:50px;
position:absolute;
top:0px;
right:0px;
height:50px;
}

Remove the float:left in your .textbox to make it static, as static blocks automatically push the other static blocks down. Also remove the height to avoid setting a fixed height and allow it height to shrink/wrap automatically.
To position the checkbox as in your picture, you could use position:absolute; top:0px; right:0px;
Check the demo


text:
Q: Insert Authorization Header field with kingfisher lib in SwiftUI In swift I'm sending authorization token in header with KF like this:
imageView.kf.setImage(with: URL(string: imageUrl),
               placeholder: UIImage(named: placeholderImageName ?? ""),
                   options: [.requestModifier(MediaProxyHelperModifier.shared.modifier)]) //<- a singleton class that used to create a token

but I unable to find out the solution to pass the same in SwiftUI, Although KFImage is available for SwiftUI but with very limited option.
Or do we have any other option to achieve the same?
For a hack, I'm using it like this
extension Image {
    func getImage(url: String?, placeholder: String?) -> Self {
        let imageView = UIImageView()
        imageView.setImage(with: url, placeholderImageName: placeholder)
        if let image = imageView.image {
            return Image(uiImage: image)
        } else {
            return Image(placeholder ?? "")
        }
    }
}

but this solution is not so perfect, I mean very first time images are not loading but when refreshing the UI or revisit the same it started working.
IMAGE 1: first visited
IMAGE 2: tab changed or refreshed view


text:
Q: How to get the object property dynamically in the run time using the name of the property I have an object Structured like below.

Now what my intention is to get the Capitals/State value on the run time dynamically using the property name, for example.
var PropertyName='Capitals';
JSON.parse(ValueList)[0].PropertyName;

How to achieve this.
Thanks.

A: You can use bracket notation([]) for object selector
var PropertyName='Capitals';
JSON.parse(ValueList)[0][PropertyName];

For more about bracket notation : visit here


text:
Q: How to predict true eigenvalues from eigenvalues of trials? Averaging? Suppose I run code that estimates a set of complex eigenvalues for a matrix operator. Now suppose I re-run this code for $n$ trials, and because of noise, I estimate a new set of eigenvalues every trial.
What's the best predictor of the true spectrum? Is taking an arithmetic mean of the results too naive?
One issue is that we don't know whether the eigenvalues are properly ordered across trials, such that the $i$th eigenvalue for each trial corresponds to the same truth eigenvalue for all $i$. For now, I'm using a lexicographic sort to arrange the eigenvalues in each trial: first sorting by real part and then by imaginary.

A: One can sort eigenvalues by the complex magnitude (or modulus) in each trial, then compute average value.


text:
Q: How to delete a row and a column Libraries I use:
library(ggplot2)
library(dplyr)
library(statsr)

```{r}
factor_sc <- table(gss1$class, gss1$getahead)
factor_sc <- addmargins(factor_sc)
factor_sc
```

I write this and the output is:
               Hard Work Both Equally Luck Or Help Other   Sum
  Lower Class        1063          368          299     0  1730
  Working Class     10229         3221         1870     0 15320
  Middle Class       9914         3624         1612     0 15150
  Upper Class         701          265          100     0  1066
  No Class              0            0            0     0     0
  Sum               21907         7478         3881     0 33266

I want to run the chi-square inference on this data so that I want to remove Others and No class.
However, I already remove them using:
```{r}
gss1 <- gss %>%   filter(!is.na(getahead),
!is.na(class), class != "No Class", getahead !="Other")
```

Why do Other and No class appear in my table?

A: There is a little misunderstanding here. filter is used to remove lines of your dataset. What you want here is to change your class to NA when it is "No Class". mutate is what you need.
Try this code:
gss1 <- gss %>%
  mutate(class = ifelse(class=="No Class", NA, class),
         getahead = ifelse(getahead =="Other", NA, getahead )) %>%
  select(class, getahead) %>%
  table %>%
  chisq.test

It is possible that you need to use NA_character_ instead of NA.
You could just remove these lines and columns from factor_sc by writing this:
factor_sc[-5,-4] %>% chisq.test

A: Try simple df$column <- NULL for column and similar for row.
If the attempt is to achieve something bigger good luck.


text:
Q: Possesive determinant (its) What does the possesive determinant (its) refer to in the following sentence ,
The thief returned the painting back to Italy (its) rightful home .
I think (its) refers to Italy .. Any thoughts on that guys ?

A: I think your teacher is right after all. Try to replace (its) in your sentence (I added the comma):

Original sentence:
The thief returned the painting back to Italy, (its) rightful home.
Weird sentence:
The thief returned the painting back to Italy, Italy's rightful home.
Correct sentence (same meaning as the original):
The thief returned the painting back to Italy, the painting's rightful home.

Clearly they mean to say the painting's home is Italy (and not Italy's home is Italy). Therefore, its refers back to the painting.


text:
Q: Unable to find where my database file and connection string is located? i downloaded a demo application from http://code.msdn.microsoft.com/Authorization-based-aa2c0185/view/SourceCode
I run it on my Visual Studio and all worked fine. There is a database ASPNETDB.MDF in its App_Data folder which is used to store the user information or retrieve information for login purpose.
Now what I want is to change this database with another database in my SQL Server.
For that there can be two ways :

*

*Locate the connection string etc. for ASPNETDB and change them with my own database.

*or add this ASPNETDB file to SQL Server by attaching. But its showing error while attaching it.
Also if I exclude App_Data folder from project...Then even it works...
Where can find connection string for DB? I want to change the DB with mine own ?
Please Help
Thanks

A: It's using default connection string from machine.config:
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated  Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>

A: Go to the Web.debug.config file. There you will find comments noting how to wire up your config file. This will use config transforms so that when you build in debug mode, it will change your config file to override the machine defaults (which is what it is currently using). Just follow the comments and you should be good :)


text:
Q: ASP core + Angular solution doesn't launch in VS unless full clean/rebuild I am developing a web application using ASP Core 3.1 with web API controllers + an Angular 11 front-end.
Most of the time when I run the solution it doesn't launch properly. It opens the browser, which will show me a spinner and then will display the message:
{"StatusCode":500,"Message":"Internal Server Error."}
This is 'fixed' by doing a full clean and rebuild of the solution. The next launch will make the website pop up correctly. The launch after that will give me the error message again until I do another clean and rebuild.
This behavior started happening when the front-end was upgraded from Angular 9 to 11.
Also, might be a related symptom: launching the solution is extremely slow. It can take multiple minutes on a powerful machine before it shows anything in the browser, the website or the error message.
I have no idea where to start looking. Since the clean/rebuild-workaround 'works' it does not seem to be the code itself. However, I would love to find a solution because it slows down development.

A: More of a workaround than a solution:
This issue does not occur when debugging using the project launch configuration instead of the IIS Express launch configuration.
Since I switched I've had no more problems.


text:
Q: Chrome reports request with 304 status code response as cancelled When returning a 304 Not modified status code from an MVC controller:
public IActionResult NotModified()
{
    return StatusCode((int)HttpStatusCode.NotModified);
}

Chrome will mark the request as cancelled, the same happens when manipulating the response directly. I'm assuming this is behaviour of Chrome. As the text is displayed in red, this seems to be an error. Other browsers just show the 304 response.

Is this problematic and do I need to make any changes to have it displayed as a correct request?
When using https://httpstat.us/304 you can check this as well, it's not asp.net related.


text:
Q: Multiple versions of same assembly dll in one process/directory I'm trying to solve problem-related to the deployment of dll libraries, below assumptions:

*

*I have an application which loads plugins from dll-s.

*The product of my team is Wix installer that should install additional plugins to that application.

*We are using additional common dll libraries that are referenced in plugins from point 2 (for example Common.Forms). They may be used by
more than one plugin.

*There may be a gap between the release of plugin A and B, both of them may refer to a different version of common libraries.

*Common libraries may refer to dll-s of Base application. Base application is not strongly named.

Issue:
If we try to install plugin A and then B, then the common library will be replaced with never version, which may be incompatible with plugin A. As a result plugin A won't work.
What I already tried

*

*GAC - version control based on the global cache, issues:

*

*I cannot sign the Base application, nor load assemblies dynamically, so
solution from:
How to fix "Referenced assembly does not have a strong name" error?
Won't work

*Fody costura - embedding common libraries in plugins

*

*The prototype works as expected but we found two issues:

*

*Costura will work only if dll was not found by Base Application, so if there is dll file that was installed with the previous plugin, and file exists in root directory - then it will be loaded instead of expected embedded version. That may be solved by renaming Libraries from given version to avoid conflicts.

*This will require to add Cody fostura to all plugins and will require a lot of manual work with the setup.

I'm looking for an alternative approach to solve that issue, any help appreciated.


text:
Q: how can a function return an lvalue in c? i read in The Linux Programming Interface 29-2 Threads and errno the next :

On Linux, a thread-specific errno is achieved in a similar manner to most other UNIX implementations: errno is defined as a macro that expands into a function call returning a modifiable lvalue that is distinct for each thread.

and i wondered how can a function return a modifiable lvalue.

A: It is the macro that "returns" the modifiable lvalue, not the function call itself. The function returns a pointer and the macro dereferences this pointer. For example, errno.h of the glibc source code defines the macro errno like this:
# define errno (*__errno_location ())

This wording is a bit misleading:

errno is defined as a macro that expands into a function call returning a modifiable lvalue that is distinct for each thread.

A more accurate wording would be:

errno is defined as a macro that expands into an expression that contains a function call. This expression evaluates to a modifiable lvalue that is distinct for each thread.


text:
Q: Can I use this USB-to-UART converter with a MCU? My project is as follows:

I need to choose an USB-to-UART converter to be able to communicate with an MCU from my PC through a serial interface. I was thiking of using this part : FT234XD-R (datasheet).
I have one question: Can this chip be interfaced with a 3.3 V MCU?
In the datasheet they give application examples: USB-to-RS232, USB-to-RS422 and USB-to-RS485 converters, but they do not give a USB-to-UART converter example. I need to make sure that the voltage levels of the RXD/TXD pins can be handled by my MCU, for example I know that RS232, RS422 and RS485 voltage levels cannot be handled by a 3.3 V MCU.

A: It's safe to use with an MCU directly. This is what the chip is designed for.
Apply 3.3V to VCCIO for 3V3 logic, or use the on-chip regulator by shorting the 3.3VOUT pin (pin-3) to VCCIO pin (Don't forget to place a decoupling capacitor to this pin). You can use the on-chip 3V3 regulator to supply your MCU and externals if the total consumption is less than 50 mA.
If you want to convert the logic-level RX/TX signals to RS-232, -422, or -485 then use an extra transceiver such as MAX232, MAX485, etc.


text:
Q: maven uber war (cargo-maven2-plugin) merging only the first  element I am trying to merge two wars and thereby the web.xml files using the maven uber war cargo-maven2-plugin. The merge on all the tags (filters, servlet) happens as desired, but for <context-param> it's only merging the first element defined in the web.xml on R.H.S. I want to keep all context-param on the web.xml on L.H.S merge all the <context.param> elements defined in my web.xml on R.H.S. Any help would be appreciated. Here is my code
web.xml on R.H.S
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- ** SPRING ** -->
    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>com.myorg.context.MyApplicationContextInitializer</param-value>
    </context-param>

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:conf/spring/*.xml</param-value>
    </context-param>

   <context-param>
        <description>Location(s) to search for the Log4J config file</description>
        <param-name>log4jConfigLocation</param-name>
        <param-value>file:/dir/path/log4j.xml /WEB-INF/log4j.xml</param-value>
    </context-param>

    <context-param>
        <description>
            Boolean flag indicating whether internal Log4J debugging statements should be written. Log4J
            will write debugging messages to System.out and error messages to System.err.
        </description>
        <param-name>log4jConfigDebug</param-name>
        <param-value>false</param-value>
    </context-param>

**

*

*merge.xml

**
    <?xml version="1.0"?>
<uberwar>
    <wars>
        <war>org.forgerock.openam:openam-server</war>
        <war>com.myorg.xyz.addons:my-sso-addons-web</war>
    </wars>

     <merges>
        <merge>
            <type>web.xml</type>
            <parameters>
                <default>

                    <!-- Preserve execution order of filter-mappings -->
                    <tag name="context-param">
                        <strategy name="ChooseByName">
                            <default>
                                <strategy name="Preserve" />
                            </default>
                            <choice name="contextInitializerClasses">
                                <strategy name="Overwrite" />
                            </choice>
                            <choice name="contextConfigLocation">
                                 <strategy name="Overwrite" />
                            </choice>
                            <choice name="log4jConfigLocation">
                                <strategy name="Overwrite" />
                            </choice>
                        </strategy>
                    </tag>

                    <tag name="filter-mapping">
                        <strategy name="Preserve"/>
                    </tag>

                </default>
            </parameters>
        </merge>
    </merges>
</uberwar>

pom.xml
  <!-- other entries are here -->
<packaging>uberwar</packaging>

    <build>
        <plugins>
            <!-- merges openam-server with openam-addons-web-common -->
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <!-- merges the wars -->
                    <descriptor>src/assembly/merge.xml</descriptor>
                    <configuration>
                        <type>existing</type>
                        <home>${jboss.home}/aclsso</home>
                    </configuration>
                    <deployer>
                        <type>installed</type>
                    </deployer>
                    <deployables>
                        <deployable>
                            <groupId>${project.groupId}</groupId>
                            <artifactId>${project.artifactId}</artifactId>
                            <type>war</type>
                            <properties>
                                <context>openam</context>
                            </properties>
                        </deployable>
                    </deployables>
                </configuration>
            </plugin>

        </plugins>
    </build>

A: Well, the problem in this particular case was the difference in the xmlns version, and schema location at the top of web.xml. The first war had version=2.4, while the second one had version=3.0. Keeping both the web.xml schemas in sync by using the following resolved the issue (I have no idea why it merged the filter, servlet tags, and failed on merging all the context-param tags though).
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

I


text:
Q: Parsing a text file in C I am making a program that displays the element of your choice from the periodic table using a file. I try to compare a string with a line of the  file, but it doesn't work. How can I fix the comparison?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char * line = NULL;
    char name_element[1000];
    size_t len=0;
    ssize_t read;

    FILE*table;
    table=fopen("Data.txt","r");

    printf("Please enter the element you are looking for:\n");
    scanf("%s",name_element);

    while ((read = getline(&line, &len, table))!=-1){
        i=strcmp(name_element,line);
        if  (strcmp(line,name_element)==0) {
            while ((read = getline(&line, &len, table))!=-1) {
                if(strcmp(line,"////")!=0) {
                    printf("%s", line);
                } else {
                    break;
                }
            }
        }
    }
    fclose(table);
    return 0;
}

A: In the future, you may want to include the input file, just in case that is part of the problem.
Assuming that won't cause any problems, strncmp() is the way to go. The format is strncmp(str1, str2, n) where n is the number of characters you want to compare.

A: You are using getline() which stores the '\n' that's why strcmp() is returning a non-zero value. Because scanf() doesn't include the '\n'.
Try
size_t length = sizeof(name_element);
getline(&name_element, &length, stdin);

and they should compare equal, but that will not solve the problem.
You need to remove the trailing '\n' from the line read from the file, because the last line might not contain the '\n' or use this solution which is also good because you may know the string length if you use the "%n" scanf() specifier.
Also, please check the return value from scanf() if you want your code to be robust.


text:
Q: Upgrade Tailwindcss from 2 to 3 I followed up the migration guideline but I have a problem with configuration.
Warning
(4:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin before Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
Warning
(16:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin before Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
Warning
(2:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin before Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
postcss.config.js
module.exports = {
  plugins: {
    "postcss-import": {},
    "tailwindcss/nesting": {},
    tailwindcss: {},
    autoprefixer: {},
    ...(process.env.NODE_ENV === "production" ? { cssnano: {} } : {}),
  },
};

tailwind.config.js
module.exports = {
  content: ["./public/index.html", "./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
    zIndex: {
      max: 9999,
    },
  },
  plugins: [],
};

package.json
   "scripts": {
    "start": "react-scripts start",
    "build:dev": "env-cmd -f .env.dev react-scripts build",
    "build:test": "env-cmd -f .env.test react-scripts build",
    "deploy": "npm install -g serve & npm install & npm run build:dev & serve -s build -p 9999",
    "test": "npm test",
  },

and also I have a problem with css files that includes sass like syntax
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

asset static/js/bundle.js 2.7 MiB [emitted] (name: main) 1 related asset
asset index.html 1.93 KiB [emitted]
asset asset-manifest.json 190 bytes [emitted]
cached modules 2.41 MiB [cached] 475 modules
runtime modules 28.5 KiB 14 modules
javascript modules 56.2 KiB
  modules by path ./src/components/ 11 KiB
    modules with warnings 6.54 KiB [warnings]
      ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-load
er/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/compo
nents/Header/header.css 1.67 KiB [built] [1 warning]

Any help will be appreciated.
Thanks
UPDATE:
I renamed files from css to scss and it works.


text:
Q: How to reset panel look and feel in java?
Possible Duplicate:
Panel losing color

When I click on the button that activates the file chooser, and add the resulting file the panel color disappears couse using uimanager to display file chooser as windows chooser.
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;

@SuppressWarnings("serial")
public class pan extends JPanel implements DropTargetListener {

    private DefaultListModel listModel = new DefaultListModel();
    private JButton addbutton;
    private JButton removebutton;
    private JButton selectbutton;
    private JButton lockbutton;
    private JButton unlockbutton;

    /**
     * Create the panel.
     */
    public pan() {
        setLayout(null);
        addbutton = new JButton("New button");
        addbutton.setBounds(10, 10, 90, 100);
        addbutton.addActionListener(new Action());
        add(addbutton);

        removebutton = new JButton("New button");
        removebutton.setBounds(110, 10, 90, 100);
        add(removebutton);

        selectbutton = new JButton("New button");
        selectbutton.setBounds(210, 10, 90, 100);
        add(selectbutton);

        lockbutton = new JButton("New button");
        lockbutton.setBounds(310, 10, 90, 100);
        add(lockbutton);

        unlockbutton = new JButton("New button");
        unlockbutton.setBounds(410, 10, 90, 100);
        add(unlockbutton);

        JLabel headerLabel = new JLabel("New label");
        headerLabel.setBorder(new BevelBorder(BevelBorder.RAISED,
            Color.LIGHT_GRAY, Color.GRAY, null, null));
        headerLabel.setUI(new ModifLabelUI());
        headerLabel.setBounds(10, 120, 635, 30);
        add(headerLabel);
    }

    class Action implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==addbutton){
                JFileChooser filechooser=new JFileChooser();
                filechooser.setMultiSelectionEnabled(true);
                try {
    UIManager.setLookAndFeel(UIManager
            .getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (UnsupportedLookAndFeelException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

                filechooser.updateUI();
                filechooser.showOpenDialog(new pan());
                File files=filechooser.getSelectedFile();
                listModel.addElement(files);
        }
    }
}

If you remove UImanger the problem gone

A: Per The documentation ... You might want to make sure the UI manager is first set to use the look and feel you want to use ...
EDIT For a concrete example @see This Post
public static void main(String[] args) {
    try {
            // Set System L&F
        UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
    }
    catch (UnsupportedLookAndFeelException e) {
       // handle exception
    }
    catch (ClassNotFoundException e) {
       // handle exception
    }
    catch (InstantiationException e) {
       // handle exception
    }
    catch (IllegalAccessException e) {
       // handle exception
    }

    new SwingApplication(); //Create and show the GUI.
}


text:
Q: Difference between "I'm home" vs "I'm at home" What's the difference between these two sentences? And which one's grammatically correct?

A: In the literal sense, both simply tell someone where you are. These would generally be used in slightly different contexts though.
If you are at home, and have been there for some time, and someone is asking where you are, you would respond "I'm at home".
You would use "I'm home" more to indicate that you just arrived there. Maybe to someone who was expecting you or wanted you to let them know you made it home safely.


text:
Q: Print Javascript function in htm php page this  is my javascript code:

i m print the result value in html tag like:

bt its not showing the value..!!

A: The "result" variable is local to that function.  You cant use it in the document like that.
Delete those 4 lines in your HTML and just add this instead:

Do you get the desired result?  If not you'll need to better explain what "validateCreditCard" is.


text:
Q: Effect on query time by adding indexes I am trying to get a query time down. I am using codeigniter ... queries where the records in the table are 100 or less ... the query is taking 2 millisec. One query thats getting 1 record from the table and has 2 where statement is taking 35 msec ... the table has 5000 records ...
        $this->db -> where ('DealSiteId', $q1['DealSiteId'] );
        $this->db -> where ('DealUniqueId',$q1['DealUniqueId'] );

        $dup= $this-> db -> get ('deals');
        $dup1 = $dup -> result();

      if (count($dup1)!=0){

            $data['error']="Duplicate, This deal already exists. ";
            return $data;
        }

I add indexes on both fields in where clause ... index type BTREE. Any faster way to check duplicates?

A: If you created a compound index containing both fields, your query could use a single index making it more efficient.

A: Did you add individual indices on both fields or one combined one?
Either way, you should test your query directly in mysql (or something like phpMyAdmin) and use EXPLAIN to see what is happening: http://dev.mysql.com/doc/refman/5.5/en/explain.html
In you specific case, you could perhaps add a unique index / constraint for the combination of DealSiteId and DealUniqueId. That would look something like (untested, just to give you an idea...):
ALTER TABLE `deals` ADD UNIQUE `some_name` ( `DealSiteId` , `DealUniqueId` );

A: Any easy way to determine if your query is as efficient as possible is to use MySQL EXPLAIN. To do this within CodeIgniter, you can do the following:
$this->db->where('DealSiteId', $q1['DealSiteId'] );
$this->db->where('DealUniqueId',$q1['DealUniqueId'] );

$result = $this->db->get('deals');
echo $this->db->last_query();

Take that printed result and run it against a MySQL command: EXPLAIN <your query>, this will tell you information about that query which will be useful. i.e. If it's using indexes, how many rows it's scanning, if it's using sort, creating temporary tables, etc. From there you can optimize your query to get the best result.


text:
Q: How to Bind a DropDownList to a FormView I'm trying to bind a DropDownlist with some Categories in a FormView to insert Products
I'm Using ItemType="Product" in the FormView.
The Textboxes are binded this way for the product description: Text="<%# BindItem.Name%>"
But I can't seem to bind the DropDownList. I have seen solutions using the SelectedValue attribute but that doesn't even shows up as an attribute for my DropDownList in the aspx page.
In my code behind there is the InsertMethod for the FormView:
Product item = new Product();

TryUpdateModel(item);

if (ModelState.IsValid)
  {
     ProductsBLL prod = new ProductsBLL();
     prod.Insert(item);
  }

The aspx page is a standard webform:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Marcar Férias

            <asp:UpdatePanel ID="uppModal" runat="server">
                <ContentTemplate>
                    <asp:FormView runat="server" CssClass="table" ID="frmViewProdutos" DefaultMode="Insert" ItemType="NovoGRH.ENTIDADES.Produtos" DataKeyNames="Id" InsertMethod="frmViewProdutos_InsertItem">
                        <InsertItemTemplate>

                                <asp:Label AssociatedControlID="ddlExercicio" runat="server">Categoria: </asp:Label>
                                <asp:DropDownList ID="ddlCategoria" runat="server" DataValueField="Id" DataTextField="Descricao" SelectMethod="CarregarCategorias">
                                </asp:DropDownList>

                                <asp:Label AssociatedControlID="txtNomeProduto" runat="server">Nome: </asp:Label>
                                <asp:TextBox ID="txtNomeProduto" CssClass="form-control" Text="<%# BindItem.NomeProduto%>" runat="server" Width="80" ></asp:TextBox>

                                <asp:Button ID="btnSalvarCrud" Text="Salvar" runat="server" CausesValidation="true" CommandName="Insert" CssClass="btn btn-success" />

                            <asp:ValidationSummary runat="server" ID="validaForm" DisplayMode="BulletList" ShowSummary="true" />

                        </InsertItemTemplate>

                    </asp:FormView>

                </ContentTemplate>
            </asp:UpdatePanel>

Everything is working OK. Except that I can't make it work for the CategoryID stored in the DropDownList


text:
Q: JavaScript - scrollIntoView() only works in Firefox I'm trying to scrollIntoView() on a SVG element. It works on Firefox as intended but on Chrome and Edge it scrolls down too far or some other place that is wrong.
<g id="clust1" class="cluster">
    <title>cluster_Legend</title>
    <polygon fill="none" stroke="black" points="8,-8 8,-59 2503,-59 2503,-8 8,-8"/>
    <text text-anchor="middle" x="1255.5" y="-47" font-family="Times New Roman,serif" font-size="10.00">Node color legend </text>
</g>

I have a variable selectedCluster with the selected <g> element. I call scrollIntoView() on the <polygon> nested within the <g> element.
var polygon = selectedCluster.querySelector("polygon");
polygon.scrollIntoView({behavior: "smooth"});

How do I make it so that it scrolls correctly in Chrome and Edge?
Thanks


text:
Q: Can't get email address using facebook sdk for IOS and graph api for facebook I am trying to get the email address from a user. He logs in, I ask permission to access email and he chooses ok. Then I use the graph API from facebook to access the email address.

- (void) fbDidLogin
{
  btnLogin.isLoggedIn = TRUE;
  [btnLogin updateImage];

  NSString *theURL =
  [ [NSString stringWithFormat:
    @"https://graph.facebook.com/me?access_token=%@", facebook.accessToken
    ]stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding
  ];

  NSLog(@"%@", theURL);
  [facebook requestWithGraphPath: theURL andDelegate: self];
}

...

- (void)request:(FBRequest*)request didLoadRawResponse:(NSData*)data
{
  NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
  NSLog(@"%@", response);
  [response release];
}

This is how i get the information:

- (void) request:(FBRequest*)request didLoad:(id)result
{
  if ([result isKindOfClass:[NSDictionary class]])
  {
    NSString *email = [result objectForKey: @"email"];
    NSString *name = [result objectForKey: @"name"];
    NSString *facebookId = [result objectForKey: @"id"];
    //...
  }
}

It gives me only this string: { id = "https://graph.facebook.com/me"; } What did I do wrong?

A: I found answer:
 NSArray *permissions = [[NSArray alloc] initWithObjects:@"user_likes",@"offline_access",@"read_stream",@"publish_stream",@"email",nil];

  [facebook requestWithGraphPath:@"me"andParams:params andDelegate:self];
  -(void)facebookLoginScreen:(NSDictionary *)result
   {
        NSLog(%@,[result objectForKey:@"email"]);
   }

A: Ah nevermind, it works. I had to use @"me" in [facebook requestWithGraphPath: @"me" andDelegate: self]; instead of the URL.


text:
Q: How to find out "the right" IP address? I have a problem with InetAddress.getLocalHost().getHostAddress(). It works correctly on most machines, but it fails on one where there are more IP addresses available (in this case "the wrong" address belongs to VMware network adapter). I need the address to put it into a message (which then is used on the server as an address where a response should be sent).
I know that I may use NetworkInterface.getNetworkInterfaces() to get all network interfaces but how I may programatically find the right one which is later visible for the server? In my particular case both clients and the server are located inside the same corporate network.

A: If all machines are in the same network and this network has its IP range, you may check if IP is in this range. Usually vmware network adapters have IPs in 192.168.0.x subnet - if your corporate range is different, then it should be enough.

A: Maybe the following class to help with IP
public enum IpAddressHelper
{

    X_FORWARDED_FOR("X-Forwarded-For"),
    PROXY_CLIENT_IP("Proxy-Client-IP"),
    WL_PROXY_CLIENT_IP("WL-Proxy-Client-IP"),
    HTTP_CLIENT_IP("HTTP_CLIENT_IP"),
    HTTP_X_FORWARDED_FOR("HTTP_X_FORWARDED_FOR");

    private static final Logger LOGGER = LoggerFactory.getLogger(IpAddressHelper.class);
    private static final String REMOTE_ADDR = "REMOTE_ADDR";
    private String key;

    /**
     * @param key
     */
    IpAddressHelper(String key)
    {
        this.key = key;
    }

    /**
     * @return the key
     */
    public String getKey()
    {
        return key;
    }

    public static String getClientIpAddr(HttpServletRequest request)
    {

        String ip = null;
        for (IpAddressHelper header : IpAddressHelper.values())
        {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = request.getHeader(header.getKey());
                LOGGER.info("tried:" + header);
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String getClientIpAddr(Map<String, String> requestHeaders)
    {
        String ip = null;
        for (IpAddressHelper header : IpAddressHelper.values())
        {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = requestHeaders.get(header.getKey());
                LOGGER.info("tried:" + header);
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = requestHeaders.get(REMOTE_ADDR);
        }

        return ip;
    }
}


text:
Q: To import all objects in multiple nested foreign key relationships efficiently in django Is there an effective way to get all dictionary objects that correspond to the product?
This is my django model
class Product(models.Model):
    ...

class Ingredient(models.Model):
    product = FK(Product)
    middle = FK(Middle)
    ...

class Middle(models.Model):
    dictionary = FK(Dictionary)
    ...

class Dictionary(models.Model):
    ...

The way I did it.
product = Product.objects.get(id=1)
ingredients = ProductIngredient.objects.filter(product=product)
middles = ProductMiddle.objects.filter(ingredient__in=ingredients)
dictionaries = ProductDictionary.objects.filter(middle__in=middles)

but I want
dictionaries = product.ingredient.middle.dictionary.all() (?)
# AttributeError: 'RelatedManager' object has no attribute 'middle'

Or
Is there a better way?
Is there a way to import this data with fewer queries?

A: I think what you want is
dictionaries = Dictionary.objects.filter(middle__ingredient__product_id=1)
The names could be wrong, depending on the related_name you defined on each FK.


text:
Q: Where to keep git submodules inside of a go project? I want to add a submodule to my go project.
The submodule will contain some .proto files and some go files. I will use protos to generate grpc-gateway files using my Makefile, which will have the same package as the go files in the repo. The repo which contains these protos is not mine, and others are developing it. I won't commit these gateway files generated.
Is there any specific structure for such files in golang projects? Should I keep them in pkg directory?
I have three folders of build, configs, templates currently in my project.

A: You can keep them in the pkg directory,  maybe at pkg/proto.
The package names for the generated go files will be present in the go_package attribute in the .proto file. For example,
option go_package = "external/api/messages";

Then after compilation, the package name inside the go file would be
package messages

This is the folder structure
$ tree
.
`-- pkg
    `-- proto
        `-- messages
            |-- messages.pb.go
            `-- messages.proto

In order to import it, you'll have to update your go.mod file
replace external/api v0.0.0 => ./pkg/proto

afterwards, you can import it using
import (
    "external/api/messages"
)

A: If you want to keep your project dependencies inside your project then you better keep them inside a vendor directory.
But usually I use go modules for that.
Also might be useful for you:
https://github.com/golang-standards/project-layout


text:
Q: Why is SQL Server 2012 faster than MongoDB for this query I am doing some performance tests between SQL Server 2012 and MongoDB 2.4.9. I have done a little research online and found many comparisons that compare only insert performance between these two databases. I am only interested in selectperformance without indexes. I setup a very simple test. Here are the specs
SQL Server setup

*

*Setup SQL Server with only one integer field.

*Insert 1 million random integers

MongoDB setup

*

*Has two fields _id and id1

*Insert 1 million random integers into id1 field

When I inserted the numbers they are the exact same numbers going into both databases. The random numbers range from 1 to 1000.
SQL Server query
select id from a101 where id > 995

MongoDB query
var q = Query.GT("id1", 995);
foreach (var i in collection.Find(q))
{
     values.Add(i.id1);
}

Results:

*

*SQL Server: 192 ms

*MongoDB: 1109 ms

For my schema I will not need any joins and will have only denormalized data - this is why I considered MongoDB. I expected mongoDB to be many times faster than SQL Server after reading the benchmarks online. Is there something I may be doing wrong? Again, I wanted to test without indexes.

A: MongoDB is likely five times slower in this case because it needs to read and output five times as much data.
One row in your SQL table is just 4 byte. But in MongoDB it is a 4 byte integer plus a 12 byte ObjectId. Also, the field-names are part of each individual document. The strings _id and id1 are part of each document you retrieve, so some additional bytes are added.
And this is just the actual payload. When you look at BSONSpec.org you can see that your document is represented by:

*

*4 byte for a 32bit integer which is the total length of the document

*1 byte 0x01 for "now comes an ObjectId"

*4 bytes for the null-terminated string _id

*12 bytes for the ObjectId

*1 byte 0x10 for "now comes a 32bit integer" (smallest integer there is)

*4 bytes for the null-terminated string id1

*4 bytes for the 32bit integer

*1 trailing 0x00 which marks the end of the document

which is a total of 31 byte.


text:
Q: Electron.build auto-updater - when does it download updates? I've managed to successfully implement the auto-update feature for Windows and Mac for my application using https://www.electron.build/auto-update.
I wonder whether the download continues when the users closes the application (and, obviously, an update has been found)? Or does the application need to stay open until the the update has been completely downloaded?


text:
Q: Python: how to get the first file in directory? So I want to grab the first file under a directory in Python. I know I can do like this:
first_file = [join(path, f) for f in os.listdir(path) if isfile(join(path, f))][0]

But it's slow. Is there any better solution? Thanks!

A: You can use next():
first_file = next(join(path, f) for f in os.listdir(path) if isfile(join(path, f)))

Note that if there are no files in the directory it would throw StopIteration exception. Either handle it, or provide a default value:
first_file = next((join(path, f) for f in os.listdir(path) if isfile(join(path, f))),
                  "default value here")


text:
Q: No module names 'src' when importing from parent folder in jupyter notebook I have the following folder structure in my project
my_project
  notebook
    |-- some_notebook.ipynb
  src
    |-- preprocess
        |-- __init__.py
        |-- some_processing.py
    __init__.py

Now, inside some_notebook.ipynb I simply want to get the methods from some_processing.py. Now we I run
from src.preprocess import some_processing

from some_notebook.ipynb it always throws
ModuleNotFoundError: No module named 'src'

I found multiple questions regarding this and played around with sys.path.append(<path-to-src>). But I couldn't solve it. Which path do I provide? Something like ../src didnt work?
I checked for example the AlphaFold project from DeepMind and they are using it also with this structure. I tried to replicate exactly like they did.
How can I solve this? Which path do I provide in sys.path.append()?
I appreciate any help!

A: I found the answer. Running
sys.path.insert(1, os.path.join(sys.path[0], '../src'))

made it possible to import anything from parent module src.


text:
Q: Prove formulae using natural style
Prove: $((P ⇒ R) ∧ (Q ⇒ R)) ⇔ ((P ∨ Q) ⇒ R)$
Notation: $P[x]$ and $f[x$] for "$P$ applied to $x$" and "$f$ applied to $x$", instead of $P(x)$ and $f(x)$.

So far I tried the following:
Direction $=>$

*

*Assume ( (P => R)^ (Q => R) ) (1) and Prove ( (P v Q)=> R )

*From (1) we get (P => R)(2) and (Q => R)(3)

*From (2) we get P (4)  From (3) we get Q (5)
Direction $<=$

*

*Assume ( (P v Q) => R ) (6) and Prove ( (P => R) ^ (Q => R) )

*From (6) by material implication we get ~(P v Q) v R (7)

*We can rewrite (7) as (~P ^ ~Q) v R (8) by negation rules

*We can retwrite (8) as (~P v R) ^ (~Q v R) (9) by distributivity laws

*We can rewrite (9) as (P => R ) ^ (Q => R) by material implication.

I got stuck solving first direction $=>$. What should I do next?
Regarding the other direction $<=$, is there any other way to do it without rewriting?

Thanks.


text:
Q: MediaCapture failing intermittently (RecordState - The op is invalid) I'm using MediaCapture API to record audio in my Windows Phone 8.1 RT app. The audio recording works fine, but the API intermittently throws System.Exception with the following message:
RecordState System.Exception: The op is invalid. at the statement
Windows.Media.Capture.MediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile encodingProfile, IStorageFile file)
I haven't been able to find more about this error cause. Can anyone point in some direction?

A: Found the reason for this exception. I was calling MediaCapture.StartRecordToStorageFileAsync() repeatedly, even when the MediaCapture object was already recording audio. I had to make sure I call MediaCapture.StopRecordAsync() before calling StartRecordToStorageFileAsync() so that the state of the recording object is not violated.
Similarly, multiple calls to StopRecordAsync() would throw a similar exception.

A: I experienced the same problem, as you said calling multiple times StartRecordToStorageFileAsync() without stopping the previous captures with StopRecordAsync() produces this situation. I had to make sure I was not triggering StartRecordToStorageFileAsync()everytime the timer I was using was activated, I used this:
            if (_PrimeraVez)
            {
                CameraRecord(); //My own method
                _PrimeraVez = false;
            }

Glad you found the solution yourself.


text:
Q: If user is equal to string So I am trying to set a privilege to certain people on the system, showing them an extra button to delete a certain event. This is the start of the if statement:
{% if user == occurrence.created_by  %}

This works fine and I do need this but I also need an OR statement which compares the user to strings, for example user == "admin".
I get nothing and I know the string is right because I printed out {{ occurrence.created_by }} and just used that string that produces, so what is the difference between using {{occurrence.created_by}} and "admin"
Any ideas?

A: Comparing user and occurrence.created_by works because they are both user instances. Comparing user and "Admin" will always be False, because one is a user and the other is a string.
You can compare "admin" to user.username.
{% if user == occurrence.created_by or user.username == "admin" %}

However, a better approach might be to use permissions.
{% if user == occurrence.created_by or perms.my_app.delete_occurrence %}


text:
Q: Execute Python Script from outside sources I have a python script hosted in github gist for testing purpose.
It simply contain 1 line of code.
print "This line will be printed."

I name it print.py, and here is a link to it as Raw text.

I'm wondering if we can executing it without having to download it to our local VM and then run it.
Is it possible to execute it directly base on the link to it ?

A: If you mean execute it from the command line (e.g. bash), I'd grab the contents of the page using curl and pipe the output to python.
curl "URL" -s -N | python

In your case:
$ curl https://gist.githubusercontent.com/bheng/36ead076b79595639124fa783557d419/raw/e9ee46a841fd21fc1e29bdd8be1b0300fc091f72/print.py -s -N | python
This line will be printed.


text:
Q: `RUID`, `EUID` and `setuid bit` I'm trying to understand RUID, EUID and setuid bit stuff. Here are my questions in the topic:

*

*In the How to start (or find) a process with RUID different from EUID? question the Gilles answer states:

It's only setuid executables that start with the effective UID set to
  the owner of the executable while the real UID remains the real UID of
  the invoking process

What does it mean the invoking process? If I'm right that in the case of e.g. passwd command run by say Bill user with id = 1000 the invoking process mentioned above will be just the Bill user?

*Am I right that when we take some action on a file inside an executable (e.g. write to that file) the system checks if it is allowed to do that by checking EUID of that executable with the file permissions?
For e.g. we have executable abc (setuid bit not set) which writes some data to 1.txt file with -rw-r--r-- permissions. Bill user (UID=1000) runs abc. Now because abc EUID=1000 (no setuid bit set) and the 1.txt permissions is -rw-r--r-- the write operation is refused by the system because EUID=1000!=0?

A: 1) It says the invoking process because the passwd command in your example is launched by a shell (bash, csh, etc) or a program running with your ID.
2) Yes, you're right. Permissions arch checked against the process effective ID.


text:
Q: pySerial : Can't read data more than 8 characters I use pyserial to write and read between two Raspberry pi(s) via UART
Raspberry pi 1 : send data to Raspberry pi 2
    while 1:
        ser=serial.Serial('/dev/ttyAMA0')
        if not ser.isOpen():
            ser.open()
        msg=raw_input('RPi 1 send:')
        ser.write(msg)
        ser.close()

Raspberry pi 2 : receive data from Raspberry pi 1
    while 1:
        ser=serial.Serial('/dev/ttyAMA0' ,timeout=0)
        if not ser.isOpen():
            ser.open()
        data=ser.read(1024)
        if data.__len__()>0:
            print 'RPi 2 receive:',data
        ser.close()

I run both code.
and send data
    RPi 1 send : Hello

and receive data
    RPi 2 receive : Hello

But if RPi 1 send data more than 8 characters
for example
    RPi 1 send : Hello Raspberry pi NO.2

The result is
    RPi 2 receive: Hello Ra
    RPi 2 receive: spberry
    RPi 2 receive: pi NO.2

This is my problem. Because I want it to receive like this
(RPi 2 receive: Hello Raspberry pi NO.2) #show only one line.
and if send (more 8 char) again, it show in a new line.
What code to join it in one line? or other way to do this? :)

A: When reading using ser.read, you're just reading what is already in the
buffer, or waiting for chars to arrive in the buffer. The size you specify
is a maximum number of chars to receive, but it can be much less as you
experienced.
You have 2 easy solutions:

*

*use ser.readline and put a terminator in your strings (like \n)

*if you know in advance how many characters to read, repeat reading
until you've received them all

In both cases, specify a timeout (for example 1 second) when opening
the serial line, to get back control on your code if the remote end
doesn't send anything for whatever reason.
Hope it helps.

A: I like to do this
sender.py
delim = "\x00"
ser.write(msg+delim)

reciever.py
delim = "\x00"
recvd = "".join(iter(lambda:ser.read(1),delim))
print recvd


text:
Q: Specific ID exception laravel 5.4/5.5 I'm working on a functionality where only a user with the ID number 3 can bet if the match is 1 minute away from starting, it's a success, but now those matches that has the status "Open" is not allowed to place bets. here is the code:
public function *addMatchBet*(Request $request){
    $rules = [
    'matchid' => 'required|integer|exists:matches,id',
    'teamid' => 'required|integer|exists:teams,id',
    'bet_amount' => 'required|integer|min:100'
    ];
    $validation = \**Validator**::make($request->all(), $rules);
    if ($validation->passes()) {
        $user = \**Auth**::user();
        $match = \App\**Match**::find($request->matchid);
        $team = \App\**Team**::find($request->teamid);

        if(!in_array($team->id, [$match->team_a, $match->team_b])) {
            return [
            'success' => false,
            'errors' => [
            'bet' => ['Match teams have been updated! Please refresh
            page and try again.']
            ]
            ];
        }
        if($match && $match->status == 'open') {
            $betCount = $user->bets
            ->where('match_id', $request->matchid)
            ->count();

            if($match->isClosing(0)) {
                return [
                'success' => false,
                'errors' => [
                'bet' => ['Could no longer bet. This match is now
                starting!']
                ]
                ];
            }

        }

    }
}

Any ideas anyone? TYIA

A: I've found a solution, this was the code:
  if($match && $match->isClosing(0)) {

                        if($user->id == 3){
                            $betCount = $user->bets
                    ->where('match_id', $request->matchid)
                    ->count();
                        }
                    else{
                        return [
                            'success' => false,
                            'errors' => [
                                'bet' => ['Could no longer bet. This match is now starting!']
                            ]
                        ];
                    }
                }


text:
Q: In Java, what is the simplest way to create an SSLContext with just a PEM file? I used LetsEncrypt's CertBot to generate PEM files for free.  In other languages it is easy to start an HTTPS server using just a couple lines of code and the PEM/key files.  The solutions I have found so far in java are overly complex and I'm looking for something simpler.

*

*I do not want to use java's command-line "keytool".  I just want to drag and drop my PEM/key files into my eclipse, and programatically start up an HTTPS server using an SSLContext.

*I do not want to include massive external libraries like BouncyCastle. See the following link for a supposed solution using BouncyCastle:  How to build a SSLSocketFactory from PEM certificate and key without converting to keystore?
Is there a better/easier way to do this?

A: The following code shows in general how create a SSLContext for an HTTPS server by parsing a PEM file that has multiple entries, e.g. several certificates and one RSA PRIVATE KEY. However it is incomplete because plain Java 8 is unable to parse the PKCS#1 RSA private key data. Therefore it seems that your wish to do it without any library is not possible. At least BouncyCastle for parsing the PKCS#1 data is required (and then the PEM parser of BouncyCastle could be used, too).
private SSLContext createSslContext() throws Exception {
    URL url = getClass().getResource("/a.pem");
    InputStream in = url.openStream();
    String pem = new String(in.readAllBytes(), StandardCharsets.UTF_8);
    Pattern parse = Pattern.compile("(?m)(?s)^---*BEGIN ([^-]+)---*$([^-]+)^---*END[^-]+-+$");
    Matcher m = parse.matcher(pem);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Decoder decoder = Base64.getMimeDecoder();
    List<Certificate> certList = new ArrayList<>(); // java.security.cert.Certificate

    PrivateKey privateKey = null;

    int start = 0;
    while (m.find(start)) {
        String type = m.group(1);
        String base64Data = m.group(2);
        byte[] data = decoder.decode(base64Data);
        start += m.group(0).length();
        type = type.toUpperCase();
        if (type.contains("CERTIFICATE")) {
            Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(data));
            certList.add(cert);
        } else if (type.contains("RSA PRIVATE KEY")) {
            // TODO: load and parse PKCS1 data structure to get the RSA private key
            privateKey = ...
        } else {
            System.err.println("Unsupported type: " + type);
        }

    }
    if (privateKey == null)
        throw new RuntimeException("RSA private key not found in PEM file");

    char[] keyStorePassword = new char[0];

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);

    int count = 0;
    for (Certificate cert : certList) {
        keyStore.setCertificateEntry("cert" + count, cert);
        count++;
    }
    Certificate[] chain = certList.toArray(new Certificate[certList.size()]);
    keyStore.setKeyEntry("key", privateKey, keyStorePassword, chain);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("RSA");
    kmf.init(keyStore, keyStorePassword);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return sslContext;
}

A: Although an answer has been provided, I would like to provide an alternative which requires less code. See below for an example setup:
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem", "private-key-password".toCharArray());
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");

SSLFactory sslFactory = SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();

SSLContext sslContext = sslFactory.getSslContext();

To use the above setup you can use this library:
<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart-for-pem</artifactId>
    <version>7.0.0</version>
</dependency>

The setup above requires less custom code while it is still achieving what you are trying to accomplish. You can view the library and documentation here: https://github.com/Hakky54/sslcontext-kickstart

A: My full solution that I currently use:

*

*Use certbot on your server to generate the certificate.  I use the command "certbot certonly -d myawesomedomain.com"

*I use the following code to convert that certbot certificate into a java SSLContext:  https://github.com/mirraj2/bowser/blob/master/src/bowser/SSLUtils.java
package bowser;

import static com.google.common.base.Preconditions.checkState;
import static ox.util.Utils.propagate;

import java.io.File;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import com.google.common.base.Splitter;

import ox.IO;
import ox.Log;

public class SSLUtils {

  public static SSLContext createContext(String domain) {
    String pass = "spamspam";

    File dir = new File("/etc/letsencrypt/live/" + domain);
    if (!dir.exists()) {
      Log.warn("Could not find letsencrypt dir: " + dir);
      return null;
    }

    File keystoreFile = new File(dir, "keystore.jks");
    File pemFile = new File(dir, "fullchain.pem");

    boolean generateKeystore = false;

    if (keystoreFile.exists()) {
      if (keystoreFile.lastModified() < pemFile.lastModified()) {
        Log.info("SSUtils: It looks like a new PEM file was created. Regenerating the keystore.");
        keystoreFile.delete();
        generateKeystore = true;
      }
    } else {
      generateKeystore = true;
    }

    if (generateKeystore) {
      Splitter splitter = Splitter.on(' ');
      try {
        String command = "openssl pkcs12 -export -out keystore.pkcs12 -in fullchain.pem -inkey privkey.pem -passout pass:"
            + pass;
        Log.debug(command);
        Process process = new ProcessBuilder(splitter.splitToList(command))
            .directory(dir).inheritIO().start();
        checkState(process.waitFor() == 0);

        command = "keytool -importkeystore -srckeystore keystore.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks -srcstorepass "
            + pass + " -deststorepass " + pass;
        Log.debug(command);
        process = new ProcessBuilder(splitter.splitToList(command))
            .directory(dir).inheritIO().start();
        checkState(process.waitFor() == 0);

        new File(dir, "keystore.pkcs12").delete();// cleanup
      } catch (Exception e) {
        throw propagate(e);
      }
    }

    try {
      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      keystore.load(IO.from(keystoreFile).asStream(), pass.toCharArray());

      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(keystore, pass.toCharArray());

      SSLContext ret = SSLContext.getInstance("TLSv1.2");
      TrustManagerFactory factory = TrustManagerFactory.getInstance(
          TrustManagerFactory.getDefaultAlgorithm());
      factory.init(keystore);
      ret.init(keyManagerFactory.getKeyManagers(), factory.getTrustManagers(), null);

      return ret;
    } catch (Exception e) {
      throw propagate(e);
    }
  }

}

A: You can do something like this to get a proper SSLContext:
final String ca1 = "..load PEM file in string..";
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Certificate cert1 = cf.generateCertificate(new ByteArrayInputStream(ca1.getBytes()));
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
// Can add multiple truststore certificates here...
keyStore.setCertificateEntry("my-ca-1", cert1);
final SSLContext sslContext = SSLContexts.custom().setKeyStoreType(saToken)
        .loadTrustMaterial(keyStore, null)
        .build();

A: *

*This is a temporarly solution, because the code below, alows you to accept any server so, you should check deeply into your code when you are trying these kinds solutions.

*This code does not need any cert at all.

*The question is that why you are trying to avoid this procces, if the case requiered shouldn´t you be using a non secure server ?

logger.info("Starting instance ");
        TrustManager[] tm = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers(){return new X509Certificate[]{};}
            public void checkClientTrusted(X509Certificate[] chain, String authType) {logger.info(" checkClientTrusted");}
            public void checkServerTrusted(X509Certificate[] chain, String authType) {logger.info(" checkServerTrusted");}

        }};

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, tm , new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());