text:
Q: Initialize primitives or not - c++ When do I need to initialize variables in c++? Some people assert that its important but maybe this is more an issue in c-language?
I am refferering to primitives i.e. char, int, long, double
Let say I have the following code-snippet
 int len;
 double sum, mean;
 char ch;

 while (true) {

    // here I use these primitives where they are initialized.

 }

So - should I initialized these primitives as a good programming pratice here?

A: The problem is, of course, the use of unitialised variables as in
int x;
int y=1+x; // oops what is y?

AFAIK, the language standard allows the compiler to initialise x to 0, but also to leave it unitialised. In any case, most optimisations (-O) will omit an initialisation in the above situation.
If you use full warning compiler flags (e.g. -Wall -Wextra -pedantic) the compiler will almost certainly spot the usage of unitialised variables (it will also warn about usage of unitialised variables in library header files, such as boost headers -- the boost developers appear to not use such useful diagnostics).
In general, whether or not to initialise all variables is a matter of style. I would provide an explicit initialisation whenever there is a sensible initial value for a variable and/or if there is the danger of it being used unitialised. Different from C, the possibility of unitialised variables is quite rare in C++, in particular when passing by return value (including move semantics).

A: In c++ compiler usualy do not initialize local (automatic) variables. These variables are created on the stack and they are filled with random values. Usualy you do not need to inicialize variables but read carefuly what the compiler says. Try:
int main() {
int x;
x=x+1;
}

and compile it with -Wall switch (I'm using gcc). When the message
x.cpp: In function 'int main()':
x.cpp:3:6: warning: 'x' is used uninitialized in this function [-Wuninitialized]
x=x+1;

is written, then it would be better to initialize such variable.

A: You should initalize all variables to prevent: "trash in input - trash in output".

A:
When do I need to initialize variables in c++?

You should initialize local variables with a sensible value when you define them. If you cannot give a variable a sensible value yet, then you should probably define it later.
The goal here is to minimize the amount of state in your functions in order to make them easier to understand. When all variables are defined at the beginning of the function, you don't know what they are used for. When they are defined at the point they are needed, it's clear that they are not used before that point. This also helps to limit the scope in which variables are declared (e.g. inside the loop instead of before it, thus less state outside the loop) and it allows you to define more variables as const (thus not adding state).


text:
Q: Is the Air Hike skill required for any of the collectables? The description for the Air Hike skill suggests you can reach higher locations. So is this skill required for any of the collectables/secrets, or can they all be obtained without it?
If it is required, does this apply to all characters, or a specific one/two?

A: Having now obtained all collectables I can confirm that the Air Hike skill is not required for any of them.
It does make one of the secret missions a bit easier to complete, but it isn't required.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to invoke async method in C# by using reflection and won't cause deadlock? I want to invoke a async method by a Task<T> type reflection instance,I had used Task.WaitAll and .GetAwaiter().GetResult(),but all they will cause deadlock.
How should I do now?
For example:
Given
async Task<T> Add<T>(T model);

This is how I do it
void InvokeByReflection(object model) {
    MethodInfo method = typeof(SAMPLE).GetTypeInfo().GetMethod("Add");
}

How to invoke method without deadlock?

A: It is not clear how reflection has anything to do with deadlock.
Calling async methods is fairly simple:
Critical - need async here:
async void InvokeByReflection(SAMPLE sample, object model) {
   await (Task)typeof(SAMPLE)
       .GetTypeInfo()
       .GetMethod("Add")
       .MakeGenericMethod(new []{model.GetType()})
       .Invoke(sample, new object[]{ model });
}

Optionally, if you're in the web using full .Net Framework, don't forget .ConfigureAwait(false); (this is no longer critical for .Net Core because Kestrel dispatches all requests on the threadpool, not main thread).
UPDATE to get results out:
    async void InvokeByReflectionAndgetResult(SAMPLE sample, object model) {
     var task =(Task)typeof(SAMPLE)
     .GetTypeInfo()
     .GetMethod("Add")
     .MakeGenericMethod(new []{model.GetType()})
     .Invoke(sample, new object[]{ model });
     await task;
     var result = task.GetType().GetProperty("Result").GetValue(task);
    }


text:
Q: Angular Application Data Binding is Not Working I am consuming wcf rest service into angular js application . I am trying to get account information based on account number . but the problem is its displaying text Account_Type three times then showing the values .
Here is the method code .
  public string AccountDetails(string Account_Number)
        {
            var accountNumber = int.Parse(Account_Number);//It could be better to use TryParse
            using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
            {
                var inOut = context.Current_Account_Deposit.Where(x => x.Account_Number == accountNumber).Select(w => new AccountTransaction
                {
                    Account_Number = w.Account_Number,
                    Account_Balance = (decimal?)0M,
                    Deposit = (decimal?)w.Amount,
                    Withdrawal = (decimal?)null,
                    Date = w.Date,
                     Account_Type=null,
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName =null,
                    Account_Holder_LastName = null
                }).Union(context.Current_Account_Withdraw.Where(x => x.Account_Number == accountNumber).Select(d => new AccountTransaction
                {
                    Account_Number = d.Account_Number,
                    Account_Balance = (decimal?)0M,
                    Deposit = (decimal?)null,
                    Withdrawal = (decimal?)d.Amount,
                    Date = d.Date,
                    Account_Type = null,
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName = null,
                    Account_Holder_LastName = null
                })).OrderBy(r => r.Date)
                .Union(context.Current_Account_Details.Where(x => x.Account_Number == accountNumber).Select(e => new AccountTransaction
                {
                    Account_Number = e.Account_Number,
                    Account_Balance = (decimal?)e.Account_Balance,
                    Deposit = (decimal?)0M,
                    Withdrawal = (decimal?)0M,
                    Date = e.Account_Creation_Date,
                    Account_Type=e.Account_Type,
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName =null,
                    Account_Holder_LastName = null

                }))
                .Union(context.Current_Account_Holder_Details.Where(x=>x.Account_Number ==accountNumber).Select(d=> new AccountTransaction
                {
                    Account_Number = d.Account_Number,
                    Account_Balance = null,
                    Deposit =null,
                    Withdrawal = null,
                    Date = null,
                    Account_Type = null,
                    Account_Holder_Tittle =d.Tittle,
                    Account_Holder_FirstName=d.Account_Holder_First_Name,
                    Account_Holder_LastName=d.Account_Holder_Last_Name

                }));
                var js = new System.Web.Script.Serialization.JavaScriptSerializer();
                return js.Serialize(inOut);
            }
        }

Here is the code .
@{
    Layout = null;
}

<!DOCTYPE html>

    <title></title>

        Account Number:
        <input type="text" ng-model="Account_Number" />
        <input type="button" value="Submit" ng-click="Search()" />

Account Type:{{m.Account_Type}}

Here is the scrren shot when i run the application .

A: If you need Account_Type, you don't need an ng-repeat here. just assign the value to the $scope variable
 $scope.Account_Type = details[0].Account_Type;


text:
Q: How to provide ArrayList content for Intent.ACTION_GET_CONTENT I have an app where you can select multiple images. This app also will appear in the chooser dialog for attachments of images from different clients like Gmail, Message app, WhatsApp etc.
When i open WhatsApp and i press attach photo, i will choose my app, select multiple images and i will set them to be returned to WhatsApp. How to send multiple images to client?
Here is what i wrote:
 ArrayList<Uri> uris = new ArrayList<Uri>();
 for (int i = 0; i < tempFile.size(); i++)
  { File fileIn = tempFile.get(i);
    Uri u = Uri.fromFile(fileIn);
    uris.add(u);
  }
  if (tempFile != null) {
  Intent data = new Intent(Intent.ACTION_SEND_MULTIPLE);
  data.setType("image/png");
  data.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
  MainActivity.getInstance().setResult(Activity.RESULT_OK,data);
  getActivity().finish();

Thanks for help!

A: Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));


text:
Q: Using pandas to filter data frame for the most popular factors Suppose I have a data set with factors in pandas and I have factors 'A' through 'Z' and suppose factors 'A', 'B', and 'C' have 30 observations while the rest only have 5.  There are other columns in this data frame but I am only concerned about this column of factors (let's call it factor1).
What operation do I use with pandas to filter this data frame so that the only rows in the data frame are those whose factors that have more than 20 observations? What operation do I use if I want the top 3 most popular factors for factor1 in the data frame?
EDIT:
Here's a limited set of code
data = {'factor1':['A','A','A', 'B', 'B', 'B', 'C','C', 'D'], 'factor2':['apple','apple','apple','apple','apple','apple','orange','orange','orange'], 'response':range(9)}
df = pandas.DataFrame(data)

How do I filter df so that factor1 has the top 3 most popular factors or factors that have a frequency greater than 5 (or n or whatever really)

A: Try this for the top 3 most popular factors:
N = 3
handy = df.groupby('factor1')['factor1'].count()
handy.sort('factor1',ascending=False)
topNFactors = handy.head(N)
print topNFactors

dataOfTopNFactors = df[df['factor1'].map(lambda x: x in topNFactors)]
print dataOfTopNFactors

Or try this for the factors with frequency at least 2:
M = 2
handy = df.groupby('factor1')['factor1'].count()
minimumValueMFactors = handy[handy>=M]
dataOfMinimumValueMFactors = df[df['factor1'].isin(minimumValueMFactors.index)]
print dataOfMinimumValueMFactors


text:
Q: ILMerging Windows Forms application with couple localizations problem I've created a Windows Forms (C#) application called "Image Processing". It uses many external dlls so I decided to use ILMerge to merge all of them into one exe file and it worked. But today I've localized my application. After building I had 3 new folders in Debug folder: "en-US", "ru-RU", "uk-UA" with one dll with the same name "ImageProcessing.resources.dll". So I included all of them in a ILMerge command:
ILMerge.exe /t:winexe /out:ImageProcessingRelease.exe ImageProcessing.exe AForge.dll AForge.Imaging.dll AForge.Math.dll DevExpress.Data.v10.2.dll DevExpress.Utils.v10.2.dll DevExpress.XtraBars.v10.2.dll DevExpress.XtraEditors.v10.2.dll FreeImageNET.dll uk-UA\ImageProcessing.resources.dll ru-RU\ImageProcessing.resources.dll en-US\ImageProcessing.resources.dll

My program stores language locale in settings. After merging I can't change language, but settings are changing.
I don't know what else I can include here for more details so tell me please what.

A: The answer is simple. ILMerge is not suitable in this case, as .NET Framework relies on the folder structure to determine which resource file to use.
It is meaningless to combine assemblies in that way, and some third party assembly vendor's end user license does not permit you to merge their product with your own assemblies.


text:
Q: menu css and javascript not working Hello I am having a real problem implementing the code below in the JSFiddle. It works perfectly in the fiddle but when I implement it into my website it does not work. Below is an image of what I have in my html. It is a horizontal menu bar with a drop down horizontal menu bar below.
The JSFiddle of what I am trying to achieve The main difference that I can see is making the css .active instead of .hover which is what I had previously.

The CSS that is not working
#menu, #menu ul {
margin: 0 auto;
padding: 0;
background-color: #FFFFFF;
}
#menu {
font-weight:400;
display: table;
width: 100%;
list-style: none;
position: relative;
top: -20px;
text-align: center;
left: -10px;
-webkit-box-shadow: 0px 3px 5px 0px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 0px 3px 5px 0px rgba(50, 50, 50, 0.75);
box-shadow: 0px 3px 5px 0px rgba(50, 50, 50, 0.75);
font-size: 18px;
height: 20px;
z-index: 1101;
}
#menu.fixed {
position: fixed;
top: 0;
width: 100%;
}
#menu li {
display: table-cell;
list-style: none;
padding-right: 10px;
left: 50px;
vertical-align: middle;
}
#menu > li.active > ul {
background:#FFF;
display: block;
left: 0;
width: 100%;
-webkit-box-shadow: 0px 3px 2px 0px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 0px 3px 2px 0px rgba(50, 50, 50, 0.75);
box-shadow: 0px 3px 2px 0px rgba(50, 50, 50, 0.75);
border-top:thin dotted #999;
top: 32px;
height: 30px;
}
#menu > li > ul {
display: none;
position: absolute;
 text-align: center;

}
#menu li a {
display: block;
padding: 2px 10px;
text-decoration: none;
font-weight: 400;
white-space: nowrap;
color: #333;

}
#menu li a:hover {
color: #28B701;
font-size: 18px;
vertical-align: middle;
font-family: 'Lato', "sans-serif; 700;";
}
#menu li ul li {display: inline-block;
float:none; }

This is a livelink of the broken page as I believe this is a site specific issue, I shall delete it for future posterity of this post.
PLEASE PLEASE HELP ME!

A: Your issue is that you are executing the javascript for the menu before the page is finished loading. The reason it works in the jsFiddle is because you have it set to execute the javascript 'onLoad', but in your actual website you are executing it immediately.
The solution is to wrap your javascript code in the jQuery DOM Ready event handler so that it executes when the DOM is ready:
$(function () {
    $('#menu > li').hover(function() {
        $( this ).addClass( "active" ).siblings().removeClass("active");
    });
});

Updated Fiddle


text:
Q: Vline - anyway to prevent connecting panel covering the browser? I am using vline php for video chatting in my websites, the video call has no problem,
but each time, when user1 call user2, after user2 answer the call, there would be a big gray screen in user1's browser with a center box saids "connecting user2".  The big gray screen would be stayed there with user1's video chat screen, and it really affects the image sharpness for user1. In user2's browser, there is only the video chat screen which has no problem.
So the question is, is there anyway to remove the gray screen for caller?
I used chrome "Inspect element" and have found out the gray panel is a div brought in by vline.css, which looks like this:

I edited "opacity:0" using "Inspect element" and the panel is disappeared successfully, so I tried to change the div style before startmedia by using this code:
    if(button.hasClass('active')){
              var cusid_ele = document.getElementsByClassName('vl-not-dialog-bg');
              for (var i = 0; i < cusid_ele.length; ++i) {
              var item = cusid_ele[i];
              item.style.opacity = 0;
              }

            person.startMedia();
            }

but no luck, the gray panel still exists when caller make calls, check that div's opacity again, still opacity:1, so what can I do, how can I change the css element which from https://static.vline.com/vline.css?
Any help would be greatful.


text:
Q: Fastest way to find a String into an array of string The script has to verify if one predefined IP is present in a big array of IPs. Currently I code that function like this (saying that "ips" is my array of IP and "ip" is the predefined ip)
ips.each do |existsip|
  if ip == existsip
    puts "ip exists"
    return 1
  end
end
puts "ip doesn't exist"
return nil

Is there a faster way to do the same thing?
Edit : I might have wrongly expressed myself. I can do array.include? but what I'd like to know is : Is array.include? the method that will give me the fastest result?

A: You could use the Array#include method to return you a true/false.
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
if ips.include?(ip) #=> true
  puts 'ip exists'
else
  puts 'ip  doesn\'t exist'
end

A: You can use Set. It is implemented on top of Hash and will be faster for big datasets  - O(1).
require 'set'
s = Set.new ['1.1.1.1', '1.2.3.4']
# => #<Set: {"1.1.1.1", "1.2.3.4"}>
s.include? '1.1.1.1'
# => true

A: ips = ['10.10.10.10','10.10.10.11','10.10.10.12']

ip = '10.10.10.10'
ips.include?(ip) => true

ip = '10.10.10.13'
ips.include?(ip) => false

check Documentaion here

A: A faster way would be:
if ips.include?(ip)
  puts "ip exists"
  return 1
else
  puts "ip doesn't exist"
  return nil
end

A: have you tried the Array#include? function?
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
You can see from the source it does almost exactly the same thing, except natively.


text:
Q: Swift and Ionic framework I want to move my app written on Swift in Ionic framework. What is the best way to achieve this?
Is there a workaround to write swift in Visual studio? What tools I need to set this project up.
p.s I work on PC and prefer visual studio

A: basically you need to re-write the whole logic/code of your application on a Javascript based framework  and use Ionic/AngularJS for the Frontend.


text:
Q: Finding an open simply connected subset in a punctured open simply connected set Let $X$ be an open , simply connected (path connected with trivial first homotopy group) subset of $\mathbb R^2$. Let $0\in X$.
Is it true that for every $p,q\in X\setminus \{0\}$, there is an open , simply connected subset $A_{pq}\subseteq X\setminus \{0\}$ such that $p,q\in A_{pq}$ ?

A: Yes.  In fact, the assumption that $X$ is simply connected is unnecessary (you just need it to be connected and open), so we may replace $X$ with $X\setminus\{0\}$ to simplify notation.
To prove this, note that if $p\neq q$, we can find a polygonal path from $p$ to $q$ in $X$ which does not intersect itself.  Taking sufficiently small open balls around each segment of this polygonal path, we get a simply connected open subset of $X$ containing $p$ and $q$.  (You just have to choose your balls so that the ball around each segment only intersects the balls around the two neighboring segments and no others.  Then you can show by induction that the union of the first $n$ balls is simply connected, since the intersection of the $n$th ball with the union of the first $n-1$ balls is convex and in particular connected.)


text:
Q: WiX Burn BA - download payloads behind OAUTH, and is there a possibility to change the UpdateLocation and re-run engine detect? I currently spike with WiX 3.11.2 to build a burn bootstrapping application that downloads packages from a local http server currently without any authentication.
Due to a lack of documentation of WiX burn I mostly reverse engineered how to set the UpdateLocation + how to check for updates via skimming through the UpdateViewModel.cs from the Wix3 repository.
As far as I have read, the
Engine.SetDownloadSource(ea.PackageOrContainerId,ea.PayloadId, dlUrl,user,pass);
can be used to download with no AUTH (last 2 parameters null) or plain authentication. Without authentication I already have a working prototype - but I will need the possibility to authenticate against a OAUTH secured web server.
If I were to need for instance to download behind a OAUTH2 authentication would the best practice be to use the OnResolveSourdce Event and instead of setting the Result to Result.Download, just do it myself with OAUTH2 libraries and download it to the ea.LocalSource so the engine basically thinks that the source has always been already available?
My second question is with regards to the UpdateLocation.
In the OnDetectUpdateBegin event I can set the ea.Result to Result.Ok if I want to check for upates - but I would like to be able to change the UpdateLocation during runtime, similar to what the Visual Studio Installer allows - to have different ReleaseFeeds, something like PROD or TESTING or Preview.
is there any possiblity to tell the Engine to set the UpdateLocation to a different URI? It would seem that the OnDetectUpdateBegin event would be perfect to change that, but the ea.UpdateLocation only has a Get, and I did not find a Engine.SetUpdate location or anything similar.
If I am not mistaken the VStudio installer is also built upon WiX so I would presume it should be somehow possible - am I missing something here?


text:
Q: Package animate with android Could you please suggest to me a way to visualize on Android systems a PDF which contains animations realized with the animate package? I already tried with the Adobe Reader for Android, but it didn't work.
Thank you in advance!
Maurizio

A: animate-made animations rely on JavaScript. None of the known PDF readers on mobile platforms include a JavaScript engine. Therefore it is currently impossible to play this kind of animations on mobile devices.
Though I doubt it will help a lot, you could vote for a adding JavaScript on the Feature Request page of Acrobat Reader for Android:
https://acrobat.uservoice.com/forums/595576-acrobat-reader-for-android?query=javascript


text:
Q: Unit of measure for raw data in mne.RawArray I am trying to load EEG data from a numpy array into an mne.io.RawArray object. What is the correct unit of measure for the data in the array? Volts?
I read the source for mne.create_info, and it looks like the unit should be volts. Can anyone confirm?

A: Volts. The MNE-Python documentation has been updated: https://github.com/mne-tools/mne-python/pull/3972


text:
Q: How to create percentile-based metric chart? My application generates "score" values for a particular use case. These scores generally are anywhere in the range of 0-120, but most cluster in the range of 60-95.
I currently have a stat chart using counts with cardinality, e.g., 0, 1-12, 13-24, 25-36, ... 97-108, and 109+.
I'd like to instead create a percentile chart with time series lines showing percentile scores in increments of 10%, i.e., 10% score line, 20% score line, 40% score line, etc., up to 90% score line.
Is that even possible? How do I do that, beginning with recording the stat using OpenCensus Java?

A: Cloud Monitoring doesn't really have the ability to calculate percentages at display time the way you're looking for.  You can use OpenCensus to write a distribution with buckets, and you could then query their boundaries and counts - here's an example:
https://cloud.google.com/solutions/identifying-causes-of-app-latency-with-stackdriver-and-opencensus
Specifically, I'm quoting from the Accuracy section:

Monitoring computes latency percentiles for distribution metrics based on bucket boundaries at numeric intervals. This method is a common method used by Monitoring and OpenCensus where OpenCensus represents and exports metrics data to Monitoring. The TimeSeries.list method for the Cloud Monitoring API returns the bucket counts and boundaries for your project and metric types. You can retrieve the bucket boundaries in the Cloud Monitoring API BucketOptions object, which you can experiment with in the API Explorer for TimeSeries.list


text:
Q: Can I get a `Traversal` to items stored in branches using `Control.Lens.Plated`? I can easily get a Traversal to items stored in leaves:
data Tree a = Br (Tree a) (Tree a) | Lf a
    deriving (Data)

instance Plated (Tree a) where

makePrisms ''Tree

leaves :: Traversal' (Tree a) a
leaves = deep _Lf

But deep can't keep going if I take something out of a branch. The best I can seem to achieve with data in branches is a Fold:
data Tree a = Br a (Tree a) (Tree a) | Lf
    deriving (Data)

instance Plated (Tree a) where

makePrisms ''Tree

branchData :: Fold (Tree a) a
branchData = cosmos._Br._1

It is obviously possible to manually construct a Traversal because this Tree can be made Traversable:
instance Traversable Tree where
    sequenceA Lf = pure Lf
    sequenceA (Br x l r) = Br <$> x <*> sequenceA l <*> sequenceA r

Can Plated do it for us automatically somehow?

A: I do not believe it is possible to do using Plated, but it is trivial to do using template from Data.Data.Lens:
branchData :: Data a => Traversal' (Tree a) a
branchData = template

Template finds all elements of a type that can be accessed without going through the same type.

The closest thing to a traversal that I can get from Plated (except for the cosmos fold you mentioned) is transformM :: (Monad m, Plated a) => LensLike' m a a. It can be used as a Setter and can do some other stuff.
The reason that transformM needs a Monad (instead of an Applicative that would be required for a traversal) is that we need to update the children before updating the node, which means that ordering is needed. It is impossible to make a traversal that points at both a node and a child of that node.


text:
Q: How to parse json object in UnityScript? I am following this link http://wiki.unity3d.com/index.php/JSONUtils but not able to parse json object.
What I have tried so far:
function SerializeObject()
{
    var object = {"response":[{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"},{"id":"99","name":"Guest","score":"18","game":"7,8,2,5,6,9,4,3","date":"2015-02-28 11:19:35"},{"id":"89","name":"Guest","score":"17","game":"5,7,2,8,6,1,3,9","date":"2015-02-26 16:39:59"},{"id":"96","name":"Guest","score":"18","game":"2,6,1,5,9,7,8,4","date":"2015-02-26 16:34:05"},{"id":"97","name":"Guest","score":"16","game":"1,7,3,4,8,2,6,5","date":"2015-02-26 16:32:30"},{"id":"95","name":"Guest","score":"14","game":"1,3,7,4,6,9,2,8","date":"2015-02-23 19:20:07"},{"id":"90","name":"Guest","score":"16","game":"8,3,9,6,4,5,2,7","date":"2015-02-23 16:48:55"},{"id":"92","name":"Guest","score":"17","game":"5,2,1,9,7,4,3,8","date":"2015-02-23 16:48:28"},{"id":"91","name":"Guest","score":"16","game":"2,1,3,9,6,7,8,4","date":"2015-02-23 16:48:06"},{"id":"94","name":"Guest","score":"14","game":"5,2,8,7,6,1,9,4","date":"2015-02-23 16:47:25"},{"id":"93","name":"Guest","score":"16","game":"8,9,2,7,4,6,3,1","date":"2015-02-23 16:45:44"},{"id":"88","name":"jacky chain","score":"15","game":"1,2,5,4,7,9,3,6","date":"2015-02-23 13:35:20"},{"id":"87","name":"Genie","score":"15","game":"8,9,5,7,1,4,2,3","date":"2015-02-22 16:19:32"},{"id":"86","name":"Genie","score":"15","game":"9,7,3,2,1,5,8,4","date":"2015-02-22 16:16:13"},{"id":"85","name":"Genie","score":"15","game":"7,1,4,6,5,3,9,8","date":"2015-02-22 14:25:39"},{"id":"83","name":"new","score":"18","game":"2,5,4,1,8,9,7,6","date":"2015-02-22 11:11:49"},{"id":"84","name":"Guest","score":"15","game":"9,8,3,5,1,4,2,7","date":"2015-02-22 09:48:28"},{"id":"80","name":"Guest","score":"16","game":"5,4,2,3,1,8,7,6","date":"2015-02-22 08:24:55"},{"id":"82","name":"Guestr","score":"15","game":"8,1,9,5,7,4,6,3","date":"2015-02-21 21:00:37"},{"id":"81","name":"Guest","score":"18","game":"9,4,2,7,6,5,1,8","date":"2015-02-21 20:54:51"},{"id":"79","name":"Guest","score":"15","game":"2,6,9,5,8,3,1,7","date":"2015-02-21 20:37:30"},{"id":"78","name":"Guest","score":"15","game":"3,6,9,7,1,5,4,2","date":"2015-02-21 20:35:27"},{"id":"77","name":"Guest","score":"17","game":"5,3,7,9,8,4,1,6","date":"2015-02-21 16:04:17"},{"id":"64","name":"Guest","score":"17","game":"7,9,8,4,6,1,3,5","date":"2015-02-21 16:03:41"},{"id":"76","name":"new","score":"18","game":"9,3,4,8,6,5,2,1","date":"2015-02-21 15:27:25"}]};

    for( var test in object.Keys )
    {
        Debug.Log( "Object["+test+"] : "+object[test] );
    }
}

I see the below line in the Log:
 Object[response] : Boo.Lang.Hash[]

Now i want to extract value from this object.
I would appreciate your help on this, thank you.

A: Your log message is telling you that object["response"] is returning an array of hashes as you would expect from the JSON you parsed. Now you need to iterate over that array which will give you each internal hash object, the first one being:
{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"}


text:
Q: How to access Apache virtual-host in VMware guest through NAT? As a webdeveloper I have an Apache server running on my local machine which I use for developing. The server is listening on every IP address on port 80 as per default. However I've used the httpd.conf to control who can access the server and that's basically me and everyone else on the LAN, no outside access is permitted.
I also have some virtual-hosts configured. Something like this goes on httpd-vhosts.conf file:
NameVirtualHost localhost:80

<VirtualHost localhost:80>
  DocumentRoot "C:\Users\Nazgulled\Workspace\Htdocs\Project1"
  ServerName project1.domain.com
</VirtualHost>

On my local machine I access this project website by navigating to project1.domain.com (the same address is pointing to 127.0.0.1 in the hosts file).
On the VMware guest I can easily point to the host's IP address (using NAT as it works better/faster for me) and access the root of the web server, but I can't manage to access the project website navigating to project1.domain.com. I tried to point that address to the hosts's IP address in the hosts file (just like I did in the local machine but with a different address) but it didn't work.
The one thing I tried was to replace localhost:80 by *:80 but it didn't seem to have any effect.
I have no other ideas how can I make this work, suggestions?

A: Suggestions:
You are right, you need to change localhost:80 to *:80.
Add ErrorLog and CustomLog to that VirtualHost and check if it provides any useful information.
To debug try:
curl -H "Host:project1.domain.com" IP-of-your-server

This should give you at least an error message from Apache.
If curl times out then you probably have a general network issue.


text:
Q: Use spannable to highlight only part of already added text I add a text like this:
tv.setText("This is text created with StringBuilder");

Then I track which word a user longclicks on, and want to highlight that word for some short period of time:
tv.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        int offset = tv.getOffsetForPosition(coordinates.get(0), coordinates.get(1));
        int[] offsets = getWordOffsets(text.toString(), offset);
        int startOffset = offsets[0];
        int endOffset = offsets[1];

        // here I want to highlight the word starting from startOffset to endOffset

I've read that I should use SpannableString, however most examples show that I should created new SpannableString using the entire text, and then I can add styles to part of it. Is there any way to make part of the text in TextView spannable? Or should I create new SpannableString strings from TextView content and set spans every time the long click event is triggered?

A: you can use some countdown timer
 //___ HIGHLIGHT HERE ______
    new CountDownTimer(500,500){

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            //___ UN HIGHLIGHT HERE ______

        }
    }.start();

and for the highlight you can use something like
textView.setText(Html.fromHtml("text"));


text:
Q: AFJSONRequestOperation returns null response in iOS I am facing 1 problem while using AFJSONRequestOperation. My API Client is as follows
    #import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"

@interface MyAPIClient : AFHTTPClient

+ (MyAPIClient *)sharedAPIClient;

@end

// .m file
#import "MyAPIClient.h"

@implementation MyAPIClient

+ (MyAPIClient *)sharedAPIClient {

    static MyAPIClient *sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
    });
    return sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {

    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

    [self setDefaultHeader:CONTENT_TYPE_FIELD value:CONTENT_TYPE_JSON_VALUE];
    self.parameterEncoding = AFJSONParameterEncoding;
    return self;
}

@end

Now when I request with following code it returns me "null" response
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:userName,@"email",password,@"password",nil];

    NSMutableURLRequest *request = [[MyAPIClient sharedAPIClient] requestWithMethod:@"POST" path:@"login" parameters:params];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    {
        NSDictionary *dictResponse = (NSDictionary*)JSON;
        DLog(@"Login Success JSON: %@",JSON);
        if (block) {
            block(YES,nil);
        }

    }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        DLog(@"Login Error:- %@",error);
        if (block) {
            block(NO,error);
        }
    }];

    [operation start];

But when I use AFHTTPRequestOperation it reurns me correct output with logged in used info
NSURL *loginUrl = [NSURL URLWithString:kBASE_URL];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:loginUrl];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            userName,@"email",password,@"password",nil];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"login" parameters:params];

    //Notice the different method here!
    AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
                                                                            success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Raw data Response: %@", responseObject);
        NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"Converted JSON : %@", jsonArray);

    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Error: %@", error);
    }];

    //Enqueue it instead of just starting it.
    [httpClient enqueueHTTPRequestOperation:operation];

My server returns JSON response.
What is the problem in above code? Why AFJSONRequestOperation returns null response while
AFHTTPRequestOperation returns me correct response ? Any kind of help is appreciated. Thanks in advance


text:
Q: how can I dynamically select a column from a list of tables and output timestamp results? I have a large number of identical tables containing columns "eventtime" and "eventvalue"
eventtime is TIMESTAMP(6) and eventvalue is NUMBER (but I don't care about it.)
table names are like data_001,  data_002, data_003, etc. all identically defined but it doesn't matter because I have another table called table_list which contains a list of these tables by name.  (They are dynamically generated.)
So "select distinct data_table from table_list" gets you output like
data_001
data_002
data_003
and so on.
I am trying to extract the minimum timestamp from the eventtime column of each table and output it to DBMS_OUTPUT and I can't get it to work.
DECLARE
  mystr VARCHAR(1000);
  v_mystamp TIMESTAMP(6);
  cursor c1 is
    select distinct data_table from table_list order by data_table asc;

BEGIN
FOR rec IN c1 LOOP
     mystr := 'select min(eventtime) into :v_mystamp from ' || rec.data_table;

     execute immediate mystr;
     DBMS_OUTPUT.PUT_LINE(rec.data_table);
     DBMS_OUTPUT.PUT_LINE(v_mystamp);
   END LOOP;
END;

The expected output is a list of tables, and the min(eventtime) from each table.
What I am getting is a list of tables, and then a blank line after each, and I am wondering what I am doing wrong... somehow it is not capturing the min(eventtime) properly (or not outputting it properly?) but I am not sure why.

A: Put INTO clause into execute immediate:
mystr := 'select min(eventtime) from ' || rec.data_table;

execute immediate mystr into v_mystamp ;


text:
Q: ssh channel Fprintln Line Disorderly go ssh channel writer I am writing a ssh server,when i run fmt.Fprintln on ssh.Channel,it show e.g:

help

  Commands:
             clear      clear the screen
                                          exit       exit the program
                                                                       help       display help

the print line style is not expected
my code:
func handleShells(channel ssh.Channel, sshConn *ssh.ServerConn, reg map[string]interface{}) {
    defer channel.Close()
    fmt.Fprintln(channel, ">>help")
    fmt.Fprintln(channel, "Commands:")
    fmt.Fprintln(channel, "  clear      clear the screen")
}

is there any other way to solve this problem?
Thanks alot in advance

A: If the output appears as "stairs" like this, that's typically a sign of a mismatch in line endings. There are three line-ending styles:

*

*CR+LF (Windows)

*LF only (Unix)

*CR only (old macOS)

It looks like your client expects CR+LF, yet you are sending only LF characters. Is the client on Windows? Does it have a way to switch to "Unix" line endings?


text:
Q: What does this test really do (Loopback TCP Network Performance)? I found in the phoronix test suite a micro benchmark called "Loopback TCP Network Performance 1.0.1", the same kind of command used here:
nc -d -l 9999 > /dev/null  &
time dd if=/dev/zero bs=1M count=10000 | nc localhost 9999

Does it really stress the physical network interface or only the related kernel layers?
So the question is: can we consider this command a "network" test?

A: It does not test any physical network infrastructure, not even the local network interface.
What is tested it the loopback interface. It is roughly a virtual network interface that connects a computer to itself.
The test consists of sending zero bytes through the layers of the TCP/IP implementation, down to the simulated hardware device loopback, and back up the stack again.
The test tells you how fast the network stack implementation is, which depends mainly on how often the network data needs to be copied on the way. Only the throughput is tested, the latency is ignored.
The result should not be of much practical relevance as long as the machine is fast enough to handle the traffic. Maybe it's relevant with a 10GB network connection, or multiple 1GB connections.
On a single processor machine, I suspect that the main influence to the performance would be the process scheduling of the reader and writer - it would more like test the scheduling algorithm. But assuming both nc instances can use a separate CPU core, that should not be a problem.
It could be considered a network test in the sense that the network stack implementation in the kernel is an important part of the network.


text:
Q: Proving the direct product D of two groups G & H has a normal subgroup N such that N isomorphic to G and D/N isomorphic to H Let $D = G \times H$ be the direct product of groups $G$ and $H$. Prove that $D$ has a normal subgroup $N$, such that $N$ is isomorphic to $G$ and $D/N$ is isomorphic to $H$.
Here's where I stand...I know what a direct product is and I know what a normal subgroup is but I have no idea how to prove that the direct product of two such arbitrary groups has a normal subgroup.
And then with the isomorphisms. I know how to show basic isomorphisms, show that a mapping is homomorphic and then show that it is onto and one to one, but I don't know how you would show isomorphisms from completely arbitrary subgroups to groups.

A: HINT: Let $N=G\times\{1_H\}$, where $1_H$ is the identity in $H$. For any $\langle g,h\rangle\in G\times H$,
$$\langle g,h\rangle N\langle g,h\rangle^{-1}=\langle g,h\rangle N\langle g^{-1},h^{-1}\rangle=\dots\;?\tag{1}$$
If you make use of the fact that $N=G\times\{1_H\}$, it shouldn't be too hard to explain why $(1)$ eventually simplifies to $N$, showing that $N$ is normal in $G\times H$.
Then you just have to figure out what the cosets of $N$ are in $D=G\times H$; once you've done that, an isomorphism between $D/N$ and $H$ should be pretty apparent.


text:
Q: How to generate summary statistics (using Summarizer.metrics) in streaming query? Currently, I am using spark structured streaming to create data frames of random data in the form of (id, timestamp_value, device_id, temperature_value, comment).
Spark Dataframe per Batch:

Based on the screenshot of the data frame above, I would like to have some descriptive statistics for the column "temperature_value". For example, min, max, mean, count, variance.
My approach to achieve this in python is the following:
import sys
import json
import psycopg2
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
from pyspark.sql.functions import from_json, col, to_json
from pyspark.sql.types import *
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
from pyspark.sql.functions import get_json_object
from pyspark.ml.stat import Summarizer
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import StandardScaler
from pyspark.sql.functions import lit,unix_timestamp
from pyspark.sql import functions as F
import numpy as np
from pyspark.mllib.stat import Statistics

spark = SparkSession.builder.appName(<spark_application_name>).getOrCreate()
spark.sparkContext.setLogLevel("WARN")
spark.streams.active

data = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "kafka_broker:<port_number>").option("subscribe", <topic_name>).option("startingOffsets", "latest").load()

schema = StructType([
    StructField("id", DoubleType()),
    StructField("timestamp_value", DoubleType()),
    StructField("device_id", DoubleType()),
    StructField("temperature_value", DoubleType()),
    StructField("comment", StringType())])

telemetry_dataframe = data.selectExpr("CAST(value AS STRING)").select(from_json(col("value").cast("string"), schema).alias("tmp")).select("tmp.*")

telemetry_dataframe.printSchema()

temperature_value_selection = telemetry_dataframe.select("temperature_value")

temperature_value_selection_new = temperature_value_selection.withColumn("device_temperature", temperature_value_selection["temperature_value"].cast(DecimalType()))

temperature_value_selection_new.printSchema()

assembler = VectorAssembler(
  inputCols=["device_temperature"], outputCol="temperatures"
)

assembled = assembler.transform(temperature_value_selection_new)

assembled_new = assembled.withColumn("timestamp", F.current_timestamp())

assembled_new.printSchema()

# scaler = StandardScaler(inputCol="temperatures", outputCol="scaledTemperatures", withStd=True, withMean=False).fit(assembled)

# scaled = scaler.transform(assembled)

summarizer = Summarizer.metrics("max", "min", "variance", "mean", "count")

descriptive_table_one = assembled_new.withWatermark("timestamp", "4 minutes").select(summarizer.summary(assembled_new.temperatures))
#descriptive_table_one = assembled_new.withWatermark("timestamp", "4 minutes").groupBy(F.col("timestamp")).agg(max(F.col('timestamp')).alias("timestamp")).orderBy('timestamp', ascending=False).select(summarizer.summary(assembled.temperatures))

#descriptive_table_one = assembled_new.select(summarizer.summary(assembled.temperatures))

# descriptive_table_two = temperature_value_selection_new.select(summarizer.summary(temperature_value_selection_new.device_temperature))

# -------------------------------------------------------------------------------------

#########################################
#               QUERIES                 #
#########################################

query_1 = telemetry_dataframe.writeStream.outputMode("append").format("console").trigger(processingTime = "5 seconds").start()#.awaitTermination()

query_2 = temperature_value_selection_new.writeStream.outputMode("append").format("console").trigger(processingTime = "8 seconds").start()#.awaitTermination()

query_3= assembled_new.writeStream.outputMode("append").format("console").trigger(processingTime = "11 seconds").start()#.awaitTermination()

#query_4_1 = descriptive_table_one.writeStream.outputMode("complete").format("console").trigger(processingTime = "14 seconds").start()#.awaitTermination()
query_4_2 = descriptive_table_one.writeStream.outputMode("append").format("console").trigger(processingTime = "17 seconds").start()#.awaitTermination()

Summarizer documentation.
Based on the posted code, I am isolating the column "temperature_value" and then I vectorize it (using VectorAssembler) to create the column "temperatures" of type vector.
What I would like is to output the result of the "Summarizer" function to my console. This is why I use "append" for outputMode and format "console". But I was getting this error: pyspark.sql.utils.AnalysisException: 'Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark. Thus, I used the "withWatermark" function but I am still getting the same error with the outputMode "append".
When I tried to change the outputMode to "complete", my terminal was instantly terminating the spark streaming.
Instant streaming termination:

My questions:

*

*How should I use the "withWatermark" function in order to output the summary statistics of the vector column "temperatures" to my console?

*Is there any other approach to calculate descriptive statistics for a custom column of my data frame, which I may miss?
I appreciate any help in advance.
EDIT (20.12.2019)
The solution has been given and accepted. Although, now I get the following error:

A:
When I tried to change the outputMode to "complete", my terminal was instantly terminating the spark streaming.

All your streaming queries are up and running, but (the main thread of) the pyspark application does not even give them a chance to run for long (since it does not await any termination due to #.awaitTermination()).
You should block the main thread of the pyspark application using StreamingQuery.awaitTermination(), e.g. query_1.awaitTermination()


text:
Q: why does htop meter show >90% while table is 0.0%? Why do the progress meters across the top of the screen in htop show CPU usage consistently above >90% while the numbers in the table below show a nearly idle system with CPU usage and load average at 0.0%?

A: htop is unaware it is running on a kernel level virtualized environment (Dreamhost VPS is using VServer technology). It is then showing the CPU usage for all the OS instances sharing the same kernel, not just yours.
Have a look to vtop output which sho ws all processes sharing the CPUs, not just the ones in your container.
If vtop is not installed, and this is probably expected for a commercial solution as one wouldn't like to a customer to see what processes are running other customers, there is no way to fix the issue from inside your container, unless patching top source to compute CPU usage instead of getting it from the kernel statistics.
It might do it by summing up CPU usage of all the processes running in your VServer, e.g.:
ps aux | awk '
    {cpu+=$3; ram+=$6}
    END {printf("cpu: %d%%, RAM: %.2f MiB\n",cpu,ram/1024) }'

A: This sort of inconsistency is usually indicative of high processor usage by kernel threads, which aren't displayed in htop by default. To display them, in htop go to Setup, then Display options, and then uncheck Hide kernel threads. This should allow you to see the thread(s) that are responsible.
You can also disable this behaviour by setting hide_kernel_threads to 0 in ~/.htoprc.

A: Try launching htop with sudo. You need root access to see those active threads in the table.


text:
Q: Erroneous loop comparing lists I am trying to write a script that will take as input lottery numbers and also a lotto ticket, then see how many matches there are and print this.
I am however having troubles with my loop that compares the elements from two lists. What am I doing wrong?
READ: Serious newbie here.
#sets LOTTO ticket line
def makeOneTicket(myNums):
    for i in range(0,6):
        nr = input()
        myNums.append([nr])
    return myNums

def makeTicketList(numTix, ticList):
    ticket = []
    for i in range(0,numTix):
        ticket = makeOneTicket(ticket)
        ticList.append([ticket])

        if i == numTix -1:
            print "Done."
        else:
            print "Next ticket."
    return ticList

def checkTicketMatch(list1, list2):
    counter = 0
    for element in list1:
        if element in list2:
            counter = counter + 1
    return counter

winNums = []
myNums = []
ticList = []
print "Please enter winning LOTTO numbers: "
makeOneTicket(winNums)

print "-----------------------------"
print winNums
print "-----------------------------"

print "How many tickets do you have?: "
numTix = input()

print("Enter your lotto numbers one by one: ")
ticList = makeTicketList(numTix, ticList)

matches = 0
matches = checkTicketMatch(winNums, ticList[0])
print matches

A: A few issues with Python:
When you do this line :
myNums.append([nr])

That means your ticket will not look like [1, 1, 2, 3, 5], but [[1], [1], [2], [3], [5]].
Instead, you should do
myNums.append(nr)

This doesn't directly cause your bug, but later on, when you do
ticList.append([ticket])

... your list of tickets also becomes [[ticket], [ticket]], so then when you do your comparison, you're comparing a list of size one (containing a ticket) to a ticket.
That is the source of your problem.
Another issue with your code: there are two ways of making a function that makes a list, by creating it:
def make_list():
    result = []
    result.append(3)
    return result

my_list = make_list()

or passing it inline, as you would often do in C:
def fill_list(_list):
    _list.append(3)

my_list = []
fill_list(my_list)

...you seem to have functions that do both at the same time, which works, but is overkill.


text:
Q: UILabel Value of type 'String' have no member 'text' (Static Custom Cell) I'm getting user information from json but when I assign the values to my labels, it shows the error (Value of type 'String' have no member 'text').
Is it because the Custom static table cell? How to fix it? My foundation is not good...

And:

A: Use different variable names. Its good practise to have unique variable names
As the variable names are same as variable values you are getting the error
UILabel has name empNameLabel : UILabel(In viewDidLoad) and value also has same name.
change
let empNameLabel = user!["crew_name"] as? String //conflicting name with UILabel iboutlet

to
let empNameValue = user!["crew_name"] as? String //variable name is unique

Also you should not force unwrap options(user in your case)
it should be
var empNameValue = ""
if let unwrappedUser = user {
    if let empNameValue = unwrappedUser["crew_name"] as? String {
        empNameLabel.text = empNameValue //assign value to UILabel
    }
}

A: You are trying to get ".text" value from "String" which is not possible.
Either use self:
self.empnameLabel.text = empnameLabel

or give different names to string constant:
self.empnameLabel.text = str

or directly store that value to lable:
self.empnameLabel.text = user[crewname]! as! String

A: This is what happens when you give the outlet and variable the same name.
The variable empNameLabel has no property called text.
text is the property of empNameLabel outlet.
change the variable name. Eg
let empName = user!["crew_name"] as? String

A: *

*Change your label variable name

*Set your newLabelVariable.text to the empNameLabel


text:
Q: How can I find percent complete in ActiveRecord? I can't seem to find an elegant way of doing this.
But let's say my model Projects has many Tasks.
Each task has a boolean field for complete.
So if I have 10 tasks and 4 are "complete" and 6 are not, then I am only 40% complete.
Is there a slick way of doing this in a scope so that the SQL is lean?
I already have two scopes like:
  scope :complete, lambda {
    where("tasks.complete = true")
  }

  scope :not_complete, lambda {
    where("tasks.complete = false")
  }

Thanks for any tips.

A: I would think that since you're looking to get a final value out of this a model method would be the best approach. (scopes should return a Relation in order to support chaining) You could use these scopes to return the percent complete, something along the lines of:
def percent_complete
  not_complete.size.to_f / complete.size.to_f
end

Or if you require big_decimal and big_decimail/util in your model you could use to_d to get decimal division. Then in your view all you have to do is @project.percent_complete


text:
Q: Compute a set $S$ given information about how it is acted upon transitively by $D_8$
Let $D_8=D_{2 \cdot 4}$ be the dihedral group on a regular $4$-gon. Suppose that  $S$ is a subset of $S_4$, such that S contains the element $( 1 \ 2 \ 3)$. We also know that $D_8$ acts transitively on $S$ via the action:
  $$ D_8 \times S \mapsto S$$
$$ (\sigma, s) \mapsto  \sigma \circ s $$
  Task: determine $S$

My approach:

There are a lot of details, but we have to start somewhere. We can start with the orbit-stabiliser theorem:
$$ |D_8|=|\text{Stab}(( 1 \ 2 \ 3))|\cdot |\text{Orb}(( 1 \ 2 \ 3))|$$
Because we know that $D_8$ acts transivitely on our set $S$, the orbits is all of $S$,
$$ 8=|\text{Stab}(( 1 \ 2 \ 3))|\cdot |S|$$
We know there is only one element in $D_8$ that fixes/stabilises $(1 \ 2 \ 3)$, this is the identity symmetry, $Id$ and consequently  $|\text{Stab}(( 1 \ 2 \ 3))|=1$. This is because the non-identity symmetries of a square are reflections (these leave two corners fixed) and rotations (the centre is fixed, but none of the corners), neither of these have three fixed non-collinear points, the only symmetry that does this is the identity, therefore it lets the cycle $( 1 \ 2 \ 3)$ do its job, and cycle around three elements, without changing the order. Therefore we have:
$$ |S|=8$$
How do I now determine which $8-1=7$ other elements we are dealing with?

A: We know that $D_8$ acts transitively on $S$, which means that the action possesses only a single group orbit, which is just the set $S$ itself, i.e., for every $s \in S$, it holds that $D_8 \circ s = S$. We know that $(1 \ 2 \ 3)\in S$, we can use this element to construct the entire orbit, which is simply the set $S$ itself. $S$. We have $D_8=(\langle
(1 \ 3), (1 \ 2 \ 3 \ 4)\rangle)$ which consists of all symmetries of the square, a regular 4-gon. It contains 4 reflections and 4 rotations (amongst which the identity rotation). We will list the composition of $(1 \  2 \ 3 )$ with all these elements:
$(1 \ 3) \circ (1 \ 2 \ 3)= (1 \ 2 )$
$(2 \ 4) \circ (1 \ 2 \ 3)= (1 \ 4 \ 2 \ 3 )$
$(1 \ 2) (3 \ 4) \circ (1 \ 2 \ 3)=(2 \ 4 \ 3) $
$(1 \ 4) (2 \ 3) \circ (1 \ 2 \ 3)=(1 \ 3 \ 4) $
$(1 \ 2\ 3 \ 4) \circ (1 \ 2 \ 3)= (1 \ 3 \ 2 \ 4 ) $
$(1 \ 3) (2 \ 4) \circ (1 \ 2 \ 3)=(1 \ 4 \ 2 ) $
$(1 \ 4 \ 3 \ 2 )\circ (1 \ 2 \ 3)= (3 \ 4 ) $
$ Id \circ (1 \ 2 \ 3)= (1 \ 2 \ 3 )$
Consequently  $$ S= \{
   (1 \ 2 )
,(1 \ 4 \ 2 \ 3 )
,(2 \ 4 \ 3)
,(1 \ 3 \ 4)
   , (1 \ 3 \ 2 \ 4 )
 ,(1 \ 4 \ 2 )
  , (3 \ 4 )
   , (1 \ 2 \ 3 )
   \}$$


text:
Q: Migration of Angular 4 project to Angular 5
*

*What are the major differences in Angular 4 and Angular 5?

*How much effort will be required for migrating Angular 4 project to Angular 5

*Is there any  official documentation available for migration from Angular 4 to Angular 5

A: You can use this migration guide to get a "checklist". It tells you what to do before and after the upgrade.
To summarize it,

*

*template was deprecated and it is removed. Change them to
ng-template

*Date, Currency, decimal, percent pipes are deprecated and renamed. If you want to use old versions of them, you have to edit your code.

*HttpModule is deprecated and will be removed later (still exists in v5). You should change it to HttpClientModule

A: a)   Build Optimizer: This is a tool which was included in the CLI to help the developers in creating a smaller bundle for the application.  Apart from decreasing the users' bundle size, the feature also helps in increasing the boot speed of the application for the users.
b)   Compiler Improvements: To enhance faster rebuilds for production and AOT (Ahead of Time) builds, Angular 5 supports incremental compilation.
c) New Router Lifecycle Events:This new feature was added to enable the developers in tracking the cycle of the router, starting from running guards to the completion of activation.
d)   HttpClient: This feature has been recommended for all the application as HTTPClient was highly appreciated. The framework developer are not suggesting anymore, to use the previous @angular/http library. Developers can update the HTTPClient in 3 easy steps:
1.In each module, replace HttpModule with Http Client Module from
   @angular/common/http.

Inject the HttpClient service
remove any
   map(res =>res.json())

calls, which are no longer needed.


text:
Q: Get position of key on keyboard I hope that this question hasn't been asked already, but I was looking for a solution of my problem and I didn't found anything helpful for me.
I'm writing a Java Application, where the user can control the App via his keyboard. The problem is, that I need many different input keys. So I also have to use the special char keys. But my problem is, that I can't code the whole thing for every keyboard again.
So my question is, is there a way to determine the place of a given key on the keyboard. It would be very good if someone would know how to do this.
Thanks in advance,
Leo

A: A keyboard only sends key codes to the underlying stack. It's up to the OS and software to figure out how to use this. Now perhaps the hardware does have a simple code that relies on location and there's some translation going on to turn this into a usable key code for applications. I reckon this must be the case since the layout can be chosen from OS. But that doesn't seem like the kind of low-level stuff you'd have access to in Java, short of using JNI.
Originating from a KeyListener, you can capture KeyEvents. I'd suggest you look into the doc, fields and methods of that class and maybe make a small test app that captures such events and prints the results of various methods out. Maybe you can find some common ground.
If there's no straightforward way of doing this, perhaps it's best to have some sort of translation table scheme that standardizes the input for the most common layouts, like Qwerty and Azerty. That should do it for most users and since you wish to rely on absolute positioning, requiring one of a small set of layouts doesn't seem unacceptable. Users can change the layout in the OS.
If you happen to be making a game, maybe create some huge control deck that people will be forced to buy to get the best experience. Extra money! :D

A: you can make the settings fully user defined
you can make some settings that the user can modify that maps keys to actions, have a standard set for azerty and qwerty as defaults


text:
Q: A new language with the new stuff in modern C++, but without the issues of backward compatibility? I was seeing this Herb Sutter talk. C++ is changing so much, and backward compatibility is becoming such a pain. Wouldn't it be better to just create a NEW language with just the good new stuff of C++, which doesn't have to maintain backward compatibility?
I do not intend to start a flame war here. This is an objective question: Are there any initiatives out there that are trying to create a new language based on the good new features of C++, but forgetting about the backward compatibility?
On Quora: http://qr.ae/RS2k2L


text:
Q: take list from checkboxes and insert into css I want users to be able to select from a row of check-boxes of additions to make to CSS.
I'm using JS to search for checked boxes, take the names, put into a list, then take the list and put it into CSS as a value for a property.
I can't tell if it's going into the CSS just incorrectly, or not going in at all.

$(document).ready(function () {

  var checkbox = document.querySelector('[type="checkbox"]');

  checkbox.addEventListener('change', function() {
      getOTFeaturesTextA();
  });
});

function getOTFeaturesTextA(){

  var textA = document.getElementById("textA"),
    chkArray = [];

  $(".ot-textA:checked").each(function() {
    chkArray.push($(this).val());
  });

  var selected;
  selected = chkArray.join(',') ;

  if(selected.length > 0){
    textA.css("font-feature-settings", selected + ", liga");
  }else{
    textA.css("font-feature-settings", "liga");
  }
}

      <input type="checkbox" name="frac" value="'frac'" class="ot-textA" id="frac">
      Fraction

      <input type="checkbox" name="aalt" value="'aalt'" class="ot-textA" id="aalt">
      Alternatives

      <input type="checkbox" name="onum" value="'onum'" class="ot-textA" id="onum">
      Oldstyle Numbers

Trying out checkboxes 3/4

A: Use style instead of css in this use case
textA.style['font-feature-settings'] = selected + ", liga";

A: For starters there is no such thing has .css() on vanilla js. You might want to use .style or get the element using jquery instead.
function getOTFeaturesTextA(){
    const textA = $("#textA");
    const chkArray = [];

    $(".ot-textA:checked").each(function() {
        chkArray.push($(this).val());
    });

    const selected = chkArray.join(',');

    if(selected.length > 0){
        textA.css("font-feature-settings", selected + ", liga");
    }else{
        textA.css("font-feature-settings", "liga");
    }
}

Notes: Avoid var and as much as possible do not declare variables in one line. No need to declare an empty variable if you're going to use it immediately after the next line anyway.

A: I've made some changes to your example code.

*

*Removed the quotes from the checkbox values

*Added a single change listener to the container element for the checkboxes instead of a listener per checkbox.

*Since "liga" should alway be present I've used this as the initial item in the array you were constructing with selected features. This removes the need to check if there are features selected and just assign the liga feature.

I wasn't sure how comfortable you are with using the ES6 features so I coded the example to somewhat match your style. There are certainly some things which could be further optimised or done in a different way.

$(document).ready(function () {
  var checkboxContainer = document.getElementById('ot-checkboxes');

  if (checkboxContainer !== null) {
    // There is no need to wrap the event listener in another method first.
    checkboxContainer.addEventListener('change', getOTFeaturesTextA);
  }
});

function getOTFeaturesTextA(){
  var
    textA = document.getElementById("textA"),
    selectedFeatures = document.querySelectorAll('.ot-textA:checked');
    // The liga feature should always be present. All feature names should be
    // wrapped in quotes.
    features = ['"liga"'];

  selectedFeatures.forEach(function(selectedFeature) {
    features.push('"' + selectedFeature.value + '"');
  });

  // Set the style by joining all the items in the array with a
  // comma as separator.
  textA.style.fontFeatureSettings = features.join(',');
}

      <input type="checkbox" name="frac" value="frac" class="ot-textA" id="frac">
      Fraction

      <input type="checkbox" name="aalt" value="aalt" class="ot-textA" id="aalt">
      Alternatives

      <input type="checkbox" name="onum" value="onum" class="ot-textA" id="onum">
      Oldstyle Numbers

Trying out checkboxes 3/4


text:
Q: How do I refresh a Smartcar access token? I use the Smartcar API on my Tesla (https://teslaapi.dev/) and successfully made a request before but I think the access token expired and I don't know how to refresh it.
I followed this guide: https://smartcar.com/docs/integration-guides/express/request/
It talks about the access token but it doesn't tell me how to get the refresh token.
// ./index.js

app.get('/vehicle', function(req, res) {
    // TODO: Request Step 2: Get vehicle information
    return smartcar.getVehicleIds(access.accessToken)
      .then(function(data) {
        // the list of vehicle ids
        return data.vehicles;
      })
      .then(function(vehicleIds) {
        // instantiate the first vehicle in the vehicle id list
        const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken);

        return vehicle.info();
      })
    .then(function(info) {
      res.render('vehicle', {
        info: info,
      });
    });
});

This doesn't work anymore:
    {
      "error": "authentication_error",
      "message": "Invalid or expired token provided."
    }
I think it's because I need to replace the accessToken with a refresh token. How can I do this?

A: So your hunch about needing to use the refresh token is correct.
If you look at the "Request access token" section of API Reference, it notes that the access tokens are only valid for 2 hours, after that point you'll need to use the refresh token to get a new access token to use.
If you're using the Node SDK, you can use the exchangeRefreshToken method to exchange your refresh token for a new set of tokens.
Here's an example with all of that integrated:
// ./index.js

app.get('/vehicle', function(req, res) {
    if (smartcar.isExpired(acccess.expiration)) {
      const
   }

    // TODO: Request Step 2: Get vehicle information
    return smartcar.getVehicleIds(access.accessToken)
      .then(function(data) {
        // the list of vehicle ids
        return data.vehicles;
      })
      .then(function(vehicleIds) {
        // instantiate the first vehicle in the vehicle id list
        const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken);

        return vehicle.info();
      })
    .then(function(info) {
      res.render('vehicle', {
        info: info,
      });
    });
});

For a proper long term implementation of this you'll need to involve some sort of database that stores the access object based on vehicle id.


text:
Q: Selecting from different csv in SPARQL Hi I have two csv data sources.
The csv contains name of employees.
csv1 with heading: Name
Contents: Jack, Tom, Andy, Jim, Stella.
csv2 with heading: EmployeeName
Contents: Bella, Stefan, Jim, Cathy, Jack
Now I need a SPARQL query, where I can search the two csv, and have a variable where both the data can be combined avoiding duplicates(for ex: avoiding Jim and Jack in this instance, but getting data of these names only once)


text:
Q: Determine if Tomcat is running in Windows using the command prompt Quite simply, how does one determine whether or not Tomcat is running in Windows, using the command prompt?
I am writing a batch script that must do this. This is the Bash version:
RESULT=`netstat -na | grep $2 | awk '{print $7}' | wc -l`

Where $2 is the port.
I am looking for something similar to that. Using Cygwin is out of the question, of necessity this script must be able to run on machines that only have Tomcat.

A: Test the status of the Tomcat Service with the SC command. MJB already suggested to test the service status with SC, yet another batch script (without FOR loop) for testing the status:
@ECHO OFF
SC query tomcat5 | FIND "STATE" | FIND "RUNNING" > NUL
IF ERRORLEVEL 1 (
    ECHO Stopped
) ELSE (
    ECHO Running
)

If you are not sure if the service name is tomcat5 you can list all service names with
SC query state= all | FIND "SERVICE_NAME"

A: You could use tasklist to check if the tomcat executable is running. For example:
@echo off
tasklist /FI "IMAGENAME eq tomcat.exe" | find /C /I ".exe" > NUL
if %errorlevel%==0 goto :running

echo tomcat is not running
goto :eof

:running
echo tomcat is running

:eof

It is also possible to check a remove server using the options /S, /U and /P. See tasklist /? for details.

A: Using WMIC
@echo off
wmic process list brief | find /i "tomcat.exe"
set result=%ERRORLEVEL%
if "%result%"=="1" echo "not running"
if "%result%"=="0" echo "running"

note : /i is to make the find operation case-insensitive.

A: This is the Windows version of the netstat based UNIX/LINUX solution asked in the question:
@echo off

netstat -na | find "LISTENING" | find /C /I ":8080" > NUL
if %errorlevel%==0 goto :running

echo tomcat is not running
goto :eof

:running
echo tomcat is running

:eof

A: Well, I am not very good with scripts but perhaps you could use this as a starting point:

netstat -a -n | findstr :8005

To get if someone is listening in port 8005. That is Tomcat's default port for remote administration, i.e. startup or shutdown.
Alternatively you could use the port that the http server listens to.
Hope this helps

A: use netstat -a in command prompt.
You'll find 8080 port listed there.

A: If you run Tomcat for Windows not like a service and don't want to exploit JMX the best way is
for /F %%I in ('tasklist /FI "WINDOWTITLE eq Tomcat" /NH') do if %%I==java.exe goto alreadyRun

where:

*

*Tomcat - the window title of the Tomcat's terminal window by default

*java.exe - the name of the Tomcat's processe. NOT tomcat.exe.

A: Yet another option, since this is probably running as a service
FOR /F "tokens=4 delims= " %%A IN ('SC QUERY tomcat5 ^| FIND "STATE"') DO SET status=%%A
echo "%status%"

status can be things like STOPPED, RUNNING ...

A: I check it by calling a vb script from command line
cscript //nologo checkurl.vbs | findstr "200"
IF errorlevel 1 GOTO :not_running

Save the below script as checkurl.vbs and replace the ip with machines ip
' Create an HTTP object
myURL = "http://10.1.1.1:8080/"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )

' Download the specified URL
objHTTP.Open "GET", myURL, False
On Error Resume Next
objHTTP.Send
intStatus = objHTTP.Status

If intStatus = 200 Then
    WScript.Echo intStatus
Else
  WScript.Echo "Error Connecting"
End If

I had problems with using sc query command, because even if tomcat crashed, the service would still be shown as running where in actual the port was not accessible

A: You can try searching for the process and extracting the line
For example:
ps|grep tomcat


text:
Q: Mat Slider value not getting updated while sliding Mat slider value is not sync updated while sliding.
<mat-slider [(ngModel)]="myValue" step="1" min="0" max="100" ></mat-slider>
{{myValue}}

It just got updated only after release slider thumb.

A: You need to bind the input output (weird name selection) to a handler, see the docs. If you want to keep track of the slider value you could to the following:
<mat-slider (change)="updateSliderValue($event)" (input)="updateSliderValue($event)
 [(ngModel)]="myValue"
 step="1" min="0" max="100" ></mat-slider>
{{ slideValue$ | async }}

import {MatSliderChange} from '@angular/material';
// Using rxjs@6.x
import {BehaviorSubject} from 'rxjs'
private slideSubject = new BehaviorSubject<int>(0);
readonly slideValue$ = this.slideSubject.asObservable();

updateSliderValue(event: MatSliderChange){
    slideSubject.next(event.value);
}

A: Using the javascript input event:
<mat-slider [(ngModel)]="myValue" (input)="myValue = $event.value"></mat-slider>

A: If you're using reactive forms with FormControl you can directly call setValue on the form control like this:
(input)="form.controls['direction'].setValue($event.value)"


text:
Q: jQuery color style alternating I'm trying to achieve a jQuery effect like: http://jsfiddle.net/Qcghe/1/
$(document).ready(function() {
    setInterval(function() {
        $('small:nth-of-type(1)')
            .animate( { color: '#F7B903' }, 750)
            .animate( { color: '#FFF' }, 1000);
    }, 1000);

    setInterval(function() {
        $('small:nth-of-type(2)')
            .animate( { color: '#5BB6FD' }, 750)
            .animate( { color: '#FFF' }, 1000);
    }, 2000);

    setInterval(function() {
        $('small:nth-of-type(3)')
            .animate( { color: '#D13360' }, 750)
            .animate( { color: '#FFF' }, 1000);
    }, 3000);

});

I want to animate the colour of the dots in the following order:

*

*white, white, white (initial state)

*blue,  white, white

*blue,  red,   white

*blue,  red,   green

*white, red,   green

*blue,  white, green

*blue,  red,   white

*…and back to the initial state.

I made an animated GIF in Photoshop to help illustrate (black and white are inverted):
gif animation http://cdn.vpsunder10.com/1.gif

A: check the code
$(document).ready(function() {
  setInterval(function() {
    $('small:nth-of-type(1)')
    .animate( { color: '#F7B903' }, 1000)
    .delay(4000)
    .animate( { color: '#FFF' }, 1000);

     $('small:nth-of-type(2)')
    .delay(1000)
    .animate( { color: '#5BB6FD' }, 1000)
    .delay(5000)
    .animate( { color: '#FFF' }, 1000);

      $('small:nth-of-type(3)')
    .delay(2000)
    .animate( { color: '#D13360' }, 1000)
    .delay(6000)
    .animate( { color: '#FFF' }, 1000);

    }, 10000);
 });

http://jsfiddle.net/Qcghe/3/

A: Because each of them follows a similar but related cycle of animations, I'd try expressing this as one sequence of steps rather than three separate ones.
var $dots = $('#dots span'),
    colors = ['blue', 'red', 'green'], // Colour assigned to each dot, in order.
    step = 1000;                       // Duration of each animation step in ms.

function cycle() {
    $dots
        .finish() // Ensure no animations still running from last cycle.
        .each(function(index, dot) {
            var $dot = $(dot),
                color = colors[index];

            $dot
                .delay(index * step)
                .animate({ color: color }, step)
                .delay(step * 2)
                .animate({ color: 'white' }, step)
                .promise()
                .done(function() {
                    // All but last should be restored to dot colour.
                    if (index != 2) $dot.animate({ color: color }, step);
                })
            ;
        });

    // Set all the dots to white once animations have finished.
    $dots.promise().done(function() { $dots.animate({ color: 'white' }, step) });
}

// Start immediately, and thereafter every seven steps.
cycle();
setInterval(cycle, step * 7);

jsFiddle demo
You can make it faster or slower by playing with the step variable.
(If you were interested and don't have to support older browsers, I could also show you how to do this in pure CSS with keyframe animations.)


text:
Q: Why is everyone inside one room - Terraria iPad I started up Terraria on my iPad and I saw all my NPCs were in my friend's room.
Help Me What is going on?

A: They probably just walked around. At night they will go back into their rooms.


text:
Q: How to convert array data format I have the following array in number format. Arr[12,713,6…], I am trying to convert them to [0012,0713,0006…]. I tried padstart(4,"0") but not working, anybody can help?

A:

var array = [12,713,6];
var newArray = [];

array.forEach(function(element) {
  newArray.push(element.toString().padStart(4,0));
});

console.log(newArray);

//Or with array.map (requires ECMAScript 5)
console.log(array.map(number => number.toString().padStart(4, "0")))

A: You can map your array with numbers, before you use padStart just make sure that the element is a string.

const arr = [1, 2, 323, 32].map((el) => el.toString().padStart(4, '0'));
console.log(arr);

A: You can pad a number by adding n-number of zeroes before the value and then clipping the string n-places from the beginning.

const padLeft = (v, ch, n) => (ch.repeat(n) + v).substr(-n);

let input = [ 12, 713, 6 ];
let output = input.map(x => padLeft(x, '0', 4));

console.log(output);


text:
Q: Angular material mdTab and abstract route issue I try to create separate state per md-tab and following example works fine:

    <md-tabs>
    <md-tab md-on-select="transitionTo('tab1',{})">
      <md-tab-label>Tab1</md-tab-label>
    </md-tab>
    <md-tab md-on-select="transitionTo('tab2',{})">
      <md-tab-label>Tab2</md-tab-label>
    </md-tab>
  </md-tabs>

JS
var app = angular.module('app',['ui.router','ngMaterial']);
app.run(function($rootScope, $state) {
  $rootScope.transitionTo = function(state, params) {
    $state.transitionTo(state, params, { location: true, inherit: true, relative: $state.$current, notify: true });
  }
  $rootScope.checkState = function (state) {
    return $state.current.name == state ? true : false;
  }

  $rootScope.$on('$stateChangeSuccess',
  function(event, toState, toParams, fromState, fromParams){
    if($state.current.name == 'tab2') {
      $rootScope.tab = { selected : 1 }
    } else {
      $rootScope.tab = { selected : 0 }
    }
  })
});
app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('tab1', {
        url : '/tab1',
        templateUrl : 'one.html',
      controller: 'AppCtrl'
    })
    .state('tab2', {
        url : '/tab2',
        templateUrl : 'two.html',
    controller: 'AppCtrl'
    })
  $urlRouterProvider.otherwise('/tab1');
});

app.controller('AppCtrl', function($scope, $mdDialog, $mdMedia) {
  console.log('AppCtrl');
  });

See DEMO in Codepen

The disadvantage of this example, on tab change i load again and again AppCtrl controller.
So my goal is to load controller once.
One of approaches I know is to use parent abstract state. Here we go:
First off, I create new file root.html with tabs:

And my state provider should look like:
$stateProvider
  .state('root', {
        url : '/root',
        templateUrl : 'root.html',
    controller: 'AppCtrl'
    })
    .state('root.tab1', {
        url : '/tab1',
        templateUrl : 'one.html'
    })
    .state('root.tab2', {
        url : '/tab2',
        templateUrl : 'two.html'
    })
  $urlRouterProvider.otherwise('/root/tab1');

Here is a DEMO with this change
However it doesn't work. I load AppCtrl once only but I don't see tab contents, in other words I never call 'root.tab1' and 'root.tab2'
What I'm doing wrong here?
Any ideas?

A: I think your second approach is fine.
You don't see tab contents because you need to put a <md-tab-body> with the ui-view inside each <md-tab>. Example:
<md-tab md-on-select="transitionTo('root.tab1',{})">
   <md-tab-label>Tab1</md-tab-label>
   <md-tab-body>

   </md-tab-body>
</md-tab>

I've forked your plunker and here you have a working example: Controller is loaded only once and tab contents are seen.
Hope it helps.


text:
Q: SQL: Dúvida no Relacionamento entre Tabelas Estou criando um sistema académico que consiste em um tipo de cardápio de restaurante virtual, para isso, criei três tabelas no banco:
Tabela de Itens do Cardápio:
CREATE TABLE ITEMS(
    ID INT PRIMARY KEY NOT NULL,
    NOME VARCHAR(20) NOT NULL,
    DESCRICAO VARCHAR(20),
    PRECO FLOAT NOT NULL
)

Tabela de Pedidos:
CREATE TABLE PEDIDO(
    NUMERO INT PRIMARY KEY NOT NULL,
    MESA INT NOT NU NULL,
    VALORTOTAL FLOAT
)

Tabela onde registro os Itens do Pedido, no qual:

ID_PEDIDO = FK de Pedido,
ID_ITEM = FK de Item

CREATE TABLE ITEM_PEDIDO(
    ID INT PRIMARY KEY NOT NULL,
    ID_PEDIDO INT NOT NULL,
    ID_ITEM INT NOT NULL,
    QTD_ITEM INT
 )

Minha dúvida é a seguinte:
No sistema, o usuário poderá escolher um item ou mais para seu pedido, assim como a quantidade deste item. Ao final do pedido, deverá retornar o preço total do mesmo.

Sendo assim, devo deixar a QTD_ITEM na tabela ITEM_PEDIDO?
  Quanto ao PREÇO, devo deixar na tabela ITEM ou incluo também na tabela  ITEM_PEDIDO?

A: Tudo que é relacionado ao que foi/será comprado deve ficar dentro da tabela ITEM_PEDIDO se for relacionado ao ITEM. Sendo assim o PRECO, como é do ITEM e não tem relação com o pedido, deve ser colocado na tabela ITEM e a QTD_ITEM que tem relação com o que foi consumido deverá estar na tabela ITEM. O cálculo do valor total será o seguinte:
SELECT P.NUMERO,
       SUM(IP.QTD_ITEM * I.PRECO) AS VALOR_TOTAL
  FROM PEDIDO P
       INNER JOIN ITEM_PEDIDO IP ON IP.ID_PEDIDO ON P.NUMERO
       INNER JOIN ITEMS I ON I.ID = IP.ID_ITEM
 WHERE P.NUMERO = 'X'
 GROUP BY P.NUMERO

Caso queira manter um preço histórico de ITEM, sugiro a criação de uma tabela com os preços com a data vigente da seguinte forma:
╔════════════════════════════╗
║         ITEM_PRECO         ║
╠═════════════════╦══════════╣
║ ID_ITEM         ║ INTEIRO  ║
║ INICIO_VIGENCIA ║ DATA     ║
║ FINAL_VIGENCIA  ║ DATA     ║
║ PRECO           ║ NUMÉRICO ║
╚═════════════════╩══════════╝

E a adição da coluna DATA_PEDIDO na tabela PEDIDO. Sendo assim o cálculo ficaria da seguinte forma:
SELECT P.NUMERO,
       SUM(IP.QTD_ITEM * IP.PRECO) AS VALOR_TOTAL
  FROM PEDIDO P
       INNER JOIN ITEM_PEDIDO IP ON IP.ID_PEDIDO ON P.NUMERO
       INNER JOIN ITEMS I ON I.ID = IP.ID_ITEM
       INNER JOIN ITEM_PRECO IP ON IP.ID_ITEM = I.ID
                               AND P.DATA_PEDIDO BETWEEN IP.INICIO_VIGENCIA AND IP.FINAL_VIGENCIA
 WHERE P.NUMERO = 'X'
 GROUP BY P.NUMERO;

Assim você poderá fazer alterações de preço sem maiores problemas e sem precisar replicar dados.

A:
Quanto ao PREÇO, devo deixar na tabela ITEM ou incluo também na tabela ITEM_PEDIDO?

Inclua também na tabela ITEM_PEDIDO.
A tabela ITEMS contém qual é o preço vigente para cada item. Já para cada item de pedido deve-se manter tanto a quantidade de unidades pedidas como também qual era o preço vigente no momento do pedido. E o motivo é bem simples: os preços variam ao longo do tempo.
Suponha que o item A tenha preço $10 no dia D1 e que no dia D2 tenha o preço $20. Se um pedido P1 de 3 unidades para o item A foi realizado no dia D1, então o valor do pedido, para esse item, foi de $30. Se o valor do preço do item ficar armazenado somente na tabela ITEMS e se no dia D2 for consultar quanto foi o valor do pedido P1, a consulta retornará $60 para o item A, o que está errado! Por isso que nos sistemas comerciais de pedidos para cada item sempre é armazenado o valor unitário do item no momento do pedido.
Observação adicionais:

*

*não utilize tipo de dados float para armazenar valores monetários;

*na tabela ITEM_PEDIDO não é necessário criar uma coluna específica
para ser a chave primária. A chave usual é {ID_PEDIDO, SEQ_ITEM}, onde SEQ_ITEM é um número sequencial, para cada pedido.


text:
Q: Prove that $A-I_n$ is idempotent
Let $A ∈ R^{n×n}$ be a nonzero singular matrix with the property that $A^2 = A$.
Show that $A − I_n$ is also idempotent.

I tried the following:
$(A - I_n)^2 = (A-I_n)(A-I_n) = A(A-I_n)-I_n(A-I_n) = A^2 - A - A + I_n = A^2 - 2A +I_n = A - 2A + I_n = I_n - A$
Unfortunately, to the best of my knowledge, that doesn't qualify as an answer, as the identity I must get is the following: $A − I_n$.
Since that does not equal to the final form that I got upon simplifying the square, I am sort of lost. Is there something that I did wrong in my steps?

A: Your computations are O.K. The statement above is wrong. If $A$ is idempotent, then $I_n-A$ is idempotent !

A: The correct statement is $I-A$ is idempotent.
If $$0 = A^2 - A = A(A - I)$$
then the minimal polynomial $\mu_A(x)$ divides $x(x-1)$.
If $\mu_A(x) = x$ then $A = 0$ and if $\mu_A(x) = x-1$ then $A = I$, both cases being trivial. Thus assume $\mu_A(x) = x(x-1)$.
Recall that for any matrix $B$ and scalar $\lambda$ we have $\mu_{B - \lambda I}(x) = \mu_B(x + \lambda)$. Also $\mu_{-B}(x) = (-1)^n\mu_{B}(-x)$.
Therefore $$\mu_{A - I}(x) = \mu_A(x+1) = (x+1)x \implies \mu_{I - A}(x) = x(x-1) = x^2 - x$$
We conclude $(I-A)^2 = I-A$.


text:
Q: Datatable takes more time to load after first time loaded in client side i am using datatables js for my application, when i load 100000 records at first time it takes 30 sec average time but after first time it takes twice the time as first, searched internet for this but i could not find proper solution.
Any idea?


text:
Q: allow direct url access to image only if requested by bot otherwise pass url to index.php file using .htaccess .htaccess
#Disallowed
#RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
#RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
#RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]

#Allowed
RewriteCond %{REQUEST_URI}  !=/index.php
RewriteCond %{REQUEST_URI}  !.*\.php$ [NC]
RewriteCond %{REQUEST_URI}  !.*\.css$ [NC]
RewriteCond %{REQUEST_URI}  !.*\.js$ [NC]
RewriteRule . /index.php [L]

index.php
What I'm doing is handling all image url's with index.php and run the condition below. If bot is detected (googlebot,bingbot etc..) then display image otherwise run some stuff. Now I want to detect bot using .htaccess and allow image to open directly bypassing php part.
if(_bot_detected()){
  //echo image
}else{
  //redirect user to some page
}

I'm very new to web programming. After a lot of search i couldn't find any information that works for me. This is my first question to stackoverflow. Thanks for any help

A: I refer my answer based on the following _bot_detected() function:
https://gist.github.com/holgerhubbs/983a53ee21a9f6bff08d
If your function works different the matching would not be 100% equal.
The only thing that we have to check is if the request is for an image and not coming from a bot, because than we have to rewrite:
# Check if the URI is a physical file
RewriteCond %{REQUEST_URI} -f
# Check if the file has any kind off Image extension like:
# .gif .jpg .jpeg .tif .tiff .png .svg .bmp (case insensitive => [NC])
RewriteCond %{REQUEST_URI} \.(gif|jpe?g|tiff?|png|svg|bmp)$ [NC]
# check if the request in NOT coming from a bot
RewriteCond %{HTTP_USER_AGENT} !(bot|crawl|slurp|spider) [NC]
# If all Condition are satisfied than we rewrite to /index.php
RewriteRule ^.*$ /index.php [L]

Even my answer should match with your original php behavior, there is a height change that this matching criteria do not find all find  bots.


text:
Q: New to running loops in Command Prompt edit:
I'm new to running code, I'm trying to run a loop on the command prompt I don't know how to properly execute the loop.  Am I required to make a bash/batch file to get a loop to execute in the command prompt? Any guidance will be appreciated.
I'm trying to take a folder that contains mp3 files and trim the silence at the beginning and the end in all the individual files.
for f in *.mp3; do ffmpeg -i "$f" -af "silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse" "outputs/${f%.*}.mp3"; done

I keep receiving an error that f was unexpected. Can someone tell me what I'm doing wrong?

A: This is how i do it on powershell. Created a script which removes silence, normalize and inset ID3 Tags
https://github.com/djansen1987/MP3Analyze-Powershell-/blob/93607ed4f9349755df87244675fdfb7adcc019f3/Get-Mp3Details.ps1#L415
In CMD the one liner would look like this:
FOR /R  %F IN (*.mp3) DO (ffmpeg -i "%~nF" -af "silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse" "outputs/%~nF.mp3")


text:
Q: GAN нейросеть - меняется шум, но показания прежние. Как это возможно? Играюсь с нейросетью из туториала гугла
https://www.tensorflow.org/tutorials/generative/dcgan
Этапы построения
1)Подготавливаем выборку изображений
2)Делаем генератор (вход - много нейронов(7x7x256), выход - 1 изображения размером 28 на 28 в оттенках серого от -1 до 1)
3)Делаем дискриминатор - на вход - изображение размером 28 на 28 в оттенках серого, выход - цифра-вердикт,
если 1, то изображение 100% истинно и, если 0, то изображение точно фейк.
4)Запускаем тренировку:
Скармливаем случайный шум генератору
Генератор выдает картинку
Дискриминатор смотрит что это за картинка и выносит свой вердикт(допустим 0.1)
Дискриминатор смотрит на идеальные картинки и выносит свой вердикт
Высчитываем ошибку генератора (она равна кросс-энтропии между правильным ответом дискриминатора на идеальную картинку( т.е. единице) и тем, как оценил дискриминатор нашу картинку(0.1)
Высчитываем ошибку дискриминатора(она равна кросс энтропии между единицей и тем, как дискриминатор оценил идеальные картинки плюс кросс энтропия между нулем и тем как дискриминатор оценил неправильные картинки)
Применяем этим ошибки для обучения наших моделей
    gradients_of_generator = gen_tape.gradient(gen_loss, createGenerator.trainable_variables)
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)

    generator_optimizer.apply_gradients(zip(gradients_of_generator, createGenerator.trainable_variables))
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
    `

Повторяем раз за разом.
Вопросы
1)Правильно ли я понял алгоритм работы генеративно-состязательной сети?
2)Почему первых нейронов у генератора на входе так много? Почему 7х7х256? 256 - это BATCH_SIZE, использовалось при подготовке образцов. Но зачем умножать еще на 7х7?
 model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100, )))

3)Каждый раз в итерации обучения входной шум меняется! Причем случайно! При обучении модели мы добавляем в неё градиенты, основанные на ошибках, но если входные данные все время случайны - разве может мы получать правильные ответы? Сеть работает, и после 50 итераций цифры похожи на цифры, но почему не мешает случайный шум?
noise = random.normal([256, 100])

    with GradientTape() as gen_tape, GradientTape() as disc_tape:
      # получаем изображения от генератора изображений, передавая туда шум.
      generated_images = createGenerator(noise, training=True)
    ```

A: Попробую ответить на некоторые из ваших вопросов.

*

*Вы правильно описали этапы построения модели, но описали ее для случая когда BATCH_SIZE = 1. За один шаг генератор создаёт BATCH_SIZE картинок из белого шума, а дискриминатор высчитывает ошибку для BATCH_SIZE фейковых картинок созданных генератором и для BATCH_SIZE реальных картинок и суммирует ошибку.

*"Почему 7х7х256?" 256 - в данном случае это глубина первого слоя. Даже если бы изменили BATCH_SIZE - мы не должны были бы менять глубину входного тензора. Размерность первого слоя подбирается таким образом, чтобы получить на выходе правильныё размер тензора с созданными картинками после всех слоев развёртки (deconvolution / transpose convolution) . Т.е. размерность первого слоя зависит от размерности генерируемой картинки и от количества слоёв развёртки - чем больше слоёв тем глубже должна быть размерность вначале.

*Если на вход генератору подавать одни и те же данные, то он и научится создавать одинаковые картинки и только для данных входных данных. Случайный шум помогает обучать и генератор и дискриминатор. Генератор учится создавать картинки более похожие на исходные реальные картинки, а дискриминатор обучается отличать все более качественные фейки от реальных картинок.

Другой пример DCGAN архитектуры:

Для простоты описываем этапы для одной картинки. В реальном случае это будут тензоры с дополнительной размерностью - batch_size, т.е. число картинок обрабатывающихся за один шаг работы сети / модели.
Генератор

*

*На вход полносвязному слою подается вектор из 100 случайных чисел, на выходе тензор размерности 4x4x1024

*На вход развёрточному слою подаётся тензор размерности 4x4x1024. После слоя развёртки получаем тензор размерности 8x8x512, т.е. размерность картики увеличилась вдвое, а глубина уменьшилась вдвое.

*продолжаем развёртку: 8x8x512 --> 16x16x256

*продолжаем развёртку: 16x16x256 --> 32x32x128

*последний развёрточный слой создаёт картинку нужной нам размерности и глубины (в данном случае с одним цветовым каналом - оттенки серого)

Дискриминатор

*

*На вход сверточного слоя получаем картинку размерности 64x64x1, на выходе тензор размерности 32x32x64

*свёрточный слой: 32x32x64 --> 16x16x128

*свёрточный слой: 16x16x128 --> 8x8x256

*свёрточный слой: 8x8x256 --> 4x4x512

*полносвязный слой: 4x4x512 --> 1 (вероятность того, что картинка реальная)

Таким образом размерность тензора для первого разверточного слоя генератора подбирают так, чтобы после всех слоёв развертки получить картинку нужной размерности (в описанном выше случае - 64x64x1).


text:
Q: Which programming language should I use for TCP server for JavaScript clients? I am asking for advise on which programming language is most acceptable for the following situation.
The program will act as the server in a TCP networking application, serving JavaScript clients that output to the browser, using a pre-written framework.
The server program will need to be 'always-on', and be capable of dealing with JSON.
My first instinct is to use PHP, because it can run the same web-server, and has pre-existing JSON and TCP functions. Is there a way to run PHP scripts on the server without needing to have a browser open to 'trigger' the script execution? - the script will have to be running for hours on end without timing out.
Other languages that are considered are C#, C++, Java.
Thanks in advance.

A: node.js
The first example on the homepage shows how easy it is to build servers in it
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

A: Anything can make a request that triggers a PHP script to be executed, it doesn't have to be a browser.  For example, a cron job can simply request a particular page and it will be executed.  Or it can execute it directly.

A: It looks like you are trying to run a php script to push data to the browser in real time. PHP is not ideal for this since it is io-blocking and will become terribly slow/crash when there are not enough available threads. This makes it very bad from a scalability standpoint. Java is ideal for this since it gives you the ability to control how threads are handled. If you are indeed looking to push data to your browser in real-time, xhr long polling is what you want. APE-server is by far the best solution I have found for this:
http://www.ape-project.org/
As a side note, you can run php scripts serverside without a browser. For a linux system, you will need php-cli to do this. To get php-cli, in terminal, type in sudo -s, hit enter, type your password, hit enter, type sudo apt-get install php-cli, hit y, then hit enter again. Then, create a file called yourfilename.run in the same directory as your php file and insert the following into the .run file:
php -f name_of_php_file.php
Allow the file to be executed in terminal (by right clicking it and selecting it), then double click it to open it in terminal. Voila, your script is running without a browser.
But once again, if you are trying to push data to your browser in real-time, php is a bad choice. Take the time to look into ape-server.


text:
Q: Using Reflection to Upsert Derived Entities in Generic Repository A bit new at the Repository Pattern.  Trying to build a generic repository that will also handle state changes to derived entities.  What I've done so far is create a custom attribute to flag the property as one which needs to be upserted.
Attribute:
public class DerivedObjectAttribute : Attribute
{
    public enum EntityType
    {
        REFERENCE,
        OBJECT
    }

    public EntityType DerivedType { get; set; }
}

I define this attribute for any property on which I want to cascade state changes.
Sample Entity:
public class FightingCharacter : BaseEntity
{
    public Costume costume { get; set; }

    [DerivedObject(DerivedType=DerivedObjectAttribute.EntityType.REFERENCE)]
    public SpecialFinish specialFinish { get; set; }

    [DerivedObject(DerivedType = DerivedObjectAttribute.EntityType.REFERENCE)]
    public List<MoveList> moveList { get; set; }
}

So for this class, the costume property would not need to cascade, but the specialFinish and moveList properties should.
Then in my repository:
public class DataRepository<T> : IRepository<T> where T : BaseEntity {
    private void TryDerivedUpsert(T entity)
    {
        Type type = entity.GetType();
        PropertyInfo[] piList = type.GetProperties();
        foreach (PropertyInfo pi in piList)
        {
            foreach (DerivedObjectAttribute attr in pi.GetCustomAttributes(typeof(DerivedObjectAttribute), false))
            {
                // What to do here?
            }
        }
    }
}

In the innermost loop, I'm able to pinpoint DerivedObjectAttributes without any problem.  The question is: how do I obtain the Type and Value of the object, then upsert it?  In other words: if property pi is flagged to cascade changes, create a repo cast to the appropriate Entity, and Upsert it.  E.G.:
DataRepository<EntityType> repo = new DataRepository<EntityType> ();
repo.Upsert(property as EntityType);

Does that make sense?  Or am I going about generic repo entirely the wrong way?  If it does make sense (I'll be surprised), how to do it?  (The examples listed here are just examples, BTW. I'm still architecting and have no EF classes at all yet.)

A: You could get the value with pi.GetValue(entity, null), and create the generic repository (Activate.CreateInstance) for the property type (from pi), but you will have to do a lot of reflection.
In this case you should think about dropping the classic generic repository idea (separate repository per type) and use something like an extended DbContext, that can handle all types.
If you have a disconnected scenario (WCF), the main problem will be EF itself, because you have to replicate all changes to nested lists on the server side and manually change the EntityState.