text:
Q: Convert .caf audio file to .wav audio file swift I have recorded audio and saved in .caf format in document directory. I need to convert the .caf to .wav file to upload the file to server. I researched and didn't get much input in swift. Please help me out to find a solution?

A: Did you try AudioKit?
Maybe you can use AKConverter https://audiokit.io/docs/Classes/AKConverter.html


text:
Q: Thread interruption So i have a question about the interrupt() method for threads in java. Here is a piece of my code:
threads.forEach(Thread::start);
threads.forEach(thread -> {
    try {
        thread.join();
        if (done){
            thread.interrupt();
        }
    } catch (InterruptedException e){
        e.printStackTrace();
    }
});

Now, as you can see, I begin by starting each thread and joining them. What I want to know is if "thread.interrupt()" does what I think it does. I have created a volatile boolean "done" (which is false by default). And I have another piece of code somewhere, where each thread searches for something in a file.  When that something is found, I set the boolean done to true. And I am hoping that that stops all the other threads that arent finished yet from running.
However, something tells me that this isnt as easy as Im making it be. So I would appreciate it if anyone could tell me if what I did is right - and if not - what exactly this does.

A:
What I want to know is if "thread.interrupt()" does what I think it does.

No, it doesn't.
Say you have two threads search for something in a file. When thread2 finds out that thing whatever it is, and sets done to true, the main thread (the code in your question) may be still waiting for thread1 to terminate, since you invoked thread.join(); on thread1, and the fact that threads.forEach doesn't run in parallel.
The main thread will block on thread1.join() until thread1 also finds out the thing, or finishes without anything found, or interrupted by a third thread.
To implement what you intended for, you have to maintain the references of all other threads for every thread you create, and interrupt all other threads when any one thread first finds out the result.
Another way is that do not invoke join for each thread, but busy-checking for the volatile flag done, and interrupt each thread on done == true.
threads.forEach(Thread::start);
while (!done) {
    Thread.sleep(100);
}
threads.forEach(thread -> {
    try {
        thread.interrupt();
    } catch (InterruptedException e){
        e.printStackTrace();
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How PySpark allows columns with special characters? The dataframe df_problematic in PySpark has the following columns:
+------------+-----------+------------+
|sepal@length|sepal.width|petal_length|
+------------+-----------+------------+
|         5.1|        3.5|         1.4|
|         4.9|          3|         1.4|

I'd expect the dataframe would not load or throw some error since the columns have @ and ..
But it looks like it loads just fine.
How can it be loaded?
Operations on the columns with special characters (unless I surround the column with `) throw an error. However, operations on the columns with normal names work just fine, e.g. sampling:
df_problematic_sampled = df_problematic.sample(fraction=0.8)
df_problematic_sampled.head(3)

Output:
[Row(sepal@length='4.7', sepal.width='3.2', petal_length='1.3', petal.width='.2', variety='Setosa'),
 Row(sepal@length='4.6', sepal.width='3.4', petal_length='1.4', petal.width='.3', variety='Setosa'),
 Row(sepal@length='4.4', sepal.width='2.9', petal_length='1.4', petal.width='.2', variety='Setosa')]

Does it mean that as long as I do not use the columns with special characters, and perform operations only on the columns with normal names, the dataframe df_problematic can be e.g. sampled/grouped/saved just fine?


text:
Q: Does Cartesian Product and Collection of all Sets Perform a Semigroup? We know that the Cartesian Product is a binary operation. Also it is an associative operation.
We know that Cartesian Product of two set is again set, there is even closure axiom.
So I need to know does Cartesian Product and Collection of all Sets Perform a Semigroup?

A: Is the operation indeed associative? Do we have $\left(A\times B\right)\times C=A\times\left(B\times C\right)$?
The sets are isomorphic in category $\mathbf{Set}$ wich means that
there is bijection from one to another. But that does not mean that
the sets are the same. This obstacle must somehow be 'modded' out.
If that's done then you can indeed speak of a semigroup. Associativity
is enough.


text:
Q: Can't connect to local area server with asp.net page on Android I'm new here and I wish I won't make any bloomer :)
I'm developing some android app and have stucked in connecting to other computer, where I've installed ASP.net page. I can't emulate it due to problems with connecting to host.
The code that I'm using:
public class SPCChartViewerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String strData = urlData("http://[server]/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS");
    TextView tv = (TextView) findViewById(R.id.textView1);
    tv.setText(strData);
}

private String urlData(String urlString){
    URLConnection urlConnection = null;
    URL url = null;
    String string = null;

    try {
        url = new URL(urlString);
        urlConnection = url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer stringBuffer = new StringBuffer();
        while((string = reader.readLine()) != null){
            stringBuffer.append(string + "\n");
        }
        inputStream.close();
        string = stringBuffer.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return string;
}

}
In tag [server] I've put:

*

*that computer's name: http://miltstx155srv01/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:UnknownHostException

*that computer's IP: http://10.72.152.163/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:FileNotFoundException

*If I ommit the "http://" I receive java.net:Protocol Not Found
Ok, maybe something with my company's DNS. So I've put this page on my computer, which is also running AVD emulator. So the url is now: http://10.0.2.2/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS - but still java.net:UnknownHostException.
Of course clause uses-permission android:name="android.permission.INTERNET" is added to manifest.
Still, every example written upper works fine with webbrowser (of course except 10.0.2.2 - but changing it to localhost makes it work).
No idea, I've spent whole day testing it. Can anyone help?


text:
Q: LINQ Skip(0) vs Skip(n), return inconsistent sort expression When calling the Skip() method with a starting index other than 0, the method automatically appends additional columns 'in addition to' the existing order-by column.  These additional order-by columns consist of the remaining columns that are not in the sort expression.  Great job for LINQ to handle this automatically for us as it provides deterministic sorting on the data returned;however, when 0 is passed to the Skip() method (when querying for the first page for instance), it appears that the method is optimized and the additional order-by columns aforementioned is not rendered.  This is problematic as the sort condition is inconsistent between Skip(0) and Skip(n).
Another developer, Dave, also pointed out the same issue.
Quote: "Skip(0) should generate the same row numbering sql that skip(n) does..."
A link to the thread: http://www.eggheadcafe.com/conversation.aspx?messageid=32045245&threadid=32045239
Does anyone encounter a similar issue?  Fortunately the data we're querying has an identity column, so a work around we came up is to always append the identity column to the existing sort expression.  We would love to hear other creative approaches or solutions.

Example
Both queries below select the same columns from the database and include an descent ordering on the column, RequestReceivedDate.  Notice how the query generated by Skip(10) append additional ordering for the remaining columns which causes a different data ordering when there are records with the same RequestReceivedDate.  The idea of appending these extra sorting is great; however, the library should implement the same logic for Skip(0) so both Skip(0) and Skip(n) would return data in the same order.
[Query generated by Skip(0).Take(10)]
SELECT TOP (10) [t31].[PersonId], [t31].[value] AS [RequestReceivedDate2], ....
FROM (
    SELECT [t0].[PersonId], (
        SELECT MAX([t8].[RequestReceivedDate])
        FROM [dbo].[EnrollRequest] AS [t8]
        WHERE EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [dbo].[DomainAccount] AS [t9]
            WHERE ([t9].[DomainAccountId] = [t8].[DomainAccountId]) AND ([t9].[PersonId] = ([t0].[PersonId]))
            )
        ) AS [value], ...
    ) AS [t31]
ORDER BY [t31].[value] DESC

[Query generated by Skip(10).Take(10)]
SELECT [t32].[PersonId], [t32].[value] AS [RequestReceivedDate2], ...
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [t31].[value] DESC) AS [ROW_NUMBER], [t31].[PersonId], [t31].[value], [t31].[FullAccountName], [t31].[LastName], ...
    FROM (
        SELECT [t0].[PersonId], (
            SELECT MAX([t8].[RequestReceivedDate])
            FROM [dbo].[EnrollRequest] AS [t8]
            WHERE EXISTS(
                SELECT NULL AS [EMPTY]
                FROM [dbo].[DomainAccount] AS [t9]
                WHERE ([t9].[DomainAccountId] = [t8].[DomainAccountId]) AND ([t9].[PersonId] = ([t0].[PersonId]))
                )
            ) AS [value], ...
    ) AS [t32]
WHERE [t32].[ROW_NUMBER] BETWEEN @p21 + 1 AND @p21 + @p22
ORDER BY [t32].[ROW_NUMBER]

A: Apparently, this issue is fixed in LINQ to SQL in .NET 4.0:

Skip(0) no longer prevents eager loading

A: From the link this looks like a LINQ to SQL question. And there an unordered SELECT made where LINQ is returning different results after a skip.
However, you can not depend on the ordering that SQL returns its rows, unless you specify an order by clause.
Can you provide a full sample?


text:
Q: How to set card percentage width? I am trying to have the following "cards" in my row div to take 70% of the space for the left card and 30% of the space for the right card. I tried setting the percentage width for each card but it doesn't seem to be working.

Company Name

Company Overview

Annual Revenue: 2,000,000,000

Employees: 150,000

Industry: Data Processing, Hosting, and Related Services

Inherent Risk Industry: Information Processing

Relative Risk

 Medium

 999

A: The width in bootstrap should only be handled with columns. Don't set a width! If you want to have exact 70% and 30%, customize the grid here: https://getbootstrap.com/docs/3.3/customize/#grid-system (10 columns instead of 12). Set col-?-3 on the left side and col-?-7 on the right side.
If the exact width doesn't matter, you could take the standard-bootstrap-3-css and use 4 columns (33.33%) for the left side and 8 columns (66.66%) for the right side.

Company Name

Company Overview

Annual Revenue: 2,000,000,000

Employees: 150,000

Industry: Data Processing, Hosting, and Related Services

Inherent Risk Industry: Information Processing

Relative Risk

 Medium

 999

A: Both of your divs have the same class name. You could do this in your css style file:
.col1{
    width: 70%;
}

.col2{
    width: 30%;
}

So reassign your first div class (col-lg-3 col-md-6 where you have width="500px") to col1 (or whatever you want) and your second div class (col-lg-3 col-md-6) to col2...
Hope this helps


text:
Q: scrape table using google app scripts I would love to scape data from this website: https://finviz.com/screener.ashx?v=141&f=sh_avgvol_o500,sh_curvol_o2000,sh_price_u50&o=-volume
I want to scrape the whole table. I tried using this :
function myFunction(start) {
    var url = "https://finviz.com/screener.ashx?
v=141&f=sh_avgvol_o500,sh_curvol_o2000,sh_price_u50&o=-volume&r="+
start;
    var fromText = '
';
    var toText = '
';
    var content = UrlFetchApp.fetch(url).getContentText();
    var scraped = Parser
              .data(content)
              .from(fromText)
              .to(toText)
              .iterate();
}

I could scrape every element using xpath, but I think it would be quite slow.
Here is the html and the table:

Can I get the whole table ?
Thanks

A: How about a following modification? The retrieved data is imported to Spreadsheet.

NOTE: Parser is a GAS library. You can see the detail at https://www.kutil.org/2016/01/easy-data-scrapping-with-google-apps.html

Modified script :
function myFunction(start) {
  var url = "https://finviz.com/screener.ashx?v=141&f=sh_avgvol_o500,sh_curvol_o2000,sh_price_u50&o=-volume&r="+ start;
  var content = UrlFetchApp.fetch(url).getContentText();
  var scraped = Parser.data(content).from('class=\"screener-body-table-nw\"').to('	').iterate();
  var res = [];

  // If you don't want column titles, please remove this part.
  var temp = [];
  var titles = Parser.data(content).from("style=\"cursor:pointer;\">").to("	").iterate();
  titles.forEach(function(e){
    if (!~e.indexOf('\">')) {
      temp.push(e);
    } else if (~e.indexOf('img')) {
      temp.push(e.replace(//g, ''));
    }
  });
  res.push(temp);
  // -----

  var temp = [];
  var oticker = "";
  scraped.forEach(function(e){
    var ticker = Parser.data(e).from("").to("").build();
    var data2 = Parser.data(data1).from(">").to("<").build();
    if (oticker == "") oticker = ticker;
    if (ticker != oticker) {
      temp.splice(1, 0, oticker);
      res.push(temp);
      temp = [];
      oticker = ticker;
      temp.push(data1);
    } else {
      if (!~(data2 || data1).indexOf('<')) temp.push(data2 || data1);
    }
  });
  var ss = SpreadsheetApp.getActiveSheet();
  ss.getRange(ss.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
}

Result :


text:
Q: Parsing CSV to 2D Array in ExtendScript (ES3-compliant) I'm having issues parsing a Vimeo review page-formatted CSV in Adobe's ExtendScript. The problem is that ExtendScript is based off of ES3 and most solutions don't seem to work as they're based on modern JS.
Also the CSV has a header row, empty row at the end, double quotes for some but not all fields (which I'd like to remove) and potential line breaks and special characters (inc. commas) in the fields. Is there any way to get a 'clean' 2D array out?
I've tried solutions here: Javascript code to parse CSV data
And here: How can I parse a CSV string with Javascript, which contains comma in data?
But couldn't get them to work, I assume the issues are related to ExtendScript being old.
CSV File
"Test Video-01.mp4",1,00:00:00,AVT,"test comment 1",--,"Tuesday, July 9, 2019 At 8:49 AM",No
"Test Video-01.mp4",2,00:00:00,AVT,"another at same timecode",--,"Tuesday, July 9, 2019 At 8:50 AM",Yes
,3,00:00:00,--,"another at same timecode","reply here from anon","Tuesday, July 9, 2019 At 8:54 AM",Yes
"Test Video-01.mp4",3,00:00:11,AVT,"really long comment Lorem ipsum dolor sit amet, Purus sit amet volutpat consequat mauris nunc congue nisi. Semper viverra nam libero justo laoreet sit amet cursus. Id interdum velit laoreet id. Bibendum est ultricies integer quis auctor elit sed vulputate. And some special chars to boot: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Eros donec ac odio tempor orci dapibus. Nam libero justo laoreet sit amet. Pellentesque pulvinar pellentesque habitant morbi. Pellentesque eu tincidunt tortor aliquam nulla facilisi cras fermentum.",--,"Tuesday, July 9, 2019 At 8:50 AM",No
"Test Video-01.mp4",4,00:00:19,AVT,"another one different timecode",--,"Tuesday, July 9, 2019 At 8:50 AM",Yes
"Test Video-01.mp4",5,00:00:43,AVT,"comment here tooo",--,"Tuesday, July 9, 2019 At 8:51 AM",No
,6,00:00:43,AVT,"comment here tooo","reply to a comment","Tuesday, July 9, 2019 At 8:51 AM",No
,7,00:00:43,AVT,"comment here tooo","reply again","Tuesday, July 9, 2019 At 8:51 AM",No
,8,00:00:43,"PJ Palomaki","comment here tooo","Different person reply","Tuesday, July 9, 2019 At 8:52 AM",No
,9,00:00:43,--,"comment here tooo","Anon reply reply","Tuesday, July 9, 2019 At 8:53 AM",No
"Test Video-01.mp4",6,00:01:29,--,"Anon comment",--,"Tuesday, July 9, 2019 At 8:53 AM",No
,7,00:01:29,--,"Anon comment","Anon reply","Tuesday, July 9, 2019 At 8:53 AM",No
,,,,,,,

If I parse with split("\n"), fields with line breaks get split. If I use split(",") any fields with commas get split.
Also, I'd like to include the parsing function in-line (in with the main script, rather than loading an external script) as I'd prefer to use a single file when deploying.
Thanks,
PJ

A: For an Extendscript project, I used the BabyParse library.. I had to edit it a bit to be used in Extendscript. Here is the gist. It will give you a JSON object which you can transform into your 2D-Array.

Also, I'd like to include the parsing function in-line (in with the main script, rather than loading an external script) as I'd prefer to use a single file when deploying.

Use some build tool like gulp for it. Or you can use the Extendscript // @include "path/to/file.jsx" or #include "path/to/file.jsx" include syntax.
Then you can combine them using github.com/fabianmoronzirfas/extendscript-bundlr.

(All links are shameless self-promotion ;-))

A: As far as I can see the problem is this CSV file is not a valid CSV file at all. Specifically the "really long comment..." has line breaks and double quotes inside. They should be escaped somehow first. Right after that parsing becomes a trivial task.
So, the question actually is: what would be the best way to find and handle double quotes and line breaks within such texts to turn them into valid CSV data and then to turn them into 2D arrays?
I'm not sure that the task can be accomplished for any arbitrary texts. It's not unlikely the combination of unwanted double-quotes AND line breaks AND commas inside is an insurmountable obstacle.


text:
Q: UIBezierPath bezierPathWithRect memory leak I am performing some profiling on my application. I have a method that computes a CGRect and based on that returns a UIBezierPath.
The Leaks tool in XCode Instruments is displaying memory leaks with the UIBezierPath bezierPathWithRect: method. Did anyone else experience this sort of issue? Is there any possibility that this may be a false positive?
I tested on both an iPhone 5s and iPhone 5c and the results are the same. Here are some shots from my Instruments (fig. 1 is the line description of the leaking method, fig. 2 is the leaks captured by instruments, both leading to this method):

Edit: code excerpt
- (UIBezierPath *)boundaryPath {
  CGRect boundary = CGRectZero;
UIBezierPath *bezierPath;
boundary.size.width = CGRectGetWidth(self.paneView.frame)/2;
boundary.size.height = CGRectGetHeight(self.tightWindow.frame);

if (CGRectGetMinX(self.tightWindow.frame) > 0) {
boundary.origin.x = 0.0f;
boundary.origin.y = 0.0f;
} else {
boundary.origin.x = CGRectGetMinX(self.paneView.frame);
boundary.origin.y = CGRectGetMinY(self.paneView.frame);
}

bezierPath = [UIBezierPath bezierPathWithRect:boundary];

return bezierPath;
}

Edit 2 - method usage
@property (nonatomic, strong) UICollisionBehavior *paneBoundaryCollisionBehavior;

...

[self.paneBoundaryCollisionBehavior removeAllBoundaries];
[self.paneBoundaryCollisionBehavior addBoundaryWithIdentifier:identifier forPath:[self boundaryPath]];

A: can you please describe something about the code.
Well in my case i was having the problem like with returning the CGPath. The value returned is a CGPathRef which is not covered by ARC. The UIBezierPath you create is released after the method ends. Thus also freeing the CGPathRef. You can specify a source annotation to let ARC know your intent:
In the .h file:
-(CGPathRef)makeToPath CF_RETURNS_RETAINED;
-(CGPathRef)makeFromPath CF_RETURNS_RETAINED;

Hope this help!!


text:
Q: Plot function in window Create a method plot(window, expression, color = "black") to plot the expression in the
window.
This is what i've done:
from math import *
from graphics import *
win = GraphWin()

def plot(window, expression, color = "black"):
    #Evaluates given expression and plots it in "window". Returns the list of all the                                       plotted points.

    points = []

    #Evalute expression over 1000 different values and for each (x,y) pair plot the point.

    for i in range(0, 1001):
        try:
            x = i/100.0
            y = eval(expression)
            plot(x,y)

        except Exception:
            print("For ", x, " the expression is invalid")

    return points

So i guess i have done something wrong. Can someone help me? :)

A: Looking at your code you have a function called plot that calls plot - this is because of the classic error of from somewhere import *.
I suspect that you are trying to call graphics.plot within plot so get rid of the from graphics import * and put graphics. before the items that you are using from there.
You are also not filling in, or using your points list.

A: There are a couple of obvious problems:

*

*You create a list of points, never put anything into it, then return it (still empty) at the end; and

*For each individual point x, y you call plot again recursively (see Steve Barnes' answer), passing x as window and y as expression.

I suggest you separate this into two parts: one to create a list of points based on the function, and one to plot this list of points.

A: *

*don't use the name plot as your own function name, this will shadow the matplotlib.pyplot.plot method name if you have import *.

*the matplotlib plot method is used to create lines, which needs a series of Xs and Ys each time you call it. E.g., plot(1,2) or plot([1], [2]) will plot nothing in the figure, while plot([1,2], [3,4]) draws a line between point (1,3) and (2,4). You need to call scatter(1, 2) if you insist on plotting one point each time.


text:
Q: Using the Twitter gem to pull a Twitter List using slugs This question piggy backs off
Get list timeline by using Twitter gem.
In this case however, I'm trying to pull the list itself as opposed to the list_timeline, passing in the list slug, per the documentation here:
https://rdoc.info/gems/twitter/Twitter%2FREST%2FLists:list
and grab some of the relevant info about the list, per the methods listed here:
https://rdoc.info/gems/twitter/Twitter/List
This is the code I'm using to do this, I want my retrieve_a_list function to return an object of type Twitter::List
def
@client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

def retrieve_a_list(slug)
  @list_info = @client.list(slug)
  return @list_info
end

Calling this function in the ruby console gives the following error, and I'm not sure if this is because I'm inputing the slug incorrectly or something else is going on here.
[6] pry(main)> list = C.retrieve_a_list('emilyslist')
Twitter::Error::NotFound: Sorry, that page does not exist.
from /Users/drewbateman/.rvm/gems/ruby-2.7.4/gems/twitter-7.0.0/lib/twitter/rest/request.rb:97:in `fail_or_return_response_body'

I've verified that https://twitter.com/emilyslist actually exists. This is the same error for basically all lists I try and I'm not sure where I'm going wrong here


text:
Q: (systemjs) xhr error (404 not found) loading I use a service in an Angular 2 app, and I get an error which is attached below.
I started this project using "Angular 2 QuickStart" cloned as 'my-proj'.
Error screenshot
systemjs.config.js
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
 System.config({
 paths: {
   // paths serve as alias
   'npm:': 'node_modules/'
  },
  // map tells the System loader where to look for things
  map: {
   // our app is within the app folder
   app: 'app',

  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
  '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

  // other libraries
  'rxjs':                      'npm:rxjs',
  'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
  app: {
    main: './main.js',
    defaultExtension: 'js'
  },
  rxjs: {
    defaultExtension: 'js'
  },
  'angular-in-memory-web-api': {
    main: './index.js',
    defaultExtension: 'js'
   }
 }
});
})(this);

app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, JsonpModule } from '@angular/http';

import { AppComponent }  from './app.component';
import { ProfileComponent }  from './components/profile.component';

@NgModule({
imports: [ BrowserModule,HttpModule,JsonpModule ],
declarations: [ AppComponent,ProfileComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

profile.component.ts
import { Component } from '@angular/core';
import {GithubService} from '../services/github.service';
import 'rxjs/add/operator/map';
@Component({
moduleId:module.id,
selector: 'profile',
templateUrl:'profile.component.html'
})
export class ProfileComponent {

constructor(private githubService:GithubService){
    this.githubService.getUser().subscribe(user => {
        console.log(user);
    });
}
}

github.service.ts
import { Injectable } from '@angular/core';
import {Http,Headers} from '@angular/Http';
import 'rxjs/add/operator/map';
@Injectable()

export class GithubService{
private username:string;

constructor(private http:Http){
    console.log('Github Service Ready...');
    this.username='bradtraversy';
}

getUser(){
    return this.http.get('http://api.github.com/users'+this.username).map(res => res.json);
 }
}

A: In github.service.ts, change
import {Http,Headers} from '@angular/Http'

to
import {Http,Headers} from '@angular/http'

might help.


text:
Q: Blank Screen while using react-navigation I am beginner is React Native, I have created a sample application and trying to add react-navigation
here is my code in App.js
import React, {Fragment} from 'react';

import {
StyleSheet,
View,
StatusBar,
} from 'react-native';

import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

import Container from './ScreenContainer';

const App = () => {
 return (
<View style={styles.container}>
  <StatusBar backgroundColor="#819ca9" barStyle="light-content"   hidden={true}></StatusBar>

</View>
);
};

const styles = StyleSheet.create({
 container:{
 justifyContent: 'center',
backgroundColor:'#819ca9',
flex: 1,
// alignItems:"center"
},
});

export default App;

And this is my ScreenContainer.js
import { createAppContainer, createStackNavigator, StackActions,    NavigationActions } from 'react-navigation'; // Version can be specified in package.json
import login from './pages/login'; //import Login from './pages/login';
const NavigationStack = createStackNavigator({
SignUp: login
});

const Container = createAppContainer(NavigationStack);

export default Container;

When I use this js in my App.js everything goes blank, after research a lot I found if I comment alignItems:"center" then my screen comes bt everything get distorted, search a lot on internet couldn't found the proper solution
Here is my package.json
{
"name": "MobileAPP",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"react": "16.8.6",
"react-native": "0.60.4",
"react-native-gesture-handler": "^1.3.0",
"react-native-router-flux": "^4.0.6",
"react-navigation": "^3.11.1"
},
"devDependencies": {
"@babel/core": "7.5.5",
"@babel/runtime": "7.5.5",
"@react-native-community/eslint-config": "0.0.3",
"babel-jest": "24.8.0",
"eslint": "^6.0.1",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.1",
"react-test-renderer": "16.8.6"
},
"jest": {
"preset": "react-native"
 }
 }

Can anyone help me how to make this working without disturbing my UI.
Thanks a lot

A: I see that you've imported Container in your App.js but I can't see it being used anywhere.


text:
Q: Get response from POST type method from restful API How can I fetch the json response from the POST method? Currently I'm only able to fetch Status - 401 Unauthorized and StatusCode - 401
func postUrl(url string, byt []byte) (*http.Response, error) {
    tr := &http.Transport{
        DisableCompression: true,
    }
    client := &http.Client{Transport: tr, Timeout: 10 * time.Second}
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(byt))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")
    req.Header.Add("Authorization", "Basic "+basicAuth("username", "password"))
    resp, err := client.Do(req)
    return resp, err
  }

Above code produces the output:
{
  "errorMessages": [
    "You do not have the permission to see the specified issue.",
    "Login Required"
  ],
    "errors": {}
}

A: The way to read the response (if there is one) is the same regardless of what status you get.
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

A: As Frank said, regardless of the status code in the response you can simply read its body to use whatever content it has.
Particularly for the case of a JSON message, you have two options depending on whether you know the JSON message structure in advance (or want your code to depend on it).
If you know the structure and are ok with hard-coding it (plus you gain some type safety and better client code) you can have:
type ErrorResponse struct {
    Messages []string `json:"errorMessages"`
}

And then when you detect an error status code unmarshal the response body as that struct:
if resp.StatusCode % 100 != 2 {
    var error ErrorResponse
    err := json.Unmarshall(resp.Body, &error)
    // check err != nil ...
    // user error.ErrorMessages for whatever you want
}

Alternatively if you don't want to depend on the JSON structure (to some degree) you can try to unmarshall it to a map[string]interface{} and try to use that in the generic way you think you can (generally not very useful).

A: This question is not related to http responses and http methods. Decode json string (wich is http response body in that case) with json decoder.
Simple example
(not directly related to your code snippet)
type Transition struct {
    Transition map[string]int
}

func main() {
    resp, err := postUrl(url, byt)
    if err != nil {
        log.Fatal(err)
    }

    var trans Transition
    decoder := json.NewDecoder(resp.Body)

    if err := decoder.Decode(&trans); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v\n", trans)
}


text:
Q: jqGrid. First single click on column span-resizer sets column width to default calculated I have an issue when I'm clicking first time to column's span-resizer --> column width returns to some default calculated value. The same thing appears when I'm trying to resize it: it resizes not from current width, but from that calculated!
This shows my table after page load: columns' width are good.
screenshot after page load
But after clicking to resize State column --> it's just returns to some value (in that case
screenshot after click on column resize
How can I fix this issue?
P.S. Sorry, I have no enough rep to add images.

A: jqGrid hold column header and the column data in separate dives. So jqGrid have to hold scroll position of the header div (hDiv) the same as the scroll position of the div with the grid body (bDiv). I think that jqGrid have a bug in your situation. As the workaround you can use resizeStop where one set the scroll position of hDiv to the current scroll position of bDiv:
resizeStop: function () {
    this.grid.hDiv.scrollLeft = this.grid.bDiv.scrollLeft;
}

I think that it should solve the problem.


text:
Q: Where to find aapt2 logs? When I try to build my project, I get the following error:

In the end it is stated: "check logs for details". Where to find those aapt2 logs?

A: NOTE: regarding disabling AAPT2, it's not a good idea. AAPT is now deprecated and will be removed by the end of 2018. Disabling it just delays the problems you'll have to fix either way when AAPT is deprecated and removed.

The logs do unfortunately not show up directly in the regular build window. I'm not sure why, or who thought it was a good idea, but that's how it currently works. You'll need to pop into the text-based version.
Using AS 3.1 (possibly 3.0 as well, I'm using 3.1 so I can't test there) or IntelliJ 2018.1, you open the build tab:

In this case I intentionally created a syntax error in some XML code (there are other places you can get AAPT2 errors too, like in the manifest or Kotlin, or somewhere else. This is just for the sake of demonstrating). I've highlighted a button in the image. If you hover over the button it should say "Switch view". Click it and you'll enter the text-based version of the build tab:

In this case I set an XML property to a non-existent value. The actual problem is formatted as JSON (see the content of the red circle). Inside the pink one is the actual error message (resource not found), the blue circle contains the file (in this case label_layout.xml) and content of the black circle contains the location (line 4).
What the actual error is will vary from time to time, so I'm not going to add how to solve it, because there's a wide range of different problems that could be the cause. Most of the time it's your code (so far I haven't seen any cases where AAPT2 crashes or has a bug that prevents compiling). Actually solving these issues get a lot easier with decent log output.

For reference, the same applies to compilation errors:

Though the syntax is slightly different:

The icon changed in a later version. I will not be keeping active updates of the icon itself beyond this.
For future reference: hover over the buttons in the build window until you find one that says "Toggle view":

That is the button you're looking for, regardless of what icon Google decides to use for it in future versions of Android Studio - at least until they fix the issues.


text:
Q: How to query relation in laravel scope I have the following scope that I would like to amend slightly:
function scopeNotRunOut($query)
{
    return $query->has('redemptions', '<', DB::raw('quantity'));
}

This return all models where the related redemptions count is less than the quantity column. The redemptions table has a column for user_id so how would I tweak this so that it only counts redemptions where the user_id column is a given value?

A: Managed to work it out myself in the end, here is the answer:
function scopeCustomerMaxUsesValid($query, $user_id)
{
    return $query->whereHas('redemptions', function($query) use ($user_id) {
        $query->where('user_id', '=', $user_id);
    }, '<', DB::raw('quantity'));
}


text:
Q: In ETL, How to handle new data inserted in Source DB with past Timestamp? We have a DWH that is connected to several sources DB's. We recently faced an issue where one of the sources inserted a new set of records with Timestamp that is in the past (not the actual Timestamp of the insertion to their DB). We use the Timestamp to extract Delta records. So in this case these new set of records are not getting extracted in our delta extraction. I believe using rowversion would be an ideal solution but we do not have control over this source and we can't guarantee this won't happen again. What would be a good solution to handle such cases? We use Datastage.
Thanks!


text:
Q: How should I animate a Circle/Soap-Bubble in iOS (possibly with Swift)? I'm not an expert on animations and drawing, so I'm trying to validate the most efficient way to solve this problem.
I need to create a Soap Bubble-Like Circle view; it should look like a soap bubble that floats in the air, for now I'm just concerned on the shape and not the position on screen, which is assumed to be fixed.
The end result should be a Circle that gets deformed at specific points along the circumference (as a soap bubble would look when it floats in the air).
I've been thinking of these possible solutions:

*

*Explore the particle effects available in SpriteKit to find some ready-made effect.

*Use UIBezierPath to draw a deformed circle with some function and animate it.

Since both of the things require some degree of deepening, I'd like to know which one in your opinion would be the best solution to do the job, some examples or tutorials would be greatly appreciated.

A: If I've understand your question, you want to realize something similar to  the "soap bubbles". I think the fastest way was to make SKShapeNode with some animation to change  it's path during the time but you don't have the sensation to see a bubble deformation..and in my honest opinion this result is ugly. Another ugly situation can be obtain with SKFieldNode.
You can also constraining a node(with SKConstraint) to obtain some deformation but it's hard to calculate everytime a reasonable distortion especially because you should have to do with more than one constraint..
I think that the best result could be obtained with SKWarpGeometryGrid that allows you to deform sprites (iOS 10).

I think that if you follow this example to understand how to prepare your grid, you can build your control points array  and define a warp geometry to have a good "soap bubble" simulation.
I hope this helps for your research.

A: in viewDidLoad:
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(makeBubble), userInfo: nil, repeats: true)

and add a function in your viewController:
@objc func makeBubble() {
    let bubbleImage = UIImage(systemName: "circle")
    let bubbleImageView = UIImageView(image: bubbleImage)
    let screenSize = UIScreen.main.bounds
    let bubbleWidth = Int(bubbleImage!.size.width)
    let bubbleHeight = Int(bubbleImage!.size.height)
    let randomX = arc4random_uniform(UInt32(screenSize.width))
    bubbleImageView.frame = CGRect(x: Int(randomX) - Int(Double(bubbleWidth) * 0.5), y: Int(screenSize.height) + bubbleHeight, width: bubbleWidth, height: bubbleHeight)
    view.addSubview(bubbleImageView)
    UIView.animate(withDuration: 7.0, animations: {
        bubbleImageView.center = CGPoint(x: bubbleImageView.center.x, y: CGFloat(-bubbleHeight))
    }) { (finished: Bool) in
        bubbleImageView.removeFromSuperview()
    }
    UIGraphicsEndImageContext()
}


text:
Q: Load DIV tag from external file I am trying to get rid of the FRAME tag by trying to load a DIV tag when a link is selected in my NavBar (what used to load "file1.html" target="ContentFrame"). I now have the single page divided into two DIV tags. The top DIV tag is my navbar which works perfectly loading html files into a FRAME, but now I'm trying to instead load the HTML file (after removing all the extra HTML tags like HTML, HEAD, BODY, etc...) into a second DIV tag called "Content". I've looked into jQuery .Load, but can't seem to get that to work like I want. I was considering looking into PHP instead now. I'm really open to suggestions on what to look for, or any example source that might do something like I want. Any ideas?

Load body1.html into DIV ID Content
Load body2.html into DIV ID Content

  Contents of body1.html would be here when page is first loaded.
  Then the contents here would be loaded from the file in the anchor
  tag when a link is selected. The bodyX.html files would have tags
  within them as well. Not just text.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="styles.css" />

    <title>Index Page</title>

Home

Officers

<a href="announce.html"

Events

Continuing Ed

A: Switch to .php extensions, and if your main file for example is called "index.php" create two other files with the contents of the two divs (for example: div1.php and div2.php
Based on the above, your index.php should look similar to that:

..... head here

<?php include('div1.php'); ?>

<?php include('div2.php'); ?>

Very basic and unpolished example but should give you a point to start...
UPDATE:
First check out this updated fiddle: http://jsfiddle.net/vc2nq3us/3/
This is not working of course since ajax is not included in my fiddle. You can just use this code for your project and will be ok...
Now, there is one more file involved -not showing in jsfiddle. It can be something like that:
<?php

//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}

if(isset($_POST["fileid"])){$fileid = $_POST["fileid"];}else{$fileid = ""; exit();} //if no fileid is set, kill the script

$file_contents = file_get_contents($fileid.".html"); //here we fetch the contents of file (for example: 1.html or 2.html and so on...)

echo htmlentities($file_contents);

?>

Hope this works for you... T.

A: Try using .click() , .preventDefault() , href of clicked a element within handler
$(function() {
  $("a").click(function(e) {
    e.preventDefault();
    $("#Content").load(this.href)
  })
  // load `body1.html` into `#Content` at page load
  .filter("[href^=body1]").click()
})

A:

    <meta charset="UTF-8">
    <title>Include</title>

    Link1
    Link2
    Link3
    Link4

A: Not sure why jquery.load is not working for you. Posting your efforts on that could be more beneficial.
Here is the documentation on it, it should work:
http://api.jquery.com/load/
Below: The selector is where you want to put the contents of the file. The parameter within the .load() is the path to the file.
$( "#Content" ).load( "file1.html" );

A: You wrong to use #Content try using #content instead :
$(function() {
  $("a").click(function(e) {
    e.preventDefault();
    $("#content").load(this.href);
  })
  .filter("[href^=body1]").click();
});


text:
Q: Have large lists of DVDs with years of movies, cannot get the two separated as lists into dictionary format Hello I am using a Python(3.8.2) for loop with this list of DVD's a family member has given me, all organized as:
A Walk Among the Tombstones (2014)
Blithe Spirit (2020)
Jeepers Creepers (2001)
The Place Beyond the Pines (2012)

etc....
Search code:
inp = input().lower().title()
if inp in movieTitle:
    print(inp+ " DVD is AVAILABLE")
else:
    print("THIS DVD IS NOT AVAILABLE")

Code to extract titles/years:
for lin in L:
    movieName = re.findall('(^.*)\s', lin)
    movieTitle.append(movieName)
    movieYr = re.findall('(\(....\))$', lin)
    movieYear.append(movieYr)

note: ('L' is the original list created from the string of the .txt file)
I am creating a search via user input to check for existing titles. I have been successful at retrieving just the titles of the DVD's using re.findall so that the user input easier matches the title (otherwise it will show as non existant without them entering the year in parentheses).
The ISSUE I am having is that once I extract just the titles, I now have a list in which I cannot add into a dictionary as a Key. The movie years I have extracted separately as well, and those I want to add as the Value to the key.
I have had many "unhashable type" list errors and have reviewed many posts regarding a similar situation. Where my situation doesn't seem to relate, is that my titles have spaces and multiple words for certain titles as well as many line items.
Please advise how I may approach this in another way; thanks and cheers~

A: The re.findall will return a list so you cannot use that as a dictionary key. You can use re.search and the get correct search group. For example:
import re

with open("your_file.txt", "r") as f_in:
    L = f_in.readlines()

movies = {}
for lin in L:
    movieName = re.search(r"^([^(]+)", lin).group(1).strip()
    movieYr = re.search(r"\((\d+)\)$", lin).group(1)
    movies[movieName] = movieYr

inp = input("Search for movie: ").lower().title()

if inp in movies:
    print(inp + " DVD is AVAILABLE")
else:
    print("THIS DVD IS NOT AVAILABLE")

Prints:
Search for movie: Blithe Spirit
Blithe Spirit DVD is AVAILABLE

The movies dictionary is:
{
    "A Walk Among the Tombstones": "2014",
    "Blithe Spirit": "2020",
    "Jeepers Creepers": "2001",
    "The Place Beyond the Pines": "2012",
}


text:
Q: Singleton. приватная переменная в потомке класса Application В одном из ответов на форуме есть такие слова:
Лучше создать приватную переменную в потомке класса Application со ссылкой на экземпляр вместо приватной статической в самом классе сиглтона, если это возможно.
Я запутался, не могу понять разницу, покажите пожалуйста код, где всё сделано по этой рекомендации и код, где переменная в самом классе.
Ну вот переменная в самом классе, выглядит так:
public class Singleton {
 private static Singleton instance;

 private Singleton (){}

 public static Singleton getInstance(){
  if (null == instance){
   instance = new Singleton();
  }
  return instance;
 }
}

Переменная в подклассе Application как выглядит не пойму..Скорее потому, что я не понимаю в чем будет выгода, если выполнить эту рекомендацию.
Принятый ответ в этом вопросе и является темой моего вопроса
Singleton в Android - зло?

A: Application - базовый класс для хранения глобального состояния приложения. Использовать можно например так (нужно добавить android:name=".MyApplication" в раздел  файла AndroidManifest.xml):
public class MyApplication extends Application {
    private String mName;

    @Override
    public void onCreate() {
        super.onCreate();
        setName("Application instance is maintaining global application state");
    }

    public void setName(String name) {
        mName = name;
    }

    public String getName() {
        return mName;
    }
}

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyApplication myApplication = (MyApplication)getApplication();
        String s = myApplication.getName();
        Log.d("TAG", s);
        myApplication.setName("tester");
        Log.d("TAG", myApplication.getName());
    }
}

Однако гугл рекомендует использовать Singleton:

Note: There is normally no need to subclass Application. In most
  situations, static singletons can provide the same functionality in a
  more modular way. If your singleton needs a global context (for
  example to register broadcast receivers), include
  Context.getApplicationContext() as a Context argument when invoking
  your singleton's getInstance() method.

https://developer.android.com/reference/android/app/Application


text:
Q: Is it ok to use glob.has_magic? I have a bit of code where I'd like to know if a path has shell wildcards, which seems like something that would be defined in a central location.  I've found that glob.has_magic() provides this (it's just a regex: '[*?[]').  But this method is not listed in the module's __all__ list, and does not appear in the pydoc.
Should I just copy this regex into my code?  (I'd prefer not to)
Is there a risk of this method being removed in future versions of python, since it does not show up in the documentation?

A: Personally I would copy the regexp. It's not like the definition of glob patterns will ever change, forcing you to change it in your code. The fact that the method is not made available externally by the stdlib means that there is no promise that it won't change in the future. I wouldn't worry about it CHANGING in the future (for the same reason as above: the definition of a glob pattern won't change) but I would be worried that it might be REMOVED if the module's implementation were refactored so that it was not required anymore.


text:
Q: When using python tvm, No CUDA-capable device is detected I wrote the following python code
import tvm

ctx = tvm.device("cuda", 0)
print("ctx: ", ctx.exist)

The output is
ctx:  False

However, I install cuda and cuda driver.
The nvidia-smi result is,
NVIDIA-SMI 495.44       Driver Version: 495.44       CUDA Version: 11.5

I use lspci -vnn | grep VGA to check whether there is a GPU. The result is
03:00.0 VGA compatible controller [0300]: Matrox Electronics Systems Ltd. Integrated Matrox G200eW3 Graphics Controller [102b:0536] (rev 04) (prog-if 00 [VGA controller])
3b:00.0 VGA compatible controller [0300]: NVIDIA Corporation Device [10de:1e04] (rev a1) (prog-if 00 [VGA controller])
af:00.0 VGA compatible controller [0300]: NVIDIA Corporation Device [10de:1e04] (rev a1) (prog-if 00 [VGA controller])
d8:00.0 VGA compatible controller [0300]: NVIDIA Corporation Device [10de:1e04] (rev a1) (prog-if 00 [VGA controller])

And my system is Linux PowerEdge-R740 5.4.0-90-generic #101~18.04.1-Ubuntu.My python version is 3.6.
I don't know why tvm cannot find the correct device.

A: One possible source of error could be that you did not enable CUDA backend support when installing TVM.

Edit build/config.cmake to customize the compilation options.
Change set(USE_CUDA OFF) to set(USE_CUDA ON) to enable CUDA backend. Do the same for other backends and libraries you want to build for (OpenCL, RCOM, METAL, VULKAN, …).

Please refer to: https://tvm.apache.org/docs/install/from_source.html#install-from-source
(I would have commented, but not enough reputation)


text:
Q: Perspective correct texture mapping in Pixi.js My purpose is making a simple 3d engine with 2D sprite (I choose Pixi.js this time as I can control the vertices of sprite arbitrarily), but I cannot understand how to map the texture to a perspective projected quad correctly.

texture: https://imgur.com/Z5xDL8V

I am using the PIXI.mesh.Plane for the quad, if the subdivision is low
var verticesX = 2, verticesY = 2;
this.field = new PIXI.mesh.Plane(resources['palette'].texture, verticesX , verticesY );

This will give out the result of screenshot01: https://imgur.com/a/m261h

You can see the texture mapping is incorrect.

Goes on I increase the division to 4 after the projection to screen vertices, and calculate the division point linearly.
this.field = new PIXI.mesh.Plane(resources['palette'].texture, 5, 5);
var lt = [this.field.model.screenVertices[0], this.field.model.screenVertices[1]];
var rt = [this.field.model.screenVertices[2], this.field.model.screenVertices[3]];
var rb = [this.field.model.screenVertices[4], this.field.model.screenVertices[5]];
var lb = [this.field.model.screenVertices[6], this.field.model.screenVertices[7]];
var segX = this.field.verticesX - 1;
var segY = this.field.verticesY - 1;
var vertices = [];
for (var i = 0; i < (segY + 1); i++) {
  var l = (lb[0] - lt[0]) / segY * i + lt[0];
  var r = (rb[0] - rt[0]) / segY * i + rt[0];
  for (var j = 0; j < (segX + 1); j++) {
    var t = (rt[1] - lt[1]) / segX * j + lt[1];
    var b = (rb[1] - lb[1]) / segX * j + lb[1];
    vertices[(i * (segY + 1) + j) * 2] = (r - l) / segX * j + l;
    vertices[(i * (segY + 1) + j) * 2 + 1] = (b - t) / segY * i + t;
  }
}
this.field.vertices.set(vertices);

that is 4x4 division as 5 points for each edges, the result is shown as screenshot02: https://imgur.com/a/6HREk, but the height of each division is the same, the illusion of perspective is broken

How can I achieve the result as the screenshot: https://imgur.com/a/ZEUHu

The height of division proportion to the depth respectively

Or am I heading to a wrong direction to solve the problem, please suggest me some advise, thanks.
PS. The debug message in the screen is describing the vertices coordinate of the field lay on ground in clipping space, not the screen space.

A: You need to apply perspective and calculate your (x2, y2) coordinates from a (x3, y3, z3) 3D space point.
The simplest perspective transform equations are:
x2 = x3 / z3
y2 = y3 / z3
being (x3, y3, z3) space defined as (0, 0, 0) is the camera position, z is the viewing direction, x3 is the horizontal perpencitular axis and y3 is the vertical perpendicular axis. And for the 2D (x2, y2) the (0, 0) should be the center of the screen.
You can read more in https://en.wikipedia.org/wiki/Transformation_matrix#Perspective_projection and in https://en.wikipedia.org/wiki/3D_projection#Weak_perspective_projection
To get something rendered, a visible quad, you can try these 3D points should work:
(100, -100, 3), (100, -100, 5), (-100, -100, 5), (-100, -100, 3)
Now, subdivide in 3D coordinates, not in 2D coordinates and calculate for each 3D vertex the 2D projected position.
You probably will need to apply 3D transforms to move and rotate camera and objects, check this: https://en.wikipedia.org/wiki/Transformation_matrix#Examples_in_3D_computer_graphics
However you will still have problems with texture perspective correction if you use an image. The more subdivisions, the less problems.
I think it will be better to use three.js or other webgl library.


text:
Q: How can I add interactive python console to my website? I'd like to create an educational website where I would like people to be able to run Python console from an interpreter window and also be able to modify that code in the window and run it again to see how the results vary.
In the link below there is a good example of this:
https://www.safaribooksonline.com/oriole/saf-generative-adversarial-networks-for-beginners
I know I can create a Jupyter notebook and embed it with an iFrame, but it only displays the static version. I want to find a way to run the kernel server- or client-side and let people play around.

A: It looks like the example link you provided uses O'Reilly's open source project Thebe: https://github.com/oreillymedia/thebe
The readme in the repo provides some instructions to get it set up. Hope that helps!


text:
Q: Django Template - List not rendering properly I have the following list which is sent to django template using render function: ["9.8 m/s", "9.9 m/s", "1.0 m/s"].
When the list is printed in javascript function, it shows as: ["9.8 m/s", "9.9 m/s", "1.0 m/s"]
I have used the following to print the list: console.log("{{ options }}"); in javascript function.
I have tried iterating over as
{% for option in options %}
    console.log("{{ option }}");
{% endfor %}

The above code displays single characters as opposed to printing list elements.
Also tried JSON.parse and JSON.stringify functions in javascript.

A: The template engine will HTML escape the strings it renders. You can avoid that with the |safe template filter:
var options = {{ option|safe }};

for (var i = 0; i < options.length; i++) {
    console.log(options[i]);
}


text:
Q: lineedit-password-character proprety not working in PyQT5 I created a QlineEdit, the content of which I would like to mask, I resorted to the QLineEdit.Password EchoMode, but unfortunately it doesn't let me specify the mask character. I stumbled upon the lineedit-password-character StyleSheet proprety, but it does nothing.
password_field.setEchoMode(QtWidgets.QLineEdit.Password)
password_field.setStyleSheet("color: #88c0d0; border: 0; lineedit-password-character: 2731; selection-background-color: #88c0d0; selection-color: #2e3440;")

The mask character I want is *
# Password field
password_field = QtWidgets.QLineEdit(window)
password_field.resize(input_window.width() - password_label.width() - input_field_offset - input_window_padding * 2, password_label.height())
password_field.move(password_label.x() + password_label.width() + input_field_offset, password_label.y())
password_field.setEchoMode(QtWidgets.QLineEdit.Password)
password_field.setStyleSheet("color: #88c0d0; border: 0; lineedit-password-character: 61; selection-background-color: #88c0d0; selection-color: #2e3440;")

A: You need to specify the ASCII value for '*' which is 42.
This worked for me.
password_field.setStyleSheet("color: #88c0d0; border: 0; lineedit-password-character: 42; selection-background-color: #88c0d0; selection-color: #2e3440;")


text:
Q: Show that the polynomial $x^2 + x + 1$ is irreducible in $\mathbb Z/2\mathbb Z[x]$ I've looked up Eisensteins criterion, but I don't understand how to apply it to show that
$ x^2 + x + 1$ is irreducible.
Edit: Ok, I see now that Eisensteins criterion does not apply here.

A: Since the degree of $f(x) = x^2 + x + 1$ is $\leq 3$, then $f$ is irreducible if and only if $f$ has no roots in $\mathbb{Z}_2$. (why?)
Well, in $\mathbb{Z}_2$, the only possible roots are $0$ and $1$. Try them out!

A: Hint: a quadratic polynomial is reducible over $k$ iff it has a root in $k$.


text:
Q: Use array map to modify entire object I'm using typescript (angular2) to create a "reset" method on an object array:
cars [
  {
    id: 1,
    color: white,
    brand: Ford,
    model: Mustang,
    ...
  },
  ...
]

User can modify this objects, and he can also "reset" to default values. So I keep an array of objects called originalCars. So if he selects the first object and choose "reset", I want to do something like: car = originalCar.
I was doing this:
this.selectedCars().map(car=> {
  const originalCar = this.getOriginalCar(car.id);
  car.color = originalCar.color;
  car.brand = originalCar.brand;
  // ... I'm doing this to all properties of my object
 });

This is working, but I want to do it simple. Something like car = originalCar. I tried:
this.selectedCars().map(car=> {
  const originalCar = this.getOriginalCar(car.id);
  return originalCar;
  // also tried car = originalCar;
 });

The selectedCars method is:
selectedCars = () => {
    return this.cars.filter(car=> {
        return car.selected;
    });
};

But It did not work. How can I do this?

A: With the map function you create a new array of whatever thing you return from the method. Which means, you have to overwrite the selectedCars property:
this.selectedCars = this.selectedCars.map(car => this.getOriginalCar(car.id));

A more weird way of doing it, is by using the forEach method. That would be something like this:
this.selectedCars.forEach((car, index) => {
  this.selectedCars[index] = this.getOriginalCar(car.id);
});

If you just want to reset one car by id:
resetCar(id: number): void {
  const idx = this.selectedCars.findIndex((car) => car.id === id);

  if (idx > -1) {
    this.selectedCars[idx] = this.getOriginalCar(id);
  }
}

New information has come to light, and your selectedCars() is a method. In that case you can do the following:
this.selectedCars().forEach((car, index) => {
  Object.assign(car, this.getOriginalCar(car.id));
});

It however does not feel proper, because you are updating an object and causing side-effects. Better would be to just create a new array/object collection


text:
Q: Cannot Run *.java downloaded file I have downloaded a java file needed for a coursework at college. However I find it impossible to run it. Eclipse won't give me the chance to even run it (only ant build), and if I use netbeans I get this exception :
Exception in thread "main"
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java
at Hangman. < clinit > (hangman(Case Conflict).java: 20)
Java Result: 1

If someone is kind enough to read through the code, I really do not know what to do next. I figure there has to be something wrong with the main class. Thanks!
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

class Hangman {
  Scanner userInput;
  private Set < Character > wrongGuesses;
  private String[] answers = {
    "leverets", "hatchlings", "puppies",
    "kittens", "pullets", "goslings"
  };
  private String answer;
  private String guessed;
  private int maxTurns;
  private int currentTurns;
  private boolean inProgress;
  private char nextGuess;
  private boolean gameWin;

  public Hangman() {
    userInput = new Scanner(System.in);
    wrongGuesses = new HashSet < Character > ();
    inProgress = false;
    gameWin = false;
    maxTurns = 14;
    currentTurns = 0;

    // set answer somehow
    answer = answers[0];

    // set guessed to the correct number of dashes
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < answer.length(); i++) {
      sb.append('-');
    }
    guessed = sb.toString();
  }

  /* start a new game */
  public void startGame() {
    inProgress = true;
    startGameLoop();
  }

  /* the game loop. this method is the heart of the game */
  private void startGameLoop() {
    printInstructions();
    while (inProgress) {
      printStatus();
      acceptGuess();
      checkStatus();
    }
    printWinOrLose();
  }

  private void printInstructions() {
    System.out
      .println("Guess the word one letter at a time until you win or run out of turns. Good luck!");
  }

  private void printWinOrLose() {
    if (gameWin) {
      System.out.println("You win! The answer was " + answer);
    } else {
      System.out.println("You lose.");
    }
  }

  private void printStatus() {
    System.out.println("Guesses left: " + (maxTurns - currentTurns));
    System.out.println("Current status: " + guessed);
    System.out.println("Wrong guesses: " + getWrongAnswers());
  }

  /* get the next character from the player */
  private void acceptGuess() {
    System.out.println("Next guess: ");

    String temp = userInput.next();
    nextGuess = temp.charAt(0);
  }

  /* check what state the game is in */
  private void checkStatus() {
    // if already guessed, say already guessed.
    if (wrongGuesses.contains(nextGuess)) {
      System.out.println("You already guessed that!");
      return;
    }

    // if guess is not in answer, update number of turns played and add
    // guess to wrong guesses
    // otherwise update the guessed variable
    if (answer.indexOf(nextGuess) < 0) {
      ++currentTurns;
      wrongGuesses.add(nextGuess);
    } else {
      updateGuessStatus();
    }

    // check to see if the player has won or lost
    if (answer.equals(guessed)) {
      gameWin = true;
      inProgress = false;
    }
    if (currentTurns == maxTurns) {
      inProgress = false;
    }
  }

  /* update the guessed variable when there is a correct guess made */
  private void updateGuessStatus() {
    // replace - with nextGuess where appropriate
    int index = answer.indexOf(nextGuess);
    int lastIndex = answer.lastIndexOf(nextGuess);

    StringBuilder sb = new StringBuilder(guessed);
    if (index != lastIndex) { // more than one instance of the guess in the
      // answer
      // swap out in a loop
      while (index != -1) {
        sb.setCharAt(index, nextGuess);
        int i = answer.indexOf(nextGuess, (index + 1));
        index = i;
      }
    } else { // letter only appears once
      // swap out just that one
      sb.setCharAt(index, nextGuess);
    }
    guessed = sb.toString();
  }

  /* build a text representation of all the incorrect guesses */
  private String getWrongAnswers() {
    if (wrongGuesses.size() > 0) {
      StringBuilder sb = new StringBuilder();
      sb.append('(');
      for (Character c: wrongGuesses) {
        sb.append(c + ",");
      }
      sb.deleteCharAt(sb.length() - 1); // delete trailing comma
      sb.append(')');

      return sb.toString();
    } else {
      return "<none>";
    }
  }

  public static void main(String[] args) {
    Hangman h = new Hangman();
    h.startGame();
  }
}

A: The exception says everything you need to know. Rename the class FILE to Hangman.java.
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java

A: You should save your downloaded file in Hangman.java and not hangman.java (see it needs 'H' in caps same as your class name).

A: Change the class to public class Hangman. It allows outside methods to access it.
EDIT: I downloaded the file, changing the class to public worked. I also found an issue in the code itself, the word is always "Leverets".
To change this, edit the getAnswer() method and change it to
private int getAnswer() {

    int i = (int) (Math.random() * 6) + 0;
    return i;
}


text:
Q: Not printing output ? python def binary_search(li, targetValue):
   low, high = 0, len(li)
   while low <= high:
        mid = (high - low)/2 + high
        if li[mid] > targetValue:
             low = mid - 1;
        elif li[mid] < targetValue:
             high = mid + 1;
        elif li[mid] == targetValue:
             return "we found it!"
   print start, end
   return False

I almost positive it  works. It works when the targetValue is present in the array, but when you ask it to find a value outside of the given elements, it doesn't work any more ...
Does anyone know why?

A: From http://docs.python.org/2/library/bisect.html

import bisect
bisect.bisect_left(li, targetValue)

A: I'm not sure exactly what you're trying to print, but I see where there might be some misbehavior from that function. Try something like this instead:
# binary search for list with desending values
def binary_search(li, targetValue):
    low, high = 0, len(li) - 1  # min & max index
    while low <= high:          # loop til high & low switch
        mid = (high + low) / 2  # midpoint (rounds down)
        if li[mid] > targetValue: low = mid + 1     # confine to upper half
        elif li[mid] < targetValue: high = mid - 1  # confine to lower half
        elif li[mid] == targetValue: return mid     # found it!
    return None  # nothing to return (low/high switched, so it wasn't found)

This will return the index of the match if targetValue is in li, or None otherwise. Use like:
li = [10000, 1000, 100, 10, 1]

if binary_search(li, 500) is None: print '500 not found!'
else: print '500 found!'

i = binary_search(li, 10)
if i is None: print '10 not found!'
else: print 'Found 10 at index ' + str(i) + '!'

That would output:
500 not found!
Found 10 at index 3!

For an acceding li, just switch < and >:
def binary_search(li, targetValue):
    low, high = 0, len(li) - 1
    while low <= high:
        mid = (high + low) / 2
        if li[mid] < targetValue: low = mid + 1
        elif li[mid] > targetValue: high = mid - 1
        elif li[mid] == targetValue: return mid
    return None


text:
Q: How do I make an USB printer halt mid-print? What I'm trying to do is make a USB printer behave a bit more like a dot matrix printer in the sense of being able to control when a page is actually ejected.
What I want to do is use two pdf files, one for the top of the page and one for the bottom, and have the printer print the first pdf, halt and wait for the second pdf to show up, then continue printing the second pdf on the second half of the page.
The idea here is that the first part of the paper should be able to be torn from a perforated page without having to wait for the second half to be done. I'm using C# and have looked at many different ways of printing raw data, but I'm not finding very much on this matter. Thank you all in advance and please let me know if any information is needed!


text:
Q: How to tell which process set the high timer resolution in Windows My system is suffering from a high timer resolution (NtQueryTimerResolution returns 0.5ms).
Maximum timer interval: 15.600 ms
Minimum timer interval: 0.500 ms
Current timer interval: 0.500 ms

Some process must be calling NtSetTimerResolution with a value of 5000 (0.5ms), but how can I determine which one? I saw Intel has a tool called Battery Life Analyzer that shows the current timer resolution per process, but that tool is only available to Intel partners. Is there another tool or a way to see it via WinDbg? Note: It seems to happen at boot time as setting a breakpoint isn't working (the resolution is already high when the debugger starts).

A: I found that Windows 7 keeps track of timer resolution per process in the _EPROCESS kernel structure.
With debugging enabled (boot with /debug) it is possible to browse the ExpTimerResolutionListHead list with windbg (run windbg -kl) and extract timer information like this:
lkd> !list "-e -x \"dt nt!_EPROCESS @$extret-@@(#FIELD_OFFSET(nt!_EPROCESS,TimerResolutionLink)) ImageFileName UniqueProcessId SmallestTimerResolution RequestedTimerResolution\" nt!ExpTimerResolutionListHead"
In my case however the process ID was NULL (probably because a driver made the request), and I still couldn't figure out which driver it was.

A: The only way I know and have used so far is injecting into each of running processes and inside that process calling timeEndPeriod for each increased resolution (values 1-15) in a loop over these resolutions and checking whether the timeEndPeriod call for a current resolution returns TIMERR_NOCANDO or TIMERR_NOERROR (note: these return values are NOT correspondingly false and true). And if it returns TIMERR_NOERROR then concluding that the program is using that frequency, and then calling again timeBeginPeriod to restore the original resolution requested by the program.
Unfortunately this method does not detect the 0.5 ms timer resolutions that can be set by undocumented NtSetTimerResolution function.
If you want to continuously monitor the new timer resolutions then hooking calls to undocumented NtSetTimerResolution function in ntdll.dll is the way I use currently (the function's signature can be taken for example from here).
Unfortunately hooking does not detect timer resolutions that were requested before the hook was installed, so you need to combine it with the above timeEndPeriod trick and note also that the 0.5 ms resolution requests before the hooking stay undetected.
And I agree, this method seems cumbersome. Moreover, it is a bit intrusive since it modifies the state of the process, and also assumes that you are able to inject into all processes.
If anybody has better methods, I would be interested knowing about them too.

A: Input
You can run the following command in a Administrative CMD Prompt:
c:\temp> powercfg -energy duration 5

This will create a report called: C:\temp\energy-report.html
This report will show you which processes have changed the Clock Latency/Resolution on your computer. Normally these are RTC (Real-Time Communication) applications, but as you have noticed can be Chrome and other applications.
Output
An (albeit German) example of the output looks like this. Sorry I don't have access to an English client at the moment.
First Statement in Report: Something has changed

Plattform-Zeitgeberauflösung:Plattform-Zeitgeberauflösung
Die standardmäßige Plattform-Zeitgeberauflösung beträgt 15,6 ms (15625000 ns) und sollte immer dann verwendet werden, wenn sich das System im Leerlauf befindet. Wenn die Zeitgeberauflösung erhöht wird, sind die Technologien zur Prozessorenergieverwaltung möglicherweise nicht wirksam. Die erhöhte Zeitgeberauflösung kann auf eine Multimediawiedergabe oder Grafikanimationen zurückzuführen sein.
Aktuelle Zeitgeberauflösung (100-ns-Einheiten) 10000 <<=== CURRENT SETTING
  Maximale Zeitgeberperiode (100-ns-Einheiten) 156250  <<== DEFAULT SETTING

Second Statement in Report: The Culprit

Plattform-Zeitgeberauflösung:Ausstehende Zeitgeberanforderung
Von einem Programm oder Dienst wurde eine Zeitgeberauflösung angefordert, die kleiner als die maximale Zeitgeberauflösung der Plattform ist.
Angeforderter Zeitraum 10000  <<== Requested Clock Latency
  ID des anfordernden Prozesses 12592  <<== Process ID of application requesting different Clock Latency
  Pfad des anfordernden Prozesses \Device\HarddiskVolume4\Program Files (x86)\C4B\XPhone Connect Client\C4B.XPhone.Commander.exe  <<== The culprit

The information can be separated from each other and can contain different modules in between the individual blocks, but you should be able to find the culprit armed with the information provided above.


text:
Q: Filter the query and refresh the recycler view using firebase in android @Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
}

The above is the code that I use to get the data from the firebase realtime database. How can I change the query (mDatabase in my code) and refresh the recyclerview to filter the data? How to set a new adapter? Please give me some helps.Thank you.

A: Try this:
FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

        Product.class,
        R.layout.product_row,
        ProductViewHolder.class,
        mDatabase.orderByChild("KeyName").equalTo("Value") //add this line
)
 mProductList.setAdapter(firebaseRecyclerAdapter);
  firebaseRecyclerAdapter.notifyDataSetChanged();  // also add this line

A: Set query in your database...
FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase.orderByChild("KeyName").equalTo("Value")

    )


text:
Q: Creating processes in Java using Activiti I have a requirement to create a dynamic multi level approval process for my application using activity.process diagram
The Number of steps and parallel approvals in each step is decided at run time.
In the diagram above, the number of levels, number of concurrent approvals with within each level are defined at record creation.
I am not looking to change the process at run time, but create the process at run time.
Is this possible using Activiti?

A:
I am not looking to change the process at run time, but create the process at run time.
Is this possible using Activiti?

Yes, it is. In fact I tried both, but for completely different requirement.
https://gromar01.wordpress.com/2016/06/16/design-by-doing-with-activiti6/
I would say that for your case it is possible to cover your requirements by standard BPMN model and do not use dynamically created process models.


text:
Q: Uncaught Error: Call to a member function prepare()
Fatal error: Uncaught Error: Call to a member function prepare() on
  null in C:\xampp\htdocs\PDO\config\DB.php:21 Stack trace: #0
  C:\xampp\htdocs\PDO\config\Student.php(14): DB::prepare('SELECT * FROM
  t...') #1 C:\xampp\htdocs\PDO\index.php(60): Student->readall() #2
  {main} thrown in C:\xampp\htdocs\PDO\config\DB.php on line 21

DB.php
class DB{
    private static $pdo;

    public function connection(){
        if(isset(self::$pdo)) {

            try{
                self::$pdo = new PDO ("mysql:host=".DB_HOST.";dbname=",DB_USER,DB_PASS);
                echo "Conncetion successfully";

            }catch(PDOException $e){
                echo "Conection Failed............".$e->getMessage();
            }
        }
        return self::$pdo;
    }
    public static function prepare($sql){ // own prepare() method
        return self::connection()->prepare($sql); //pdo prepare()
    }
}

Student.php
include "DB.php";

class Student{
    //private $table = "tb_user";

    public function readall()
    {

        //$sql = "SELECT * FROM $this->table";

        $sql = "SELECT * FROM tb_user";
            $stmt = DB::prepare($sql);
            $stmt->exceute();
            return $stmt->fetchAll();
    }

}

A: Change the statement from
 if(isset(self::$pdo)) {

into
 if( ! isset(self::$pdo)) {

You need to create pdo object if it doesn't exist


text:
Q: How to create hyperlink within PDF (which is opened in browser) which will open in a new tab/window I generate some PDF via XSLT transformation (FOP) from XML. The PDF file is opened in the browser. If it contains any hyperlink, that hyperlink is supposed to open in a new browser tab/window. I'm quite not sure if it is even possible. Any insights?

A: You could try show-destination property. It's mentioned on some sites but I couldn't get it to work. I believe it also depends on which Fo Processor you're using, your browser settings and the PDF reader.


text:
Q: scrape a table in a website with python (no table tag) I'm trying to scrape daily the stock value of a product. This is the web https://funds.ddns.net/f.php?isin=ES0110407097. And this is the code I'm trying:
import pandas as pd
from bs4 import BeautifulSoup

html_string = 'https://funds.ddns.net/f.php?isin=ES0110407097'
soup = BeautifulSoup(html_string, 'lxml')

new_table = pd.DataFrame(columns=range(0,2), index = [0])

row_marker = 0

column_marker = 0
 for row in soup.find_all('tr'):
     columns = soup.find_all('td')
     for column in columns:
         new_table.iat[row_marker,column_marker] = column.get_text()
         column_marker += 1

print(new_table)

I would like to get in Python the same format I can see in the web, both the data and the number. How can I get it, please?

A: There's a simpler way for that particular page:
import requests
import pandas as pd

url = 'https://funds.ddns.net/f.php?isin=ES0110407097'
resp = requests.get(url)

new_table = pd.read_html(resp.text)[0]
print(new_table.head(5))

Output:
            0          1
0       FECHA     VL:EUR
1  2019-12-20  120170000
2  2019-12-19  119600000
3  2019-12-18  119420000
4  2019-12-17  119390000


text:
Q: How to build ionic1- project in ionic3 environment? My boss gave me an ionic1 project, but my computer is the ionic3 environment. How can I package the project.
'python' : "v-2.7"
'node'   : "v-8.9"
'cordova': 'v-7.1'
'ionic'  : "v-3.18"

A: You have to just use this command
ionic start <YOUR APP NAME> --type=ionic1

hope this works for you

A: you can create new project from template also
 ionic start [<project_name>] [<template>] --type=ionic1

example
ionic start myApp tabs --type=ionic1

for more info: https://ionicframework.com/docs/cli/start/

A: You can use the following code for building Ionic version 1 app in Ionic 3 environment
For sidemenu:   ionic start yourappname sidemenu --type ionic1
For tabs:      ionic start yourappname tabs --type ionic1


text:
Q: XAML Progressbar in Powershell I want to have a Progressbar in my Powershell application, which progress is changed during executing the functions. Once one function is ended, I want to move Progressbar a little.
Progressbar is declared in XAML:
<ProgressBar x:Name="ProgressBar"
             HorizontalAlignment="Left"
             Height="20"
             Margin="0,672,0,0"
             VerticalAlignment="Top"
             Width="754" Grid.ColumnSpan="4"/>

Then, I'm trying to change the Progressbar value during event Button_Click:
$ProgressBar.Value = 0

Function1

$ProgressBar.Value = 30

Function2

$ProgressBar.Value = 100

I tried this logic using Write-Progress and it works, also tried with non-xaml .Net Powershel implemented in Powershell - with success. Do I need to use Background Jobs? Or maybe there's another solutions.
Do you have any ideas?

A: Sorry to resurrect an old thread, but this is something that I have been working a lot on lately.  Not exactly sure if this is the case because of the lack of code, but you could try this if your ProgressBar is on a different thread.  It will wait for the dispatcher to have an opening and update the ProgressBar on the UI thread
$ProgressBar.Dispatcher.Invoke([action]{
    $ProgressBar.Value = 30
}, "Normal")

Edit:
Another way to accomplish this task would be using a dispatcherTimer, where you could tell it how often you want the component updated.  This was a resource that helped me understand the basic concept of the DispatcherTimer
https://richardspowershellblog.wordpress.com/2011/07/07/a-powershell-clock/


text:
Q: How to change a specific Character in String using Linq I have a string structure like this:
Exec Test @totalRows = 10 ,@DateCriteria = 'nd',@NDays = -7 ,@GroupIds = '3,4,6,7',@OrderBy =  'DESC'
I am trying to change '3,4,6,7' with any single value like 3 or 45 or 65 etc.
'3,4,6,7' can be n comma separated N numbers like '1,2,3,45,33,111,33'. These are IDs basically. I want to change them with one single value. So my required string will become like:
Exec Test @totalRows = 10 ,@DateCriteria = 'nd',@NDays = -7 ,@GroupIds = '455',@OrderBy =  'DESC'
455 is just an example it can be any integer value.
So far I have tried this without Linq
string[] tempQuery = query.Split(',');

for (int i = 0; i < tempQuery.Length; i++)
{
    if (tempQuery[i].Contains("@GroupIds"))
        myQuery = myQuery + ",@GroupIds = '" + ddlTeams.SelectedValue + "'";
    else
        myQuery = myQuery + "," + tempQuery[i];
}

A: You can easily do this using regex.
Regex.Replace(your string,@"(?<=')(\d,?)+(?=')","455")

I don't know why you are using LINQ for this. But regex more suitable for these purposes.
Edit: Looks like you need only GroupId to be changed. In that case, you can modify the regex pattern like so:
@"(?<=@GroupIds = ')(\d,?)+(?=')"


text:
Q: Bind data to ExpanderViews from coding I am trying to bind data to ExpanderViews from my code behind. But its giving me error and list is blank. only left slider is appeared on the screen.
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll
System.Windows.Data Error: BindingExpression path error: 'groups' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='groups' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'Microsoft.Phone.Controls.ExpanderView' (Name=''); target property is 'ItemsSource' (type 'System.Collections.IEnumerable')..
System.Windows.Data Error: BindingExpression path error: 'title' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='title' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'announcementid' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='announcementid' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Tag' (type 'System.Object')..
System.Windows.Data Error: BindingExpression path error: 'description' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='description' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'groups' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='groups' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'Microsoft.Phone.Controls.ExpanderView' (Name=''); target property is 'ItemsSource' (type 'System.Collections.IEnumerable')..
System.Windows.Data Error: BindingExpression path error: 'title' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='title' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'announcementid' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='announcementid' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Tag' (type 'System.Object')..
System.Windows.Data Error: BindingExpression path error: 'description' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='description' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'groups' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='groups' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'Microsoft.Phone.Controls.ExpanderView' (Name=''); target property is 'ItemsSource' (type 'System.Collections.IEnumerable')..
System.Windows.Data Error: BindingExpression path error: 'title' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='title' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'announcementid' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='announcementid' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Tag' (type 'System.Object')..
System.Windows.Data Error: BindingExpression path error: 'description' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='description' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availfrom' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='availfrom' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availto' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=6587942). BindingExpression: Path='availto' DataItem='MyProj.Model.MessageDTO' (HashCode=6587942); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availfrom' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='availfrom' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availto' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=37880580). BindingExpression: Path='availto' DataItem='MyProj.Model.MessageDTO' (HashCode=37880580); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availfrom' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='availfrom' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'availto' property not found on 'MyProj.Model.MessageDTO' 'MyProj.Model.MessageDTO' (HashCode=48428136). BindingExpression: Path='availto' DataItem='MyProj.Model.MessageDTO' (HashCode=48428136); target element is 'System.Windows.Documents.Run' (Name='null'); target property is 'Text' (type 'System.String')..
I am trying to bind list of MessageDTO type.
Here is my MessageDTO
public class MessageDTO
    {
        public string announcementid;
        public string lmsannouncementid;
        public string title;
        public string description;
        public string availfrom;
        public string availto;
        public string isnew;
        public string lastaccessedon;
    }

and from my code behind, I am doing
public class Alerts
{
                private List<MessageDTO> _messageA;
                public List<MessageDTO> groups;

        private async Task getMessage()
        {

               SQLiteMessageDAO messageDAO = new SQLiteMessageDAO();
                _messageA = await messageDAO.selectMessages(idStr);
                groups = new List<MessageDTO>();

                for (int i = 0; i < _messageA.Count; i++)
                {
                    //(MessageDTO)_messageA[i]
                    MessageDTO messageDTO = new MessageDTO();
                    messageDTO.announcementid = _messageA[i].announcementid;
                    messageDTO.lmsannouncementid = _messageA[i].lmsannouncementid;
                    messageDTO.availfrom = _messageA[i].availfrom;
                    messageDTO.availto = _messageA[i].availto;
                    messageDTO.title = _messageA[i].title;
                    messageDTO.description = _messageA[i].description;
                    messageDTO.isnew = _messageA[i].isnew;
                    groups.Add(messageDTO);
                }

                if (groups != null)
                {
                    listAllAlerts.ItemsSource = groups;
                }
        }
}

Data is present in list. 3 objects are added successfully in groups.
here is my XAML
<ListBox x:Name="listAllAlerts" Margin="8,0">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>

                <toolkit:ExpanderView
                    Margin="0,0,0,8"
                    Header="{Binding }"
                    Expander="{Binding }"
                    ItemsSource="{Binding groups}">

                    <toolkit:ExpanderView.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=title}" TextWrapping="Wrap"
                                       FontFamily="Segoe" Tag="{Binding Path=announcementid}"
                                       FontSize="{StaticResource PhoneFontSizeLarge}" />
                                       <!--Foreground="{Binding Path=isnew, Converter={StaticResource alterColorConvertor}}" /-->
                        </DataTemplate>
                    </toolkit:ExpanderView.HeaderTemplate>

                    <toolkit:ExpanderView.ExpanderTemplate>
                        <DataTemplate>
                            <TextBlock Grid.Row="0" Grid.Column="1"
                                   LineHeight="25" LineStackingStrategy="BlockLineHeight"
                                   TextWrapping="Wrap">
                            <Run Text="{Binding Path=availfrom}"
                                 Foreground="{StaticResource PhoneSubtleBrush}"
                                 FontSize="{StaticResource PhoneFontSizeNormal}"
                                 FontFamily="{StaticResource PhoneFontFamilyNormal}"/>
                            <LineBreak/>
                            <Run Text="{Binding Path=availto}"
                                 Foreground="{StaticResource PhoneSubtleBrush}"
                                 FontSize="{StaticResource PhoneFontSizeNormal}"
                                 FontFamily="{StaticResource PhoneFontFamilyNormal}"/>
                            </TextBlock>
                        </DataTemplate>
                    </toolkit:ExpanderView.ExpanderTemplate>

                    <ListBoxItem>
                        <TextBlock Text="{Binding Path=description}"
                                   TextWrapping="Wrap"
                                   Margin="0,0,0,-2"
                                   FontSize="{StaticResource PhoneFontSizeNormal}"
                                   FontFamily="{StaticResource PhoneFontFamilyNormal}">
                            <!--Foreground="{Binding Path=isnew, Converter={StaticResource colorConvertor}}"-->
                        </TextBlock>
                    </ListBoxItem>
                </toolkit:ExpanderView>

            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

As I have tried same example which is explain here and its working fine, but when I tried with my code its not working. Is I am missing something or I am assigning wrong values, can anyone please guide me?
Thanks in advance.