text:
Q: What kind of battery management is preinstalled on a clean Ubuntu 18.04 install? A friend recently told me that it is important to not charge the laptop battery fully, so that it lives longer. I didn't know if that is true, and if it is I would expect the battery hardware or the OS to handle that without me fiddling with it.
To back this claim up, here's a quote from Lenovo's Vantage Tool on Windows:

If you primarily use your computer with the AC adapter attached and only infrequently use battery power, you can increase the lifespan of the battery by setting the maximum charge value to below 100%. This is useful because batteries that are used infrequently have a longer lifespan when they are maintained at less than a full charge.

I have a ThinkPad X1 Yoga with Ubuntu 18.04, but I expect the answer not to be strongly dependent on the laptop model and the Ubuntu version.
What kind of battery management is preinstalled on Ubuntu without further configuration?
I am thinking of things like the following:

*

*stops charging at XX%

*warns at low battery

*hibernates on critical battery level

I am worried I might be destroying my battery's life by leaving the laptop constantly plugged in over a few weeks.
In the case that Ubuntu does not already have precautions set up, please also mention in your answer a suggestion regarding this.

A: NOTE: This answer had been edited majorly, introducing significant semantical changes:
Assumedly valid for both Ubuntu 18.04 and 20.04:
The default Gnome Settings app offers blanking the screen, switching off bluetooth and wifi to save battery power, and auto-suspending when idle, in the range from 15 mins to 2 hours.
GUI for advanced battery-management options:
I don't know where is the GUI for adjusting the below discussed settings. What I mean is, it might got nuked, which is a trend these years with the default Ubuntu experience (Gnome 3 desktop).
Where are the actual configs:
Battery-related settings now exist redundantly in the system, which is highly misleading.
With that said, they are probably in /etc/UPower/UPower.conf, as pointed out by @hackerb9 (thanks for the find, @lucidbrot)
Additionally, they are present among the system-wide application settings, accessed via the gsettings API, exposed by the optionally installable application, dconf-editor.
Those ones in gsettings are organized in the org.gnome.settings-daemon.plugins.power namespace, and apparently they do not take effect.
I take this from the above linked answer by @hackerb9, plus the telling comment section under this blog article.
(Actually, some settings in that gsettigs namespace keep taking effect, just not the ones that are introduced below.)
What can be configured:
There is a choice whether one wants to work in terms of battery level percentage or in terms of remaining time (gsettings default: time, UPower.conf default setting: percentage).
The following can be configured as both percentages and remaining time, both in UPower.conf and in gsettings, defaults being the same among them:

*

*from where it is considered low (default: 10% or 1200secs)

*from where it is considered critical (default: 3% or 300secs)

*level at which an automatic action is taken (default: 2% or 120secs)

Critical battery action choices in UPower.conf:
hybridSleep | hibernate | shutdown (default: hybridSleep, with fallback to the other options)
Critical battery action choices in gsettings:
suspend | hibernate | shutdown | and other options (default: suspend)
Worth repeating, it's likely the ones in gsettings do not play a part any more.
Now for another thing to ponder over: the UPower.conf file starts with the following comment:

Only the system vendor should modify this file, ordinary users should
not have to change anything.

Ubuntu Help on power/battery topic
(apparently for 20.10, in other words Gnome 3 (shared by 18.04)):
https://help.ubuntu.com/stable/ubuntu-help/power.html.en
Battery care via additional software:
This article commends TLP for 18.04 and higher.
TLP is well-discussed on this forum. It seems to have pretty fine-grained settings for when to start and when to stop charging, but these settings are vendor-specific (IBM/Lenovo ThinkPad, when additional dependencies are met).
Battery care via BIOS:

If you primarily use your computer with the AC adapter attached and only infrequently use battery power

In my Dell laptop's BIOS menu, there is a dedicated checkbox for exactly this use case. IIRC it's not being explained, how Dell will protect the battery, but the presence of this checkbox suggests that they are doing something differently then. So also take a good look around in your BIOS menu.
A relevant admission:
Perhaps I should have checked the aforementioned kept-on-charger BIOS checkbox, because that was my use case too. But I found it too late.
So, possibly - but not proven - due to this after 4 years, my battery has swollen to double its original thickness, and had to be removed. Due to this, right now I can't test or confirm any battery-related behaviour.


text:
Q: Can you replicate a password input with a text input? In other words, are the following equivalent?
<input type="text" autocomplete="off" spellcheck="false" />

<style>
   input[type="text"] {
     -webkit-text-security: disc;
     text-security: disc;
   }
</style>

and
<input type="password" />

A: No they are not
<input type="password" /> is compatible on all browsers of all versions, while the other is not.
But technically the output result is the same on modern browsers that support even one css property of it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How should I link to library dependencies from my git repository? I have made a project on github that uses several libraries such as glew, glm, sdl2 or sdl2_image.
I use them by having them in an a folder named 'external', and building them from source using CMake.
My problem is trying to setup that 'external' folder right after cloning the repo, so that it is easy for the user to compile the project.

*

*I could store the external folder as-is on my github repo, but it would get cumbersome to fetch the new updates of the libraries, and I don't want to make it seem like I'm "stealing ownership" of the libraries. And I don't really want to allow the usage of version control for those files.

*I could use git submodules to point at the right commits I want, but this makes the download super heavy (fetching each repo is about 10-20 times bigger than the release zip folder). And I do not really need the version control information anyway, since I'm not working on those dependencies, and would not be making changes.

The two reasonable options (but not optimal) that I see for me are downloading a zip file of the dependencies that I would have made myself, or fetching the dependencies one by one and unpacking them at the right locations through a script.
But making the script would add dependencies such as wget and its Windows equivalent, and I don't know where I could store the zip file, since github doesn't seem to provide a storage place for additional files (a new branch?).

*

*Does github provide any way of linking a repository to external repo releases?

*Otherwise, what would be a good place to store additional files relevant to a repository that should not be part of the version control?

A: This sounds like a job for FetchContent: a fairly recent couple of scripts that should be able to do exactly what you want. That is, download either compiled binary zip files from fixed URLs or even pull in and build the latest commit in a given branch.
FetchContent is especially helpful, since it does all this at configuration time, skipping a couple problems the alternative, ExternalProject, has always had for me, which is only fetching and compiling a project at build time.
From the examples on FetchContent:
include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)

FetchContent_MakeAvailable(googletest)
# you now magically have the googletest cmake targets available
# at configuration time and can link against them.

An alternative to this is to use the conan package management system, althought that is way more involved.


text:
Q: Prove minimality of lcm with Bezout Before defining the lcm I would like to prove following lemma about its properties:
Lemma
If $a$ and $b$ are nonzero integers, then there is a unique positive integer $m$ such that

*

*$a,b\mid m$,

*$a,b\mid c\implies m\mid c$.

Proof
Uniqueness: Suppose $m'$ is another such number, then from (2) follow $m\mid m'$ and $m'\mid m$, thus by Lemma ??? $|m|=|m'|$ and since both are positive, follows that $m=m'$.
Existence: We define $S=\{n\in\mathbb{N} : a,b\mid x\}$, since $|ab|\in S$, then $S\neq\varnothing$. Let $m$ be the minimum of the set (todo: existence from set theory), thus $a,b\mid m$, proving (1).
Now suppose $a,b\mid c$, set $d:=\gcd(a,b)$, then
$$...$$
Conclusion $m\mid c$.

Is it possible to fill the dots using Bezout and the usual identities for divisors and gcd? Without primes and Division Algorithm (I think this is one of the standard way) and $\textrm{lcm}(a,b)\gcd(a,b)=ab$. If not, is there an explanation why not?

I tried starting from the second proof of this answer here, but I don't get anywhere.
EDIT
Completion of the proof based on the answer of @haran :
Now suppose $a,b\mid c$, set $d:=\gcd(a,b)$, then $a,b\mid m,c$, thus $a,b\mid \gcd(m,c)\le m$ (because $\gcd(a,b)\le a$). Thus $\gcd(m,c)\in S$, but since $m$ is the minimal element, $\gcd(m,c)=m$ and we can conclude that $m\mid c$.

A: The uniqueness proof as you have done above is straightforward and beautiful.  For the proof of existence, first define LCM as the smallest number divisible by both inputs. We know that the product of two numbers is divisible by them individually which shows $lcm(a,b)<ab+1$.
Now it suffices to show that if there exists a number $x$ such that both the numbers divide, then the LCM which is $y$ divides it too. Assume the contrary, then since $a$ and $b$ divide both $x,y$, we have $a$ and $b$ divide $\gcd(x,y) =z$. Note that now, $z < y$ but this contradicts our definition of LCM  being the smallest number divisible by both $a,b$.
Hence our initial assumption is false. Thus, the definition of LCM being the least number divisible by $a,b$ is the same as the definition given. Since we have already proved that if LCM is the least number divisible by $a,b$, then there exists  and LCM for every $a$ and $b$, we are done!


text:
Q: Mysql explode function I have a table witch has a field with the following record:
1,2,3,4,5,6
I would like to ask the following two things:
1) How can i make a foreign key in another table? The rule would be:
For any value seperated by comma in field `field_name` must be record of other_table.field_id
2) How can i do something like: SELECT explode(field) AS ex FROM table_name ?
the name's of row maybe can retrieve as ex[0]-->1, ex[1]-->2

A: While it is possible to do a join on a comma separated field (using FIND_IN_SET for example), I don't think there is a way to do this for a foreign key.
MySQL doesn't have an explode function, and your idea would seem to suggest a varying number of columns on each row.
You can split them onto different rows if necessary but it is ugly. And more a good reason to NOT use comma separated fields
SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(field, ',', 1 + units.i + tens.i * 10 + hundreds.i * 100), ',', -1)
FROM table_name
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) hundreds


text:
Q: grid of images: on hover all dim but the one with the mouse over it. I have a grid images, I'm trying to get all of the images to dim (opacity change) when I mouse over an image except then one I moused over
here is what I'm using but I just changes the opacity of the one highlighted
 #grid li a:hover img {
   opacity:0.3;  filter:alpha(opacity=30);
  }
  .... ...
  ...

    ....
       .....

A: Add This to your css
#grid li a:hover img {
   opacity:1;  filter:alpha(opacity=100);
  }
 #grid:hover img {
   opacity:0.3;  filter:alpha(opacity=30);
  }

A: Using jquery this is fairly easy:
$('ul#grid img').on('mouseenter', function() {
    $('ul#grid img').fadeTo(0.3);
    $(this).fadeTo(1);
});
$('ul#grid img').on('mouseleave', function() {
    $(this).fadeTo(0.3);
});

Edit: Using only css is far better

A: Target the parent element for hover when you hover on child element.
See the JS fiddle http://jsfiddle.net/feitla/PgUMY/
 #grid:hover li a img {
   opacity:0.3;  filter:alpha(opacity=30);
  }

 #grid li a:hover img {
   opacity:0.9;  filter:alpha(opacity=30);
  }


text:
Q: Understanding the context of my json.load/re.search's syntax I recently finished a WebScrapping/Automation Zillow program for my boot camp. Instructor encouraged google as I was having issues with only being able to get the first couple of listing.
I stumbled upon this answer: Zillow web scraping using Selenium & BeautifulSoup
This worked well since instead of using bs4's find all method, I was able to get all of my listing neatly placed in a JSON file which was much easier to go through and complete the project. I only recently learned about regex and the re module on python and I was wondering if someone can explain how this code worked to help me retrieve the the nicely listed JSON from the get response and if this would work for other websites?
Code was:
self.data = json.loads(re.search(r'!--(\{"queryState".*?)-->', self.response.text).group(1))

*

*What arguments was taken account for on the json.loads?

*How did the oddly written !--({"queryState".*?)--> work?

*What is the purpose of the .group(1)?

I hate just copy and pasting but somehow this worked like magic and Id like to know how to replicate this for future projects. Sorry if this is loaded but the re.search documentation wasn't as helpful as I thought.

A: *

*json.loads() can work with a single argument, a string that will be parsed as JSON and the return value is typically a dictionary or list (depending on the JSON). Here, that single string is the return value of the call to .group(1)

*How is r'!--(\{"queryState".*?)-->' oddly written? It is a regular expression that is being applied to self.response.text using re.search(). It looks for the literal !-- and --> followed by something starting with {"queryState". The \ is there to indicated that the { is to be matched literally as well. The .*? indicates "any character zero or more times, not greedily" (to avoid matching --> as part of it).

*.group(1) returns the first matched group in the regex, which is the first part in parentheses. In this case, anything in between !-- and -->, if it starts with {"queryState"
So, if self.response.text would be this:
something
!--{"not queryState": 123}-->
something else
!--{"queryState": 123}-->
something else

Then running this:
self.data = json.loads(re.search(r'!--(\{"queryState".*?)-->', self.response.text).group(1))

Would set self.data to {'queryState': 123} (as json.loads() takes the string "{'queryState': 123}" and parses it into a dictionary, as user @Nick correctly pointed out)


text:
Q: What does ph stand for in reinforcement learning I'm reading the OpenAI baselines code for DQN.
There's a function named make_obs_ph that take a name and creates a placeholder of input with that name.
What does ph stand for ?

A: The meaning there is placeholder.
place, holder. ph.


text:
Q: Field Calc Python/VB script to populate field with one field, along with the last 6 digits of another I'm trying to populate a field in a table using field calculator with the value of the field in another, concatenated with the last 6 digits of another field.Example below, I would like a field SUBZONE to be populated with the zone code U, along with the last 6 digits of objectID, so U123456
EG:
OBJID
000000006000123456
ZONE
U
output new field:
U123456
A script will make this so easy.

A: Your field calculation will be 'U' + str(!OBJECTID!).zfill(6)[-6:]. This has several components:

*

*using str() we convert the value in OBJECTID to a string, this is required by the next step.

*zfill() the string with 0's to the left to make at least 6 characters using zfill(6), this has no effect if the string has 6 or more characters already.

*With the indexing notation [-6:] we extract the rightmost 6 digits, no matter how long the string is..

If your subzone is derived from a field then you can substitute that value using the calculation !Zone! + str(!OBJECTID!).zfill(6)[-6:] (assuming your subzone character comes from a field called Zone).


text:
Q: Using string translation in adapter return numbers I am trying to use translation string in my adapter but it returns numbers instead
if(currentItem.budget != null){
  holder.budget.text = "$ " + currentItem.budget.format()
} else {
  holder.budget.text = R.string.open_to_suggestions.toString()
}

R.string.open_to_suggestions.toString() supposed to return string text Open to suggestions but it returns numbers such as 2131755113 not sure why! any idea?

A: To show the string resource you must use context.getString()
if(currentItem.budget != null) {
  holder.budget.text = "$ " + currentItem.budget.format()
} else {
  val context = holder.itemView.context
  holder.budget.text = context.getString(R.string.open_to_suggestions)
}

Please take a look at the definition of getString here


text:
Q: How to switch from one wifi network to another wifi in appium(Android&IOS) Currently i'm working in Banking application for accessing security servers i have to switch one wifi network to another wifi is there any possible way in appium.
Anyone please help me on this

A: You can try Appium Studio. With which you can automate the process of switching from one wifi to another wifi channel.
You can find here on how to switch on the wifi in a single command.
But to change the wifi network, you have to automate the process.

A: We can use a workaround in android to connect to particular wifi.
Below are the steps:

*

*Navigate to Settings-Wifi Screen.

*Tap on the wifi-name.

Step1: Navigate to Settings-Wifi Screen.
For Windows OS:
String allCommand = null;
String commandForWifiSettings="am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings";
allCommand = "cmd.exe /C adb -s " + deviceID + " " + commandForWifiSettings;
Process p = Runtime.getRuntime().exec(allCommand);

For Linux OS:
String allCommand = null;
String commandForWifiSettings="am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings";
allCommand = "/bin/bash -l -c adb -s " + deviceID + " " + commandForWifiSettings;
Process p = Runtime.getRuntime().exec(allCommand);

Step2: Tap on the wifi-name in the wifi-settings screen. Add some wait before tapping on the element.
driver.findElement(By.xpath("//*[@text='Wifi-name']").click();


text:
Q: REGEX (regular expression) Replace  tags with  tags for font awesome with i want to replace with REGULAR EXPRESSIONS anything that starts with

Replace it with this starting as


text:
Q: SwiftUI onDrag preview doesn't get updated when Image changes on macOS I'm having an .onDrag on an Image. Whether I provide a preview myself or not, the preview always gets stuck to show the Image that appeared on the first drag. The NSItemProvider itself works well and I access the proper data, but not within the preview.

A simple example (code available here: https://github.com/godbout/DragPreview)
import SwiftUI

struct AppDetail {

    let bundleIdentifier: String
    let icon: NSImage

    init(bundleIdentifier: String) {
        self.bundleIdentifier = bundleIdentifier

        if
            let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier),
            let representation = NSWorkspace.shared.icon(forFile: url.path).bestRepresentation(for: NSRect(x: 0, y: 0, width: 64, height: 64), context: nil, hints: nil)
        {
            self.icon = NSImage(size: representation.size)
            self.icon.addRepresentation(representation)
        } else {
            self.icon = NSApp.applicationIconImage!
        }
    }

}

struct ContentView: View {

    @State private var apps: [AppDetail] = [
        AppDetail(bundleIdentifier: "com.apple.Mail"),
        AppDetail(bundleIdentifier: "com.apple.MobileSMS"),
        AppDetail(bundleIdentifier: "com.apple.Safari"),
    ]

    var body: some View {
        VStack(alignment: .center) {
            Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
                .onDrag {
                    guard
                        let app = apps.first,
                        let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleIdentifier)
                    else {
                        return NSItemProvider()
                    }

                    return NSItemProvider(object: url as NSURL)
                } preview: {
                    Text(apps.first == nil ? "no app" : apps.first!.bundleIdentifier)
                    Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
                }
            Button("next") {
                apps.removeFirst()
            }
            .disabled(apps.isEmpty)
        }
        .frame(width: 200, height: 200)
        .padding()
    }

}

Anything I'm doing wrong? Could this be a(nother) SwiftUI bug? If the preview is actually static and only rendered at the first drag, how could I change the code so that I get the preview of my current Image?
Thanks.

A: I read somewhere in a comment by @Asperi that the drag preview is only created once at init. So if you add an .id to the image it forces a redraw and reinit of preview:
            Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
                .id(apps.first?.bundleIdentifier) // here
                .onDrag { ...


text:
Q: How we should use mongoose with Typescript? I'm new to typescript and express .
I saw this code on Typescript Starter project by microsoft Link  and I'm a little confused about how this code works .
for example what does the 'type' keyword do?
and how the '&' keyword in used in this code ?
import bcrypt from "bcrypt-nodejs";
import crypto from "crypto";
import mongoose from "mongoose";

export type UserDocument = mongoose.Document & {
    email: string;
    password: string;
    passwordResetToken: string;
    passwordResetExpires: Date;

    facebook: string;
    tokens: AuthToken[];

    profile: {
        name: string;
        gender: string;
        location: string;
        website: string;
        picture: string;
    };

    comparePassword: comparePasswordFunction;
    gravatar: (size: number) => string;
};

type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void;

const userSchema = new mongoose.Schema({
    email: { type: String, unique: true },
    password: String,
    passwordResetToken: String,
    passwordResetExpires: Date,

    facebook: String,
    twitter: String,
    google: String,
    tokens: Array,

    profile: {
        name: String,
        gender: String,
        location: String,
        website: String,
        picture: String
    }
}, { timestamps: true });

I really appreciate if you could explain it a bit .

A: This has probably been answered more than a couple of times so I will be brief.
Type
A Type or type is like a blue-print for an object. Best to explain it with a example:
If you have a type called Animal:
type Animal {
  color: string;
}

Objects that is typed with Animal is expected to include a field called color of type string.
let lion: Animal;
// the lion object is expected to look like {color: 'some string'}
// only a object that conforms to Animal can be added to the lion variable.

Types are nothing more than that, they just help you to control what an object should do and what it is expected to look like.
Checkout the documentation for typescript and basic types here
The '&' part:
Let's say we have another type called LeggedAnimal:
type LeggedAnimal {
  nuberOfLegs: number;
}

We can combine two types to merge with a new type.
type Dog = Animal & LeggedAnimal;
// the Dog type is now {color: string, numberOfLegs: number}

The '&' combines one or more types together.


text:
Q: Jenkins - Dont build for specific commiter or commit message I'm having some issues with Jenkins and its Git plugin.
Currently, a Gitlab server is triggering the builds but I want to configure the job so that it doesn't build when a specific message is included in the commit.
I've tried using the ci-skip plugin (https://github.com/banyan/jenkins-ci-skip-plugin) but instead of not starting the job, the plugin allows it to start but then aborts it.
It does the job but I'm having aborted builds in Jenkins history and I'm trying to avoid that.
Anyone managed to do that?

A: Jenkins git plugin itself already provides these kinds of advanced usage.
Exclude specific messages

Job config page -->Source Code Management-->Git-->Add -->Polling ignores commits with certain messages

Exclude specific commiters

Job config page -->Source Code Management-->Git-->Add -->Polling ignores commits from certain users

Don't forget to click the help at the end of each of them to learn the correct way of usage.

A: If you have not yet found a solution:

*

*Configure your job to poll SCM but do not enter a timeplan for that (ignoring the warning that your job would never run.

*Configure the scm section to ignore commits, users, etc.

*Use a trigger for your jobs as follows: http://yourserver/git/notifyCommit?url=<URL of the Git repository>[&branches=branch1[,branch2]*][&sha1=<commit ID>] as seen on Git Plugin page
Whenever the URL is called, jenkins will scan for jobs that are using this repository. Then it checks for any specific settings (e. g. ignoring commits by certain users or with some commit messages) and either run the build or not. Of course the build will always somehow start to poll scm and check for commits, but if it is cancelled due to unimportant commits you will not see an aborted build in your history.

A: You will need to use external script.
Pull out the project (git clone/fetch) and then before continuing with your build check to see if the specific message is in your repository.
To check to see if your message is there you can use the git show or git log commands.
git log
git log --all --grep='<your message>'
# and you can add more flags if you want of course:
git log --all --oneline | grep '<your message>'

git grep
git grep '<your message>' $(git rev-list --all)

Outside of Jenkins
Add code to git hook which check what you want to find *messages, commit etc) and only if it find it call Jenkins via REST API and start your job.
This is the way im using Jenkins, i check for something that i looking for and then im invoking Jenkins via API
Read more here & here


text:
Q: PHP foreach over JSON with Array I have a json return that looks like this:
[output] => stdClass Object
    (
        [data] => stdClass Object
            (
                [Email] => Array
                    (
                        [0] => test1@AOL.COM
                        [1] => test2@AOL.COM
                    )

                [PhoneNumber] => Array
                    (
                        [0] => 2031234569
                    )

            )

What i need to do is be able to loop through the phones and emails and get them all.
I have tried:
foreach ($json_result->output->data as $data) {
$phone = $data->PhoneNumber;
$email = $data->Email;
}

but this is returning empty. Anyone have an idea?

A: You are trying to access PhoneNumber and Email as properties, while they are arrays.
foreach ($json_result->output->data->Email as $email_address) {
    echo $email_address;
}

foreach ($json_result->output->data->PhoneNumber as $phone_number) {
    echo $phone_number;
}

A: The easiest way is JSON encode your std object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
foreach($array as $data) {
   $phone = $data->PhoneNumber;
   $email = $data->Email;
}


text:
Q: Efficiently generating a UTC timestamp I need to generate UTC timestamps in string format quite often (several times a second), and the code I have for it is inefficient.
Is there a faster way than the one I'm using? It can be assumed that the program will not be running across day boundaries.
void GenerateUTCTimestamp(std::string& out)
{
    auto now = std::chrono::system_clock::now();
    time_t tnow = std::chrono::system_clock::to_time_t(now);
    tm* utc = gmtime(&tnow);

    std::stringstream ss;

    ss << std::setfill('0');
    ss << std::setw(4) << utc->tm_year + 1900;      // Year
    ss << std::setw(2) << utc->tm_mon + 1;          // Month
    ss << std::setw(2) << utc->tm_mday;             // Day
    ss << '-';
    ss << std::setw(2) << utc->tm_hour << ':';      // Hours
    ss << std::setw(2) << utc->tm_min << ':';       // Minutes
    ss << std::setw(2) << utc->tm_sec;              // Seconds

    out = ss.str();
}

A: You're going to have trouble finding faster code than this:
#include <chrono>
#include <string>

void
stamp(char* s, int i)
{
    do
    {
        *s-- = char(i % 10) + '0';
        i /= 10;
    } while (i > 0);
}

void GenerateUTCTimestamp(std::string& out)
{
    using namespace std;
    using namespace std::chrono;
    using days = duration<int, ratio<86400>>;
    auto now = time_point_cast<seconds>(system_clock::now());
    auto today = time_point_cast<days>(now);
    auto s = now - today;

    // y-m-d
    auto z = today.time_since_epoch().count() + 719468;
    const auto era = 5;
    const auto doe = z - era * 146097;
    const auto yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365;
    const auto y = yoe + era * 400;
    const auto doy = doe - (365*yoe + yoe/4 - yoe/100);
    auto m = (5*doy + 2)/153;
    const auto d = doy - (153*m+2)/5 + 1;
    m = m + (m < 10 ? 3 : -9);

    // h:M:s
    const auto h = duration_cast<hours>(s);
    s -= h;
    const auto M = duration_cast<minutes>(s);
    s -= M;

    // format yyyymmdd-hh:MM:ss
    out = "00000000-00:00:00";
    stamp(&out[3], y);
    stamp(&out[5], m);
    stamp(&out[7], d);
    stamp(&out[10], h.count());
    stamp(&out[13], M.count());
    stamp(&out[16], s.count());
}

*

*This code uses the public domain algorithm civil_from_days from here:
http://howardhinnant.github.io/date_algorithms.html#civil_from_days
where you can find an in-depth explanation of that algorithm.

*The number of branches in the code is minimized, and the code size itself is minimized.

*The use of general purpose (and convenient) streams are entirely avoided, opting instead for a bare-bones integer-to-char algorithm that doesn't  deal with localization, traits, wide characters, custom widths or alignments or even negative values.

*Except for the first call, memory allocation is completely avoided by reusing and formatting directly into out.

*This code does have a limited range of validity:  2000-03-01 to 2400-02-29.  If you need to make this code valid for points in time outside this range, change the computation of era to:
const auto era = (z >= 0 ? z : z - 146096) / 146097;
I put this code in a loop of 1000 calls (with the same string), timed it, and averaged the time over all the calls.
On my machine (macOS, clang, libc++, -O3), the original code takes about 3.9µs and the optimized code takes about 150ns (about 25X faster).
Then for grins, I implemented GenerateUTCTimestamp using Howard Hinnant's date library to see how it fared in the timing test.  It clearly wins the ease of use test (imho):
#include "date.h"

void GenerateUTCTimestamp(std::string& out)
{
    using namespace date;
    using namespace std::chrono;
    out = format("%Y%m%d-%T", time_point_cast<seconds>(system_clock::now()));
}

It clocked in at 2.5µs, 50% faster than the thread-unsafe C API, but plenty slower than the optimized code.  There's a performance penalty for the flexibility of a general purpose tool.
The date library uses the same calendrical algorithm as the optimized tool (except for using the generalized era), but formats into a stringstream like the original code.  It also of course has to parse the formatting string.


text:
Q: Flipped output using svgwrite-1.1.9 Building svg file using svgwrite-1.1.9 using polyline entities.
How can I prevent flipped output?
It seems the coordinates are messed up - vertical (y) is flipped.
Here's the code I'm using to generate the polyline:
# generate svg element

line = dwg.add(dwg.polyline(
   pairs,
   stroke='black', fill='blue'))

Pairs is a list of tuples in cartesian coordinates (X Y pairs):
[(2228.427, 1643.919), (2419.889, 1643.919), (2419.889, 1814.927), (2431.918, 1985.935), (2216.397, 1985.935), (2228.427, 1814.927), (2228.427, 1643.919)]

I'm using InkScape to visualize the svg output, and an in-house editor to visualize an alternate data stream; the in-house version is the correct version.  I'm missing one entity.
The right entity block is rotated (in source), the left one is not (but is flipped).  You can see in the svg that the entire right block is also flipped vertically, so it's above where it should be.
I haven't set any user viewport/coordinates in the SVG.
I'm pretty sure XY are the same (SVG, other).

A: Difference between SVG and data coordinate systems is the correct answer, I can't flag Martineau as correct (not enough rep?), but this lets me post an updated graphic.


text:
Q: Preloaded database with core data I am trying to use a preloaded Sqlite database for my universal app, which uses core data. It use to work with iOS 4.3, but not with iOS 5.0+ and I'm using Xcode 4.3.
I've looked at the linked below, made changes, changed back, but to no avail and now the preloading does not work at all.
Prepopulate Core Data in iOS 5
coredata problem nsurl may not respond to stringByAppendingPathComponent
What am I doing wrong, I have listed my code below, any help would be greatly appreciated. Thank you for your time.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{

    if (persistentStoreCoordinator != nil)
    {
        return persistentStoreCoordinator;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"SAP_ECC_DB.sqlite"];
    //NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"SAP_ECC_DB.sqlite"];

     //Set up the store.
     //For the sake of illustration, provide a pre-populated default store.
    NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    // If the expected store doesn't exist, copy the default store.
    if (![fileManager fileExistsAtPath:storePath])
    {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"SAP_ECC_DB" ofType:@"sqlite"];
        if (defaultStorePath)
        {
            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
    }
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

    NSError *error;
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }

- (NSString *)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
    //return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

A: Sometimes, especially in XCode 4.3, even if you add a resource to the project file list it doesn't get included in the final product, or gets removed along the way for no reason.  If you experience a problem where your product is not updating, not appearing, or not behaving as it should for whatever reason, check to make sure that it is actually included in the "Copy Bundle Resources" (sometimes even .m files go missing, those will be in the Compile Sources though) of the Build Phases tab of your project.
This one is especially tricky because Core Data will create a new database if one doesn't exist, making it appear as though it didn't copy, when in fact it didn't exist in the first place.


text:
Q: Send simple data from wp7 to winforms application I want to send simple data (geolocation data to be precise) from Windows Phone 7 application to a windows forms application and use it, as I'm a total beginner in this field I don't know which tools to use.
I searched about wcf services and tested this method but there's some issues: the data is sent from the phone application but isn't sent to the winforms application (guess something is missing)
If your know how to do this in a quick way, or have good tutorials I'll be thankful.
EDIT
I found this tutorial, it show how to connect directly wp7 application and desktop application without using sockets neither wcf service, I'm wondering if it is really works if the application isn't in localhost.
the like for the tutorial: wp7 tutorial

A: I had a similar problem and so I created a REST/JSON WCF service hosted in IIS with AppHarbor to provide the data. There's hundreds of ways to do it (Ruby/Heroku, etc..), but that particular one fits well within the Microsoft stack. I also needed to share route data and I used the WCF service to wrap the BingMaps services so that route computations are cached and shared. Considering that I had already created a local model, moving it out of my phone project into a service took less than a few hours (including the usual config hiccups, and forgetting to add the appharbor user to my bitbucket repo).
Consuming the service from WinForms (or any client) shouldn't be an issue as the service knows nothing about the client implementation.
Here's a tutorial from code project. REST WCF Service with JSON

A: I think you would need to implement some sort of server side solution which you could upload to on your Windows Phone and download from on your Windows Form application. This could be achieved using a WCF service which was connected to a server side database.

A: Another option would be to use sockets and communicate directly with your WinForms application. Check this tutorial on how to use basic sockets on WP7.


text:
Q: Как правильно добавить фотографии в слайдер Vue Carousel 3D? Пытаюсь разобраться в документации  Vue Carousel 3D и не могу понять, как сделать так, чтобы в каждом слайде отображалась одна картинка. Поясню: Хочу сделать слайдер, как в документации в примере Controls Customised.
Там такая конструкция

new Vue({
  el: '#example',
  data: {
    slides: 8
  },
  components: {
    'carousel-3d': window['carousel-3d'].Carousel3d,
    'slide': window['carousel-3d'].Slide
  }
})

  <carousel-3d :controls-visible="true" :controls-prev-html="'❬ '" :controls-next-html="'❭'" :controls-width="30" :controls-height="60" :clickable="false">
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
  </carousel-3d>

Но при попытке использовать конструкцию, как в примере, у меня получилось вот так и в итоге отображаются слайдеры с одной и той же картинкой. Так же я не понял, что такое :index="i". Я думал это приоритет картинок, но я оказался не прав.

  <carousel-3d :controls-visible="true" :controls-prev-html="'❬ '" :controls-next-html="'❭'" :controls-width="30" :controls-height="60" :clickable="false">
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>

  </carousel-3d>

Как в макете

Как у меня

Так же пробовал использовать несколько тэгов figure в тэге slider, заключая в figure картинки, но опять не то. Помогите разобраться, пожалуйста!
Сам сайт http://c96180og.beget.tech/

A: Начнем с того что ты должен понимать как пользоваться v-for.
slides должен быть массивом в котором могуть быть данные, например:
slides:['/img/sliders/4.jpg','/img/sliders/3.jpg','/img/sliders/2.jpg'....]

И тогда ты будешь перебирать уже массив путей к картинкам (на выводе будут у каждой карточки своя картинка)

  <carousel-3d :controls-visible="true" :controls-prev-html="'❬ '" :controls-next-html="'❭'" :controls-width="30" :controls-height="60" :clickable="false">
    <slide v-for="(slide, i) in slides" :index="i">

    </slide>
  </carousel-3d>

значение i это индекс объекта в массиве


text:
Q: Symfony2 form: create entity on Ajax success I am working with Symfony2 and I am trying to create new entity Collection without page reload. My controller works fine, but I have issues with Ajax, I am NOT well familiar with it. Below is the code I already have. When I press submit button, new entity is saved in db, but entity doesn't appear on page.
CollectionController
/**
 * @Route("/create-collection", name="collection_create_collection")
 * @Template()
 */
public function createAction(Request $request)
{
    $collection = new Collection();
    $form = $this->createForm(
        new CollectionType(),
        $collection,
        array('method' => 'POST',
            'action' => $this->generateUrl('collection_create_submit'),
            )
    );

    return array('collection'=>$collection, 'form' => $form->createView());
}

/**
 * @Route("/collection_create_submit", name="collection_create_submit")
 */
public function createSubmitAction(Request $request)
{
    $collection = new Collection();
    $user = $this->getUser();
    $form = $this->createForm(
        new CollectionType(),
        $collection,
        array('method' => 'POST',
        )
    );

    $form->handleRequest($request);
    if ($form->isValid() && $form->isSubmitted()) {
        $colname = $form["name"]->getData();
        $existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')->findBy(['name' => $colname, 'user' => $user]);
        if ($existing) {
            return new JsonResponse(['error' => 'Collection with such name already exists']);
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($collection);
        $em->flush();

        return new JsonResponse(array(
            'success' => $collection
        ));
    }
}

create.html.twig
 {% include 'CollectionBundle:Collection:collectionJS.html.twig' %}

Create a collection

     ×
  {{ form_start(form, {'attr' : {'action' : 'collection_create_collection', 'id': 'create-collection-form'}}) }}
  {{ form_widget(form) }}
Cancel
<button type="submit" value="create" class="right" onclick="createCollection();">Create</button>
{{ form_end(form) }}

collectionJS.html.twig
function createCollection(){
    var $form = $('#create-collection-form');
    $($form).submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $form.attr('action'),
            data: $form.serialize()
        }).done(function( data ) {
            if(data.error)
            {
                console.log(data.error);
            } else if(data.success) {
                var collection =  data.success;
                $('.griditems').prepend('
' + collection + '
');
                $('#externalModal').foundation('reveal', 'close');
            }
        });
    });
}

UPD
The submit is triggered, but now I get undefined instead of entity. Probably, I am sending wrong json response.
UPD
I tried to encode collection entity.
In createSubmitAction I changed return to
  $jsonCollection = new JsonEncoder();
        $jsonCollection->encode($collection, $format = 'json');

        return new JsonResponse(array(
            'success' => $jsonCollection
        ));

How do I get this response in Ajax?

A: JsonResponse cannot transform your entities into JSON. You need to use a serializer library like JMSSerializerBundle or implement a serializing-method inside your entity.
Check the answers provided here.
How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

A: You have to return a simple $collection object as the standard doctrine entity objects are too large in size. What I recommend is:
return new JsonResponse(array(
        'success' => $collection->toArray()
    ));

and adding a new method to your entity class:
public function toArray(){

return array(
'id'  =>$this->getId(),
'name'=>$this->getName(),
// ... and whatever more properties you need
); }


text:
Q: Office.js on Outlook for Mac: Internal Error on saveAsync method So office.js add-in support is finally out for Outlook for Mac since version 15.32.
I'm actually using the latest non-insider version 15.33, and have one issue that doesn't take place on OWA or Outlook Desktop for Windows.
When I make following call in the add-in to get the event id:
const itemCompose = Office.cast.item.toItemCompose(Office.context.mailbox.item);
itemCompose.saveAsync((result) => console.log(result));

on OWA and Outlook Windows result.value has the event id, however on Outlook for Mac that is the result:
{
 error: Error {name: "Internal Error", message: "An internal error has occurred.", code: 5001}
 status: "failed"
 value: null
}

is it a bug in the freshly released office.js support for Outlook for Mac, or I'm doing something wrong?
important note: it happens only if the event has some attendees, that is, if the event is an meeting. On an appointment, so an event without attendees, it works as expected.

A: Outlook for Mac doesn't support saving a meeting in compose mode, so this is expected. The Mac Outlook team knows about it.


text:
Q: importing a class that I have created in Python I want to import a class that I have defined and use it in a different file (main.py):
this is the class i have defined:
Example.py:
class Example:
  m=0
  n=0

def _init_(self,n,m):
    self.n=n
    self.m=m

main.py
 from Example import *
 p = Example (2,3)

both of the files are at at the same directory
but when I run main.py I am getting an error:
"TypeError: object() takes no parameters"

where am I wrong ?

A: The __init__ function is a magic method, and thus, has 2 underscores before and after the word.
As other have pointed out, you methods must also be properly indented to be inside your class.

A: class Example:

    def __init__(self, n, m):
        self.n = n
        self.m = m

This is the code you want. The __init__ has double underscores and it must be proper indented.
Also, your class level m=0, n=0 does not work the way you expect. It is not a default value to the instance.


text:
Q: Dynamically Choose a File Depending on Props I'm trying to import a file dynamically based on props, or at least find a way to get a file based on props. Is there a way to do that?
import json from '../../data/yearly/CAN.json';

In this case I would want CAN.json to be this.props.country + '.json'.

A: Yes you can..
What you're looking is called Dynamic Imports. You should only use it only when necessary though.
It works the same as importing statically, however when exporting a default module, you need to destructure first.
Example code of using it:
 useEffect(() => {
    async function importSelect() {
      const { default: data } = await import("./Testing");

      setData(data);
    }
    importSelect();
  }, []);

Here's sandbox link to check if data is loaded


text:
Q: Swift : Cannot assign to "" in self In Swift, I have a computed property called managedObjectContext: NSManagedObjectContext. when I try to initialise it like:
var managedObjectContext: NSManagedObjectContext? {
    get {
        createManagedObjectContext()
        return self.managedObjectContext
    }
    set(newManagedObjectContext) {
        self.manageObjectContext = newManagedObjectContext
    }
}

func createManagedObjectContext() -> NSManagedObjectContext {

    if let coordinator = persistentStorageCoordinator() as NSPersistentStoreCoordinator!
    {
        self.managedObjectContext = NSManagedObjectContext()
        self.managedObjectContext!.persistentStoreCoordinator = coordinator

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleBackgroundMOCDidSaveNotification:", name: NSManagedObjectContextDidSaveNotification, object: self.managedObjectContext)
    }

    return self.managedObjectContext!;
}

I am getting an error saying : Cannot assign to "managedObjectContext" in self.
Can anybody help to fix this?
Thanks in advance.

A: A lazy stored property (see the Swift Programming Language book, page 313) is more appropriate for what you are trying to do here.
lazy var managedObjectContext = createManagedObjectContext()

createManagedObjectContext() won't be called until you attempt to access the property the first time (and only the first time).

A: You also receive this compile error when you're trying to assign a value to a let constant. Changing the variable's type to var should solve it, in this case.

A: Your problem is that you are using a computed property as if it were a standard property, you are effectively attempting to call the setter recursively .  You don't need to use a computed property here, just a standard property -
var managedObjectContext: NSManagedObjectContext?

A computed property is one whose value is computed when required based on other properties - For example the "center" property in the Swift Programming Language -
var center: Point {
    get {
        let centerX = origin.x + (size.width / 2)
        let centerY = origin.y + (size.height / 2)
        return Point(x: centerX, y: centerY)
    }
    set(newCenter) {
        origin.x = newCenter.x - (size.width / 2)
        origin.y = newCenter.y - (size.height / 2)
    }
 }

Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itunes.apple.com/au/book/swift-programming-language/id881256329?mt=11
Center is determined by the origin and size, and setting the center affects the origin

A: Add it!! = )
// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: NSURL = {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.YOURNAME_OTHERS.YOURAPP" in the application's documents Application Support directory.
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as NSURL
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = NSBundle.mainBundle().URLForResource("YOURAPP", withExtension: "momd")
    return NSManagedObjectModel(contentsOfURL: modelURL)
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("YOURAPP.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if let moc = self.managedObjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save(&error) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            //abort()
        }
    }
}


text:
Q: html Buttons with automatic height and width next to each other Basically, what I am planning to do, is have 4 buttons, which can trigger an action.
However, these are very short in height and don't seem to move around easily. I do have the code for the actions they are supposed to do, but this question is purely about the lay-out.
Two of these buttons should be 35% of the max height and be on the left and right of the screen.
The other 2 should be half the height, and on top of each other, in the middle of the screen.
I think that this should be possible using classes, but I don't know how exactly.
Would appreciate some help.
Sketch of what I mean

A: Check this out. It is not perfect by any means but should get ya going at least.
HTML
  <div class='container'>
  <button class='side'>L</button>
  <button class='mid'>T</button>
  <button class='mid'>B</button>
  <button class='side'>R</button>
</div>

CSS
.container {
    width: 100%;
    height: 35%;
    column-count: 3;
    column-gap: 0px;
    position: absolute;
    bottom: 0;
}
.side {
    width: 100%;
    height: 100%;
}
.mid{
    height:50%;
    width: 100%;
    display: block;
}

https://jsfiddle.net/de6wygtp/39/


text:
Q: Why do we have to set responseType when using XMLHttpRequest? I implemented a HTML which upload a file, and then download another file from server.
When handling the "download part", i noticed that if i download a binary file, i have to set responseType to blob or the file will be broken.
What confused me is that, HTTP header contains content-type which could tell XMLHttpRequest what type of file the server is sending. Why i have to set it manually? I don't understand the logic because it's server's turn to tell what the file type is, rather than predicted by client
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'blob'

.......

        xhr.onload = function(e) {
          if (this.status == 200) {

          var blob = new Blob([this.response]); // if i don't set responseType, this.response will be broken
          let a = document.createElement("a");

A: Your question made me realise I'm not entirely sure of the following, but it is how I have always looked at it.
responseType sets the type of xhr.response so you can process it as a Blob; it lets you retrieve the results of the xhr request as a Blob. If you don't set it, xhr.response will be Text.
A server may have sent the data the right way based on a mime type, but it still only sends a stream of bytes with a mime type; the interpretation of the received bytes lies on your end, and the received data won't automatically be of the type Blob based on the mime type.
Blob is not a file type on the server; the server may know and send the mime types of files, but Blob isn't one of them, and xhr.response won't be a Blob just because the mime type suggests that a Blob would be the right type.
Also, you may want to process the xhr.response differently from what can be inferred from the mime type, and in that sense, it is a kind of override (though not with the same functionality as xhr.overrideMimeType()).


text:
Q: Django best practice for common class I would like to make class like common.py and access from each application's views.py or management/commands
For now my structure is like this
myproj/myproj
      /myapplication/views.py
                    /management/commands/mycommand.py

then I add my orivinal class and call from each files like this.
However , where should I put common.py and how to import???
For example making newfolder ??
 but it might be confusing for application name??
myproj/myproj
      /myapplication/views.py
                    /management/commands/mycommand.py
      /commonlib/common.py

How is the best practice for this purpose??

A: If it's generic to lots of different apps, I often create something at the top level, so it's like:
myproj/myproj/helpers

inside helpers, put:
utilities.py

and then in your view or command, use:
from myproj.helpers import utilities

You could put any number of generic files into your helpers folder, and import them anywhere from that location.
Often it depends what feels most organised for you :)


text:
Q: Error The argument type 'Object?' can't be assigned to the parameter type 'Color?' There is my code :
The StreamBuilder has an error

Error The argument type 'Object?' can't be assigned to the parameter
type 'Color?

body: Center(
          child: StreamBuilder(
            stream: bloc.stateStream,
            initialData: Colors.amber,
            builder: (context, snapshot) {
              return AnimatedContainer(
                duration: Duration(milliseconds: 500),
                width: 100,
                height: 100,
                color: snapshot.data,
              );
            },
          ),
        ),
        body: Center(
          child: StreamBuilder(
            stream: bloc.stateStream,
            initialData: Colors.amber,
            builder: (context, snapshot) {
              return AnimatedContainer(
                duration: Duration(milliseconds: 500),
                width: 100,
                height: 100,
                color: snapshot.data,
              );
            },
          ),
        ),
      ),
    );
  },
}

A: Your getting the error because the snapshot is of type AsyncSnapshot<Object?> and when you set the color to snapshot.data, the type Object, there's a type mismatch since the color should be of type Color.
You can fix the error by specifying the type of stream your StreamBuilder is using like below:
    body: Center(
              child: StreamBuilder<Color>( //Add <Color> after StreamBuilder
                stream: bloc.stateStream,
                initialData: Colors.amber,
                builder: (context, snapshot) {
                  return AnimatedContainer(
                    duration: Duration(milliseconds: 500),
                    width: 100,
                    height: 100,
                    color: snapshot.data,
                  );
                },
              ),
    ),


text:
Q: ksh prompt defined as function with newlines I wrote myself a pretty, git aware ksh prompt function. Here I only include a minimal working example so that you can see my problem without all the bloat:
#!/bin/ksh

function _test_prompt
{
    prompt="`whoami`@`hostname` > "
    [[ $(id -u) -eq 0 ]] && prompt="ROOT@`hostname` # "

    print "\n\w"
    print -n "$prompt"
}

export readonly PS1='$(_test_prompt)'

I source this script from my .kshrc.
The problem is that when I try to look at for example a longer, prettified git log, the prompt's newlines cut off the top of my output. For example
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s'

shows up as
* f0490d0 - Make sure fb is big enough to handle reconfigure   (3 years, 10 months ago) <Keith Packard>
* 7caa6ce - Add xrandr-auto sample script   (3 years, 10 months ago) <Keith Packard>
* f59c924 - (tag: v0.2) Update to version 0.2   (7 years ago) <Keith Packard>
* a6c8969 - Add --auto switch, a shortcut for --config "xrandr --auto"   (7 years ago) <Keith Packard>
* d45135b - Add manual   (7 years ago) <Keith Packard>
* ef165dc - add .gitignore   (7 years ago) <Keith Packard>
* d927ec1 - Autotool   (7 years ago) <Keith Packard>
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

~/git-misc/x-on-resize
user@hostname >

And the first line of the output can only be seen by paging up once:
~/git-misc/x-on-resize
user@hostname > git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s'
* 617e5ed - (HEAD -> master, origin/master, origin/HEAD) Use mode ID instead of mode for autoconfig   (3 years, 10 months ago) <Keith Packard>
* f0490d0 - Make sure fb is big enough to handle reconfigure   (3 years, 10 months ago) <Keith Packard>

(this is what's at the bottom of the previous page, cut off).
As you can imagine, this is very annoying; in this case I actually lose the most recent commit and have to scroll up for it.
This only happens when the output of the log would fit on one screen (otherwise it goes into less).
Thanks for your help!

A: As usual, I managed to solve the problem after I actually got around to ask about it.
I simply set the pager.log git config variable to less -RFc; the relevant switch is -c as far as I understand: it tells less to repaint the screen from bottom to top instead of doing so vice versa.
Apprently, this was indeed not a ksh issue. My apologies.


text:
Q: how to split a column in to two columns in postgresql? I am using postgresql database. I have a table called "notifications" which consists of a column called Time which has both date and time value like this
--> time
   2014-07-24 19:11:18
I want to split this time column in to time and date column.
How to do this?Someone do help me...

A: if your column is of type text (or timestamp or any explicitly casted), then:
t=# with d as (select '2014-07-24 19:11:18'::text col) select col::date, col::time from d;
    col     |   col
------------+----------
 2014-07-24 | 19:11:18
(1 row)

Time: 0.826 ms

here d is your table and col is your column:
select col::date, col::time from d;


text:
Q: Lighttpd fails to start after reboot I installed lightpd on a Raspberry Pi (running Raspbian Stretch) in this way:
apt-get install -y lighttpd php-common php-cgi php
lighty-enable-mod fastcgi-php
usermod -aG www-data pi

after starting the service I checked and it worked fine, serving the php web pages as expected. After rebooting the service doesn't start anymore:
$ systemctl status lighttpd.service
● lighttpd.service - Lighttpd Daemon
   Loaded: loaded (/lib/systemd/system/lighttpd.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sat 2017-09-09 21:26:39 CEST; 6min ago
  Process: 1302 ExecStart=/usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf (code=exited, status=255)
  Process: 1295 ExecStartPre=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf (code=exited, status=0/SUCCESS)
 Main PID: 1302 (code=exited, status=255)

Sep 09 21:26:38 rpi systemd[1]: lighttpd.service: Failed with result 'exit-code'.
Sep 09 21:26:39 rpi systemd[1]: lighttpd.service: Service hold-off time over, scheduling restart.
Sep 09 21:26:39 rpi systemd[1]: Stopped Lighttpd Daemon.
Sep 09 21:26:39 rpi systemd[1]: lighttpd.service: Start request repeated too quickly.
Sep 09 21:26:39 rpi systemd[1]: Failed to start Lighttpd Daemon.
Sep 09 21:26:39 rpi systemd[1]: lighttpd.service: Unit entered failed state.
Sep 09 21:26:39 rpi systemd[1]: lighttpd.service: Failed with result 'exit-code'.

Here the configuration file:
$ cat /etc/lighttpd/lighttpd.conf
server.modules = (
    "mod_access",
    "mod_alias",
    "mod_compress",
    "mod_redirect",
)

server.document-root        = "/home/pi/www"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"
server.port                 = 80

index-file.names            = ( "index.php", "index.html", "index.lighttpd.html" )
url.access-deny             = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/javascript", "text/css", "text/html", "text/plain" )

# default listening port for IPv6 falls back to the IPv4 port
include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

What should I check?

A: You should check that if any directory it's going to use is not mounted to a tmpfs system. Lighttpd is not able to recreate them after installing.
The solution is then to manually create on every reboot the following directories:

*

*/var/log/litghtpd

*/var/run/lighttpd
owning them as www-data.

A: Try to disable selinux by typing setenforce 0 and then restart lightpd to check if it works. If it does then edit nano /etc/selinux/config and change the value of SELINUX from enforcing to disabled in order to permanently disable selinux. Very often on Linux os' SELINUX is preventing web servers from starting.

A: To check configuration: lighttpd -t -f lighttpd.conf
To start in foreground with logging on stdout: sudo lighttpd -D -f lighttpd.conf
More info: https://redmine.lighttpd.net/projects/1/wiki/TutorialConfiguration


text:
Q: Удваивание вывода при простом парсинге csv в C++ Я написал этот код, и я не могу понять, почему он удваивает строку, когда я компилирую и запускаю ее ...
data.csv состоит из:
0, person, 8, 12, 344, 486
Пожалуйста, скажите мне, почему это происходит и что я могу сделать, чтобы избежать этого..
Спасибо за любую помощь.
Вот код:
ifstream myfile("data.csv");

if(!myfile.is_open()) cout<<"error";

        string num1;
        string num2;
        string num3;
        string num4;
        string num5;
        string num6;

            while(myfile.good()){

                    getline(myfile,num1,',');
                    getline(myfile,num2,',');
                    getline(myfile,num3,',');
                    getline(myfile,num4,',');
                    getline(myfile,num5,',');
                    getline(myfile,num6,'\n');

                    cout<<num1<<","<<num2<<","<<num3<<","<<num4<<","<<num5<<","<<num6<<"\n";
            }

myfile.close();

return 0;
}

A: Это происходит из-за того, что после чтения первой строки поток myfile все еще имеет состояние good (ибо неудачных попыток чтения еще не было). На второй итерации цикла, num1 принимает пустое значение, а в потоке встречается конец файла. Остальные num уже не читаются, и сохраняют считанные на первой итерации цикла значения. Предлагаю такую модификацию кода:
for(;;)
{
    getline(myfile,num1,',');
    getline(myfile,num2,',');
    getline(myfile,num3,',');
    getline(myfile,num4,',');
    getline(myfile,num5,',');
    getline(myfile,num6,'\n');

    if(myfile.good())
        cout<<num1<<","<<num2<<","<<num3<<","<<num4<<","<<num5<<","<<num6<<"\n";
    else
        break;
}


text:
Q: Custom Asymmetric Cryptography Algorithm I want to use an asymmetric cryptography algorithm, but I need it have short Key Size(not like RSA which is at least 384).
I need it to be about around 20.
Is it possible?

A: That's a .NET restriction on the key size; RSA can be used with any key size. It just doesn't make sense to do so.
Think about it, with a 20-bit key you can brute force the it in 2^20 attempts and that's just too easy with today's computers.

A: There are several ways to have a short key size.
1. With RSA
A RSA public key consists in a big number n (the "modulus") and a (usually small) number e (the public exponent). e can be as small as 3, and in a closed setup (where you control key generation) you can force the use of a conventional e, the same for everybody. A typical size for n is 1024 bits (i.e. 128 bytes).
n is the product of two prime numbers (n = p*q). Knowledge of p and q is sufficient to rebuild the private key (nominally a value d which is a multiplicative inverse of e modulo p-1 and q-1). Assuming that n is known, knowledge of p alone is sufficient (if you know n and p, you can compute q with a simple division). For proper security, p and q should have similar sizes, so even by taking the smaller of the two, you still need to store about 512 bits or so -- that's 64 bytes).
It has also been suggested to select a small d (the "private exponent"). But this makes e essentially random, hence large; you can no longer use a conventional small value for e. This basically doubles the public key size. Also, forcing a small d can make the key weak (it has been shown to be the case when the size of d is no more than 29% of the size of n, but that does not prove in any way that a d of 30% the size of n is safe). This is generally considered to be a bad idea.
2. With DSA / Diffie-Hellman
DSA is a digital signature algorithm. Diffie-Hellman is a key exchange algorithm. Both are "asymmetric cryptographic algorithms" and you would use one or the other, or both, depending on your needs. In both cases, there is a public mathematical group (numbers modulo a big prime number p for the basic DSA and DH; elliptic curve variants use an elliptic curve as group); the public key is a group element, and the private key is the discrete logarithm of that element relatively to a conventional generator. In other words, a prime p and a number g modulo p are given (they can be shared by all key holders, even); a private key is a number x corresponding to the public key y = gx mod p. The private key is chosen modulo a small prime q. q is known and must be large enough so as to defeat the generic discrete logarithm algorithms; in practice, we want a 160-bit or more q.
This means that a private key fits in about 20 bytes. That's not 20 decimal digits, but closer.
3. With ANY cryptographic algorithm
When you generate a key pair, you do so with:

*

*a deterministic procedure;

*a source of random bits.

For instance, with RSA, you generate p and q by creating random odd numbers of the right size and looping until a prime number is found. For a given random source, the whole process is deterministic: given the same random bits, this will find the same primes p and q.
Hence you can develop a PRNG seeded by a secret key K and use it as random source for the key generation process. Whenever you need the private key, you run the key generation process again, using K as input. And voilà! Your private key, the one you need to store, is now K.
With RSA, this makes private key usage quite expensive (RSA key generation is not easy). However, with DSA / Diffie-Hellman, this would be very inexpensive: the private key is only a random number modulo q (the group order) which can be generated with much less cost than using the private key for a digital signature or an asymmetric key exchange.
This leads to the following procedure:

*

*The "private key", as stored, is K.

*The group parameters for DSA / Diffie-Hellman are hardcoded in the application; everybody uses the same group and that is not a problem. The group order is q, a known prime of at least 160 bits. If you use an elliptic curve variant, then q is a property of the curve, hence a given.

*When you need to sign or to perform a key exchange (key exchange is used to emulate asymmetric encryption), you compute SHA-512(K), which yields a 512-bit sequence. You take the first half (256 bits), interpret it as a number (with big-endian or little-endian convention, as you wish, provided that you always use the same convention), and reduce it modulo q to get the private DSA key. Similarly, you use the second half of the SHA-512 output to get the private DH key.

The key generation is very slightly biased but this does not imply much security trouble. Note that if you need a DSA key and a DH key, then you can use the same group but you should not use the same private key (hence the use of both halves of the SHA-512 output).
How big should be K ? With a hash function such as SHA-512, K can be any arbitrary sequence of bits. However, K should be wide enough to defeat exhaustive search. A 1024-bit RSA key, or a 1024-bit DSA modulus (the p modulus for DSA), provide a security level which is very roughly equivalent to an 80-bit symmetric key. Similarly, a 160-bit group order for DSA/DH provides the same level. 80 bits are not that much; you cannot go lower than that if you want to be taken seriously. This means that K should be chosen among a space of at least 280 possible keys; in other words, if K is selected as uniformly random bytes, then it must be at least 10 bytes long. With decimal digits, you need at least 24 digits. Anything below that is intrinsically weak, and that's unavoidable.
Standard warning: if anything of the above is not obvious or crystal clear to you, then do not even think about implementing it. Implementation of cryptographic algorithm is tricky, especially since the deadliest errors cannot be tested (it is not because the program runs and appears to work properly that it does not contain security weaknesses).

A: You may want to consider using Elliptic Curve Cryptography, if you can find a standard implementation of it. It provides the same level of protection against brute force as RSA, with substantially shorter key lengths.
The standard disclaimer about cooking up your own cryptosystems applies here, of course.


text:
Q: Same program is 10 times slower on windows I wrote a simple c program that copies 10 million bytes from a file and pastes them in reverse order on another file (this is done one byte at a time, I know it's not efficient but it's just to make some tests), I don't understand why on linux it takes 2.5 seconds while on windows it takes more than 20 seconds. I run the same program changing only the paths.
I use windows 10 and archlinux, the files are on an ntfs partition.
code on windows
#include <stdio.h>
#include <time.h>

void get_nth_byte(FILE *fp, int nth_index,unsigned char* output){
    fseek(fp,nth_index,SEEK_SET);
    fread(output, sizeof(unsigned char), 1,fp);
}

int main() {
    clock_t begin = clock();
    //
    FILE* input = fopen( "C:\\Users\\piero\\Desktop\\input.txt","rb");
    FILE* output = fopen("C:\\Users\\piero\\Desktop\\output.txt","wb");
    unsigned char byte;
    for (int i = 10000000; i > 0; i--) {
        get_nth_byte(input,i,&byte);
        fwrite(&byte, sizeof(unsigned char),1,output);
    }
    //
    clock_t end = clock();
    double result = (double) (end - begin)/CLOCKS_PER_SEC;
    printf("%f",result);
    return 0;
}

code on linux
#include <stdio.h>
#include <time.h>

void get_nth_byte(FILE *fp, int nth_index,unsigned char* output){
    fseek(fp,nth_index,SEEK_SET);
    fread(output, sizeof(unsigned char), 1,fp);
}

int main() {
    clock_t begin = clock();
    //
    FILE* input = fopen( "/run/media/piero/Windows/Users/piero/Desktop/input.txt","rb");
    FILE* output = fopen("/run/media/piero/Windows/Users/piero/Desktop/output.txt","wb");
    unsigned char byte;
    for (int i = 10000000; i > 0; i--) {
        get_nth_byte(input,i,&byte);
        fwrite(&byte, sizeof(unsigned char),1,output);
    }
    //
    clock_t end = clock();
    double result = (double) (end - begin)/CLOCKS_PER_SEC;
    printf("%f",result);
    return 0;
}

output on linux : 2.224549
output on windows : 25.349647
UPDATE
I solved the problem by using cygwin rather than mingwin, now it takes about 4.3 seconds

A: This is a great demonstration of how it's not the code we write that runs, it's the executable that the compiler makes from the code that runs.
It is possible that your Windows C compiler is not as advanced as your Linux C compiler, and is not optimizing your code as well as it could, or it's possible that the libraries that the Windows compiler is linking to for fread() and fwrite() are slower than the equivalent libraries in the Linux system.
If I had to put up my best guess, the Linux C compiler probably noticed that it would be more efficient to read more than one byte at a time, and it could do that without affecting the semantics of your program, and the Windows compiler either didn't infer the same, or wasn't able to optimize in the same way due to some underlying proprietary filesystem thing that only Microsoft engineers understand.
I can't say for sure without a peek at the disassembled binaries

A: One of the strengths of Unix/Linux is that files are designed to be treated as streams of bytes, with it being maximally easy and efficient to seek to the n'th byte using fseek or lseek.
Non-Unix operating systems, such as Windows, tend to have to work much harder to implement those seek operations.  In the worst case, they may actually need to read through the file, counting characters as they go.
Your code opens both files in binary mode, and this should reduce the need for the fseek implementation to perform any expensive emulations.  In text mode, a 10x performance penalty for heavy fseek use wouldn't surprise me.  I'm much more surprised you're seeing it in binary mode.
[Disclaimer: strictly speaking, in text mode fseek is not defined as seeking to an arbitrary byte offset at all, but rather, only to a position defined by the number returned by a previous call to ftell.  If an implementation takes advantage of that freedom, it can reduce the performance penalty for text-mode fseek operations, also, but it then means that code like yours, that constructs positions to seek to on the assumption that they're pure byte offsets, may not work at all.]


text:
Q: Error messages about missing Codebase attribute when loading webstart application I have a webstart application in which all the jars are signed (my own and third-party). When load it with Java7u25, I see error messages like the following in the Java console:
Missing Permissions manifest attribute for: http://example.com/webstart/application-jars/commons-beanutils-1.8.3.jar
Missing Codebase manifest attribute for: http://example.com/webstart/application-jars/commons-beanutils-1.8.3.jar

I read up on the changes in 7u25 here: http://blog.eisele.net/2013/06/java-se-7-update-25-release-notes.html
The note says to specify the Codebase attribute in the JAR's manifest at the time of building and have it match the Codebase in the JNLP file. How is this supposed to be setup to work for third-party jars like commons-beanutils which clearly don't have this manifest entry?

A: If you are signing the jar files yourself (third party as well as your own) you can just add the necessary parameters to the third party jars manifest.mf (open them with an archive utility, i.e. archive manager on ubuntu or try 7-zip etc for windows) add the parameters as you have to your own jars manifest (re package them, on ubuntu this happens automatically when you close the file after editing, I'm not sure if you're on windows) and then build your application/sign all the jars.
This worked for me although I'm sure there's a better way of doing it.

A: If you cannot sign yourself see also this answer for a way to add an exception for the site of the app.


text:
Q: Javascript/Jquery Logic - Few Questions about Modal and .data Hello guys I have a few questions so I'll get to it as best as I can.
I am using javascript and jquery along with ajax to pass json data to my database. I am also using Spring MVC to process the store/request data but that is not my concern.
I am using Metronic theme, and currently in the form wizard where student need to fill a form for application. I have trouble in using the Modal to get/pass data between the tables and the Modal, vice versa.
I have a few objectives that I want to accomplish and I have issues with them after trying a few approach.
1) Here is the screenshot and I will explain what I am to achieve and what issue I have.

When clicking the "Add new Owner" button, a modal should appear(you can see in below). Data inserted using the modal will populate in table below the button as the arrows shown.

So, in the "matrik No." field, it is a Select2 dropdown that will filter the id of the student as they type. and once the id has been selected, the fields from Name to Email including the student's photo will auto-populate.
When clicking the "add owner" button(in the modal), those data will be shown in the table on the first screenshot.
Here is my related codes for the modal and the buttons.
HTML

Owner Info

                                Add New Owner

                                                 Matrik No.
                                                 Name
                                                 IC No.
                                                 Birth Place
                                                 Faculty
                                                 Phone No.
                                                 Email

                                        <button type="button" class="close" data-dismiss="modal"
                                            aria-hidden="true"></button>

Add New Owner

                                    <form id='frm'>

                                                    Matrik No.  *

                                                        <input name="matrik_number" class="form-control select2" />

                                                    Name

                                                        <input name="student_name" id="student_name" type="text" class="form-control"
                                                            readonly>

                                                    IC Number

                                                        <input name="student_ic" id="student_ic" type="text" class="form-control"
                                                            readonly>

                                                    Birth Place

                                                        <input name="student_birthplace" id="student_birthplace" type="text"
                                                            class="form-control" readonly>

                                                    Faculty

                                                        <input name="faculty_name" id="faculty_name" type="text"
                                                            class="form-control" readonly>

                                                    Study Year

                                                        <input name="student_studyyear" id="student_studyyear" type="text"
                                                            class="form-control" readonly>

                                                    Phone No.

                                                        <input name="student_phoneno" id="student_phone" maxlength="11" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="text"
                                                            class="form-control">

                                                    E-Mail

                                                        <input name="student_emailadd" id="student_email" type="text" maxlength="50"
                                                            class="form-control">

                                                    Year Start
                                                        Business

                                                             <input type="radio"
                                                                name="optionsRadios4" value="option1" /> 1
                                                              <input
                                                                type="radio" name="optionsRadios4" value="option2" />
                                                                2
                                                               <input
                                                                type="radio" name="optionsRadios4" value="option3" />
                                                                3
                                                              <input
                                                                type="radio" name="optionsRadios4" value="option4" />
                                                                4

                                        </form>

                                        <button type="button" class="btn dark btn-outline"
                                            data-dismiss="modal">Close</button>
                                        Add Owner

JS
        //tab2
        tab_owner.on('click', '.add-owner', function (e){
            e.preventDefault();
        });

        tab_owner.on('click', '.del-owner', function (e){
            e.preventDefault();
            $(this).closest('tr').html('');
        });

        tab_owner.on('click', '.edit-owner', function (e){
            e.preventDefault();

            var m = $(this).closest('tr').find('.matrik').html();
            var n = $(this).closest('tr').find('.name').html();
            var i = $(this).closest('tr').find('.ic').html();
            var bp = $(this).closest('tr').find('.bp').html();
            var fac = $(this).closest('tr').find('.fac').html();
            var f = $(this).closest('tr').find('.fon').html();
            var e = $(this).closest('tr').find('.email').html();

            $('#matrik_number', large).val(m);
            $('#student_name', large).val(n);
            $('#student_ic', large).val(i);
            $('#student_birthplace', large).val(bp);
            $('#faculty_name', large).val(fac);
            $('#student_phone', large).val(f);
            $('#student_email', large).val(e);

            large.modal();
        });

        large.on('click', '.add-modal-owner', function (e){
            e.preventDefault();

            var student_data = {
                    id:$('[name=matrik_number]').val(),
                    phone:$("[name=student_phoneno]").val(),
                    email:$("[name=student_emailadd]").val(),
                    optionradio4:$("[name=optionsRadios4]").val()
                };

            var show_studentdata = $("
\n" +
                        "" + $('[name=matrik_number]').val() + "	\n" +
                        "" + $('#student_name').val()+ "	\n" +
                        "" + $('#student_ic').val() + "	\n" +
                        "" + $('#student_birthplace').val() + "	\n" +
                        "" + $('#faculty_name').val() + "	\n" +
                        "" + $('#student_phone').val() + "	\n" +
                        "" + $('#student_email').val() + "	\n" +
                        "Edit	" +
                        "Remove	" +
                        "
\n");

            //insert modal data to tables/forms

    $('tbody',tab_owner).append(show_studentdata).data(student_data);

                //console.log(student_data);
                //console.log($('tr#C11A007').data());

                //clear all data upon close/save
                $(".modal").on("hidden.bs.modal", function(){
                    $("input").val("");
                    $('[name=optionsRadios4]',form).each(function(){
                        $(this).prop('checked',false).uniform('refresh');
                    });
                    $('#student_photo').attr('src', '');
                    $("[name=matrik_number]").select2("val", "");
                });
        });

I managed to do the append() part when the add owner button is working. However I am having problem when I want to edit(how to call it back), and to validate the add owner button(inside modal) if the no input has been inserted.
This is the 3rd screenshot to show how the table looks like after adding the owners,

Marked as number 1, ignore it for now.
Marked as number 2, is the edit button. For now(if you are looking at my codes, I just use find() to get the html contents but I am sure there could be a better way? It will also create a duplicate data if I press "Edit" and correct some info, press Add Owner in the modal again.
I hope my explanation does not confuse those who are reading this. I have been stuck to this for about a week now.
Thanks in advance.

A: If I understand your question correctly, you are trying to edit a row in your table. But the code you have written would add a new row every time you will edit an existing record. That is because of the following line which creates a new row.
$('tbody', tab_owner).append(show_studentdata).data(student_data);
In order for you to be able to edit the row you need to replace the old row with the new one.
In tab_owner.on(), you have access to current tr. You can keep this in a global variable like
selectedRow = $(this).closest('tr');
(be sure to clean if afterwards)
Later, in large.on(), you can do the following
if (selectedRow && selectedRow.length) { // check if in edit mode
    selectedRow.replaceWith(show_studentdata).data(student_data);
  } else { // add mode
    $('tbody', tab_owner).append(show_studentdata).data(student_data);
  }

be sure to clear selectedRow in add
tab_owner.on('click', '.add-owner', function(e) {
  e.preventDefault();

  selectedRow = null;
});

For the validation part, you can check for the conditions on student_data variable in large.on() and return in case of validation fail. like
if (student_data.email == "") {
    return;
  }

Hope this helps


text:
Q: Admin Themes based on user role is there a way to assign different user roles different admin themes? I have looked into the documentation but it seems no one thought of this issue.

A: A quick and dirty way to achieve what you want is by adding a theme class to the document body on document ready in a custom admin theme.
Basic example:
var changeTheme1 = jQuery('.admin-user-account-text').text()=='user'

//change theme
if(changeTheme1){
jQuery('body').addClass('theme1');
}

Maybe it helps.


text:
Q: Jquery MVC 4 Client side Validation Won't Work I'm trying to use the jQuery validation plugin on a simple MVC 4 application - something I've done in MVC 3 with no problems, but I can't get it working at all.
I want the validation to fire when:
1 - my control looses focus .
2- on form submit.
Any ideas on what I've missed would be appreciated !
Script references in _Layout.cshtml

    <meta charset="utf-8" />
    <title>@ViewBag.Title - AWC Web Console</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

Index.cshtml markup with validation JS applied in Doc ready function

Body of form markup

@{
     ViewBag.Title = "Messages";
     Layout = "~/Views/Shared/_Layout.cshtml";
}

@using ( Html.BeginForm("SelectProduct", "WMSMessages", Model, FormMethod.Post, new {  @id = "prodIdFilterForm"} ) )
{
   <fieldset class="filtering">
      <legend>SelectExtensions Product</legend>

         Product Id:
         @Html.TextBoxFor(model => model.productId_str, new { @id ="productId_str"}  )

            <input type="submit" value="Show Messages" />

   </fieldset>
}

A: For client side  validataion microsoft uses jquery.validate.unobtrusive.js file.
Client side validation asp.net mvc

Enabling Client-Side Validation
To enable client-side validation in ASP.NET MVC 3, you must set two
  flags and you must include three JavaScript files.
Open the application's Web.config file. Verify that
  ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to
  true in the application settings. The following fragment from the root
  Web.config file shows the correct settings:

 <appSettings>
  <add key="ClientValidationEnabled" value="true"/>
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 </appSettings>

Setting UnobtrusiveJavaScriptEnabled to true enables unobtrusive Ajax and unobtrusive client validation. When you use unobtrusive validation, the validation rules are turned into HTML5 attributes. HTML5 attribute names can consist of only lowercase letters, numbers, and dashes
for example if you said required attribue for email and with its error message. it will append data-attributes to element like this.
 <input data-val="true"
        data-val-required="Email is required (we promise not to spam you!)."
        id="Email" name="Email" type="text" value="" />

Setting ClientValidationEnabled to true enables client-side validation. By setting these keys in the application Web.config file, you enable client validation and unobtrusive JavaScript for the entire application. You can also enable or disable these settings in individual views or in controller methods using the following code:
for more info :

*

*Asp.net MVC validation

*MVC client side validation


text:
Q: How to define contrast colors in extending a palette in Angular Material theme Angular Material Documentation for theming states the following to extend an existing palette for custom theming-
var neonRedMap = $mdThemingProvider.extendPalette('red', {
    '500': '#ff0000',
    'contrastDefaultColor': 'dark'
  });

In this, if i want to specify which color i want as the contrast using
'contrastLightColors': ['800']

is it possible? Doesn't seem to be working at all. Just defaults to black on giving contrastDefaultColor.
Is defining a whole new custom palette for this the only option?
I can't exactly use color css property since there are icons also that need to take that color. All those icons are web components (Angular 1.5x) so i want a centralised control over the colors.
What should i do?


text:
Q: 2 Way Encryption Algorithm that for both Ruby & Node.JS that only encrypts to letters and numbers I have a node.js server that will encrypt a string and store it into a database. I also have a RoR(Ruby on Rails) server that will retrieve the encrypted string from the database and decrypt it. The only criteria I have is that the encryption must only encrypt strings into a string of letters and numbers (no special characters)
Any suggestions

A: As others have suggested, a strong encryption like AES-CBC or AES-CTR together with Base-64 is one solution.  Base-64 uses +, / and = in addition to the 62 alphanumeric characters.  Hex (Base-16) is strictly alphanumeric, but takes more storage space.  Base-32 only has the padding character, =, like Base-64.  In a pinch it is possible to omit padding, and to recalculate in for decoding.
If you are wiling to accept a lower level of security then one alternative is to use a Vigenère cypher, where you can explicitly determine the input and output characters allowed.


text:
Q: Nuxt Universal Mode not helping with vue meta i am using nuxt for my application and have default mode i.e. universal mode. As i needed to make support of meta tags. But even though i have ssr mode and i can see ssr thing when inspecting the page, it's picking up default meta description, image etc instead of dynamic one that i have mentioned in different pages.
As visible in below image i have hid mentioned too, to avoid duplication, but it still picks the one which is the default in config file

A: You're a little confuse
Nuxt offers 3 ways to manage meta tags. You can set global on nuxt.config OR locally as object OR locally as function.
You should delete the global configuration before use meta tags at local (pages) level


text:
Q: NodeJS - Sequelize - Stored Procedure - is not working I am trying do find what is the problem with my code below, I am using the plugin Tedious (SQL Server), sequelize and NodeJs:
exports.getCreditsGeneral = function(sgecode) {
    return sequelize.query('[dbo].[SP_ListaCreditos](:sgecode1)',
          { replacements:{sgecode1: sgecode}})
          .then(total => {
               return total.length ? total : 0
          })
}

Can someone help me please?
Thanks.

A: you are missing exec parameter
exports.getCreditsGeneral = function(sgecode) {
    return sequelize.query('exec [dbo].[SP_ListaCreditos](:sgecode1)',
          { replacements:{sgecode1: sgecode}})
          .then(total => {
               return total.length ? total : 0
          })
}