Q: Executing arbitrary javascript from Android WebView callback/interface I have set up a very simple javascript implementation using Android's WebView:
index.html
<!DOCTYPE html>
<html>
  <head>
  <title></title>
    <script type="text/javascript" charset="utf-8" src="Test.js"></script>
  </head>
</html>

MyJavaScript.java
public class MyJavaScript
{
    public MyJavaScript()
    {
        // create the WebView
        mWebView = new WebView(mContext);

        // enable javaScript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // add javaScript interface
        mWebView.addJavascriptInterface(new JavaScriptTest, "_test");

        // load our dummy page
        mWebView.loadUrl("file:///android_asset/javascript/index.html");
    }

    public void exec(String script)
    {
        mWebView.loadUrl("javascript:" + script);
    }
}

Test.js
function Test()
{
};

Test.prototype.foo = function()
{
    window._test.foo();
};

Test.prototype.bar = function()
{
    window._test.bar();
};

var test = new Test();

JavaScriptTest.java
public class JavaScriptTest
{
    public void foo()
    {
        Log.d("Test", "foo");
    }

    public void bar()
    {
        Log.d("Test", "bar");
    }
}

When a caller calls something like:
MyJavaScript.exec("foo();");

Execution is ultimately propagated to JavaScriptTest.foo().  This execution is in the WebView's worker thread.
What I would like to do in JavaScriptTest.foo(), is something like eval("bar();");.  I basically want to synchronously execute more javascript from the java callback/interface.  That is, I want the javascript bar() method to fully execute before returning to JavaScriptTest.foo().  I can not figure out how to do this.
If I back up one layer, it is trivial to call bar(); from the foo method in Test.js.  However, this doesn't really meet my needs.  I need to be able to execute arbitrary javascript discovered by JavaScriptTest.foo() within JavaScriptTest.foo().
And because JavaScripTest.foo() is executing in the WebView's worker thread, passing the arbitrary javascript discovered by JavaScriptTest.foo() to WebView.loadUrl(...) won't work because you need call that API from the UI thread.
Ideally there would be a way to execute some arbitrary javascript while in the java callback/interface stub which is executing in WebView's worker thread.
I can probably solve the problem by passing the arbitrary javascript back to foo() in Test.js, but it would be a less generic and uglier solution than my first choice.  If my first choice doesn't exist, then I don't have an option.

A: Because of the threading requirements of the WebView, I don't think that you can achieve what you want I'm afraid. The only way to start a new javascript execution in Java from the background thread would be to post a task back to the UI thread, but that break your synchronous needs.
I think your only option is to have the Java object return a String back to your JavaScript and then eval it (as you are suggesting, I think).

A: You could modify your JavaScriptTest interface to return the javascript you want to evaluate.
public class JavaScriptTest
{
    public String foo()
    {
        return "bar();"
    }

    public void bar()
    {
        Log.d("Test", "bar");
    }
}

Then in your javascript:
function Test()
{
};

Test.prototype.foo = function()
{
    eval(window._test.foo());
};

Test.prototype.bar = function()
{
    window._test.bar();
};

var test = new Test();

You wouldn't have bar() evaluated before returning but you could do it immediately afterwards.


Q: mysql: UNION GROUP BY without subquery I have a problem.
I want to wrap a query into a view. For this I have to transform the subqueries inside the FROM. My query is this:
SELECT
    b.id,
    b.summe,
    getBauNrKomplett(b.id) as bauNrKomplett,
    b.parent_id
FROM (
        SELECT
            pt.id,
            pt.parent_id,
            SUM(m.menge*p.preis_kostenanschlag) as summe
        FROM menge m
        join projektposition p ON (m.projektposition_id=p.id)
        join positionstyp pt on (p.positionstyp_id=pt.id)
        GROUP BY pt.id
    UNION
        SELECT
            pt2.id,
            pt2.parent_id,
            null as summe
        FROM positionstyp pt2
    ) b
GROUP BY b.id

I don't find another possility. I need to wrap the UNION statement because of the GROUP BY.
Does someone can imagine another workaround?
Thanks a lot and best regards,
Tobias

A: I beleive this is equal. If not - could you provide sqlfiddle with some data and explanation?
    SELECT
        pt.id,
        pt.parent_id,
        SUM(IF(m.menge IS NULL,0,m.menge*p.preis_kostenanschlag)) as summe,
        getBauNrKomplett(p.id) as bauNrKomplett,
    FROM positionstyp pt
    LEFT JOIN projektposition p
    ON (p.positionstyp_id=pt.id)
    LEFT JOIN menge m
    ON (m.projektposition_id=p.id)
    GROUP BY pt.id


Q: DocuSign Carbon Copy Doesn't Receive Note I'm using DocuSign's API in an iOS application to sign documents. Everything is going fine, except for the Carbon Copy experience.
I have two signers, with routing orders 1 and 2. Then, I have several CC recipients, all with routing order 3.
When the document is signed, the CC recipients receive an email alerting them that the document was signed, but they don't receive the note they should be getting. I know I'm setting this property well: when the CC recipients have a routing order of 1 or 2, they receive an email with the note, and then they receive an email when the document is signed.
How can I get my CC recipients to receive their email at the right point in time, with the note I want them to see?
Here's the log from DocuSign:
POST https://na2.docusign.net:8822/restapi/v2/accounts/6580857/envelopes
Content-Length: 284777
Content-Type: application/json
Connection: keep-alive
Accept: application/json
Accept-Language: en-US; q=1.0
Host: na2.docusign.net
User-Agent: Sales/1.0(iPhone; iOS 9.3.2; Scale/2.00)
X-DocuSign-Authentication: {"Username":"[email1]","Password":"[omitted]","IntegratorKey":"[omitted]"}
X-DocuSign-SDK: Obj-C
X-Forwarded-For: 69.74.21.33
X-SecurityProtocol-Version: TLSv1.2
X-SecurityProtocol-CipherSuite: ECDHE-RSA-AES256-GCM-SHA384

{"status":"sent","documents":[{"documentId":"1","documentBase64":"[omitted]","name":"Test Name"}],"emailSubject":"Subject","emailBlurb":"","recipients":{"signers":[{"email":"[email1]","routingOrder":"1","clientUserId":"1001","tabs":"[omitted]", recipientId":"1","name":"John Doe"},{"note":"This is a note that appears during the signing experience","tabs":"[omitted]","email":"[email2]","clientUserId":"1002","routingOrder":"2","recipientId":"2","name":"Jane Doe"}],"carbonCopies":[{"roleName":"Carbon Copy","routingOrder":"3","email":"[email3]","recipientId":"3","note":"This note does not appear in the email sent to the address.","name":"John Smith"}]}}
201 Created
Content-Type: application/json; charset=utf-8

{
  "envelopeId": "f3421750-6884-4f84-a318-d4637151222c",
  "uri": "/envelopes/f3421750-6884-4f84-a318-d4637151222c",
  "statusDateTime": "2016-07-12T12:51:24.4870000Z",
  "status": "sent"
}

I notice that I'm leaving the email blurb section empty. Could this be a potential solution, or does that field's content get displayed to all parties involved in the signing? In practice, I need to be able to have several different notes for several CC recipients. As far as I know, this can be achieved on DocuSign's website, so I don't see why it couldn't be done through the API.

A: In fact, it seems my problem was caused by a misunderstanding of DocuSign's API. The note field is designed to provide a note that only appears during the signing experience, while the "emailNotification":{"emailSubject":"TEST","emailBody":"TEST"} field is designed to do what I was trying to achieve.


Q: A nil pointer is sent to chan, but a "non-nil" received package main

import (
    "fmt"
    "os/exec"
)

func main() {
    errChan := make(chan error)
    go func() {
        var e *exec.Error = nil
        errChan <- e
    }()
    err := <-errChan
    if err != nil {
        fmt.Printf("err != nil, but err = %v\n", err)
    }
}

The output is weird: err != nil, but err = <nil>
Try it here: http://play.golang.org/p/_iyh0m7O1a

A:
Note: This post is just to have a bit more insight into a potentially confusing problem.
  Using a channel of type error is the idiomatic way to send errors.

Another way around this would be to change the channel signature and explicitly say that is a channel pointer to error instead of a channel of interface errors:
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    errChan := make(chan *exec.Error)
    go func() {
        var e *exec.Error = nil
        errChan <- e
    }()
    err := <-errChan
    if err != nil {
        fmt.Printf("err != nil, but err = %v\n", err)
    } else {
    fmt.Printf("err == nil\n")
    }
}

http://play.golang.org/p/l6Fq8O0wJw

A: The problem lies in that the value passed into the channel as a error interface is not nil, but rather a exec.Error pointer which points to nil.
The program will behave correctly if you change:
go func() {
    var e *exec.Error = nil
    if e == nil {
        errChan <- nil
    }
}()

This is the appropriate way to solve the problem because the idiomatic way to report that no error occurred is by passing a nil error interface.
However, if you want to change the main instead (maybe because you use a third party package which makes the mistake of returning pointers set to nil), you will have to either do a type assertion to the specific type (*exec.Error) and then check if it is nil, or else use the reflect package.
Example using reflect to check for nil:
func IsNil(i interface{}) bool {
    // Check if it is an actual nil-value
    if i == nil {
        return true
    }

    v := reflect.ValueOf(i)
    switch v.Kind() {
        // Only the following kinds can be nil
        case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
        return v.IsNil()
    }

    return false
}

Working example: http://play.golang.org/p/rpG1PVTwwM
You can find a discussion about it here: https://groups.google.com/forum/#!topic/golang-nuts/QzVDKv7p0Vs


Q: Best way to get properties from html and use as global variable in Angular 2+ What is the best way to get properties from html and use as global variable in Angular 2+?
index.html
...
<script>
    window.properties = {
        'variable1': 'string 1',
        'variable2': 'string 2'
    };
</script>
...

A: @Injectable()
class MyGlobalService {
  properties$:Subject = new BehaviorSubject();

  constructor() {
    this.properties.next(window.properties);
  }
}

@NgModule({
  providers: [MyGlobalService],
  ...
 })
 class AppModule()

class MyComponent {
  constructor(private myGlobals:MyGlobalService) {
    myGlobals.properties$.subscribe(val => console.log(val));
  }
}


Q: SQL join on one-to-many relation where none of the many match a given value Say I have two tables
User
-----
id
first_name
last_name

User_Prefs
-----
user_id
pref

Sample data in User_Prefs might be
user_id | pref
  2     |  SMS_NOTIFICATION
  2     |  EMAIL_OPT_OUT
  2     |  PINK_BACKGROUND_ON_FRIDAYS

And some users might have no corresponding rows in User_Prefs.
I need to query for the first name and last name of any user who does NOT have EMAIL_OPT_OUT as one of their (possibly many, possibly none) User_Pref rows.
SELECT DISTINCT u.* from User u
LEFT JOIN User_Prefs up ON (u.id=up.user_id)
WHERE up.pref<>'EMAIL_OPT_OUT'

gets me everyone who has at least one row that isn't "EMAIL_OPT_OUT", which of course is not what I want.  I want everyone with no rows that match "EMAIL_OPT_OUT".
Is there a way to have the join type and the join conditions filter out the rows I want to leave out here?  Or do I need a sub-query?

A: I personally think a "where not exists" type of clause might be easier to read, but here's a query with a join that does the same thing.
select distinct u.* from User u
left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT'
where up.user_id is null

A: Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly.
SELECT * FROM User WHERE EMAIL_OPT_OUT = false


Q: Exception on "add_roles" function for discord.py I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?
Codes there:
@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.message_id == 0000:
        guild: discord.Guild = client.get_guild(payload.guild_id)
        if payload.emoji.name == "someEmoji":
            role0: discord.Role = guild.get_role(1111)
            await payload.member.add_roles(role0)
        elif payload.emoji.name == "someEmoji":
            role1: discord.Role = guild.get_role(2222)
            await payload.member.add_roles(role1)

Logs(With pysnooper):
19:50:26.101973 line        54                 await member.add_roles(role1)
19:50:26.104641 return      54                 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call        54                 await member.add_roles(role1)
19:50:26.590784 exception   54                 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR   ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 54, in on_raw_reaction_remove
    await member.remove_roles(en_role)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
    start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>


Q: Tablelayout with massive data android What is the best way to create a table layout or recyclerview/listview/gridview  in android that can pull a lot of data around 1000 rows and around 50 columns each row without to crash ?
I want to show it like excel sheet nothing special just show data of course with scrolling both ways.

A: TableFixHeaders project on github has an implementation with both Adapter an Recycling of views, plus handles scrolling wery nicely. And is quite easy to modify to suit your needs.

This is not so uncommon request, so it has been done numerous times. I am sure you can find other implementations if this one is not right for you.

A: I saw a similar question on SO a few months ago, and I was interested to see if I could develop a solution.
My concept was to start with a ListView for vertical scrolling and view recycling.  Each list item is a HorizontalScrollView to show a table row with many columns.  The trick here is to listen to each HorizontalScrollView for swipe events and then scroll every HorizontalScrollView in sync with the view being swiped.
I have a proof-of-concept project on Github here:
 klarson2/android-table-test
Downsides: The project was set up for Eclipse, so you can't open it directly with Android Studio.  There is still a small bug with event handling that I haven't got around to fixing.  Another limitation is that each cell view in the horizontal LinearLayout must be a fixed size so that the columns will line up correctly.
However, the example uses a 4MB .csv file with 50 columns and over 10,000 rows for a data source proving that it is possible to display an enormous table in an Android app with responsive two-way scrolling.


Q: How to get a page not redirect to the main I'm absolute beginner at JSP and Spring framework and annotations. I've built a standard CRUD application, but have one issue. Whenever i want add, edit or delete a user, application redirects me to main "user" page, if i'm on a page, with an index more than 1. How can i make it stay still on a page, where i do all actions above?
For example, when i want to edit "Tom Hanks"(14, page number 2)
It redirects me to the 1st page
But i want it to be still on the same page, where i add, edit or delete
UserController class is below
@Controller
public class UserController
{
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService)
    {
        this.userService = userService;
    }

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public String listUsers(@RequestParam(value="page", required = false) Long page, Model model) {
        if (null == page)
            page = 1L;
        model.addAttribute("user", new User());
        model.addAttribute("searcheduser", new User());
        model.addAttribute("listUsers", userService.getUsers(page));
        model.addAttribute("page", page);

        return "users";
    }

    @RequestMapping(value = "/users/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user") User user) {
        if(user.getId() == 0)
        userService.addUser(user);
        else
            {
                userService.updateUser(user);
            }
        return "redirect:/users";
    }

    @RequestMapping("/remove/{id}")
    public String removeUser(@PathVariable("id") int id)
    {
        userService.removeUser(id);
        return "redirect:/users";
    }

    @RequestMapping("edit/{id}")
    public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) {
        if (null == page) page = 1L;
        model.addAttribute("user", userService.getUser(id));
        model.addAttribute("searcheduser", new User());
        model.addAttribute("listUsers", userService.getUsers(page));
        model.addAttribute("page", page);

        return "users";
    }

    @RequestMapping("userdata/{id}")
    public String userData(@PathVariable("id") int id, Model model) {
        model.addAttribute("user", userService.getUser(id));

        return "userdata";
    }

    @RequestMapping(value="searchresults", method = RequestMethod.POST)
    public String searchResults(@ModelAttribute("searcheduser") User user, Model model) {
        List<User> searchResult = userService.getUsers(user.getName());
        model.addAttribute("listUsers", searchResult);

        return "searchresults";
    }
}

A: Add the page as a parameter on redirect for remove and edit :
@RequestMapping("edit/{id}")
public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) {
    if (null == page) page = 1L;
    model.addAttribute("user", userService.getUser(id));
    model.addAttribute("searcheduser", new User());
    model.addAttribute("listUsers", userService.getUsers(page));
    model.addAttribute("page", page);

    return "redirect:/users?page="+page;
}

The same for remove .


Q: How to save a file name in my DB when I download or add a file into my local machine download folder in Laravel. any idea for this thing I want to save a file name into DB when it is downloaded or added into my local system folder.How can I perform this logic. any idea..... thanks for advance

A: you could just use the php function glob() to get all filenames from the download directory. then setup a cronjob for every 5m or whatever interval you want where you save the names to your database.


Q: date format is not working monthpicker I have a month picker in my form in laravel 4.2. While changing the month, the month and year are shown like 05/2015. But i need it to be in the format May, 2015.
{{ HTML::style('public/asset/css/smoothness/jquery-ui.css') }}
{{ HTML::style('public/asset/css/MonthPicker.css') }}
{{ HTML::script('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js') }}
{{ HTML::script('http://code.jquery.com/ui/1.10.2/jquery-ui.js') }}
{{ HTML::script('public/asset/js/MonthPicker.min.js') }}
{{ HTML::script('public/asset/js/MonthPicker.js') }}
Query(document).ready(function() {
$("#SearchVal").val('');

var currentYear = (new Date).getFullYear();

var _picker = jQuery('#SearchVal').MonthPicker({

    ShowIcon: false

            });

A: You can do that manually on change event :
var monthsLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

var picker = jQuery('#SearchVal').MonthPicker({
    ShowIcon: false,
    OnAfterChooseMonth: function(){
        var elts = picker.val().split('/');
        picker.val(monthsLabels[parseInt(elts[0])-1]+', '+elts[1]);
    }
});

jsFiddle

A: hello bro try to see this will help you it's about Datepicker


Q: Google Apps Script: Server error occurs when using a UiApp and a server handler in new sheets AND there is a library I converted my sheets from the old to the new sheets as the code started creating sheets in the new version which was causing it to fail. After converting, I am now getting another error which I cannot find a solution for.
The error seems to be when using UiApp which calls a server handler and there is a library attached to the project. The error occurs even when there is no code in the library. The error occurring is:
Server Error: We're sorry, a server error occurred. Please wait a bit and try again.
Steps to reproduce
(1). Create 2 new sheets, use one as the library and one as the test sheet
(2). In the library, add a new version to the project then add the project as a library in the test sheet. There should be no code in the library (doesn't really matter either way).
(3). In the test sheet, add the following code:
function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication();

  // create a button and handler
  var buttonHandler = app.createServerHandler("buttonTest");
  var button = app.createButton("Button Test");
  button.addClickHandler(buttonHandler)

  app.add(button)
  ss.show(app); // Display the app
}
function buttonTest(e) {
  // nothing here is executed
}

(4). Run the test code
The following error is displayed:
Server Error: We're sorry, a server error occurred. Please wait a bit and try again.
If the library is removed then it will run as expected

A: The UiApp is deprecated. That would be creating the server error. Sometimes the UiApp functions still work (like the chart service) but the output crashes. The googlescript library functionality should still work.
https://developers.google.com/apps-script/reference/ui/ui-app?hl=en
The html service should be a replacement for the UiApp but unfortunately it does not cover all the same functionality.
https://developers.google.com/apps-script/guides/html/


Q: How to split/cut till specific path (directory path )of string in perl Input : "/abcd/prod/Cid/1234/Did" or "/abcd/prod/Cid/1234/Did/Pid/234"
Output: "/abcd/prod/Cid/1234/"  (Only till 4th word, considering '/' is the delimiter)
How to slice and get above using perl

A: As one-liner :
$ perl -F'/' -lane 'print join "/", @{F[0..4]}' <<< "/abcd/prod/Cid/1234/Did"

As a script :
while (<>) {
    chomp $_;
    my @F = split(m[/], $_, 0);
    print join('/', @F[0..4]), "\n";
}

 Output :
/abcd/prod/Cid/1234


Q: Subscripting a string in Javascript I have a data in the object section_data.title and i am trying to use str.sup() where str=section_data.title; and str holds following data:

str="Not less than 30 net ft2 (2.8 net m2) per patient in a
  hospital or nursing    home, or not less than 15 net ft2 (1.4 net
  m2) per resident in a limited care facility, shall be provided within the aggregated area of corridors, patient rooms, treatment
  rooms, lounge or dining areas, and other similar areas on each side of
  the horizontal exit. On stories not housing bed or litterborne
  patients, not less than 6 net ft2 (0.56 net m2) per occupant
  shall be provided on each side of the horizontal exit for the total
  number of occupants in adjoining compartments."

Now I want to add superscript for the bold words indicated above (e.g ft2). How can I do this using str.sup() or are there any other alternative method to do so in javascript? Or any other tricks?

A: String in javascript is not formatted. You can only do that when you output to HTML. So basically you must write it like this
var str = "Not less than 30 net ft2 (2.8 net m2)";
document.write(str);

You can do a find and replace for all string contain ft2 and m2 turn them into ft2 and m2
str.replace(/ft2/g,"ft2");  //But it not safe...


Q: how to apply constraint by Stored procedures that ID should start with 'E' and has 2 numerics aftarwards? EID should only be inserted if it starts with 'E' and has 2 numerics aftarwards ....
i was trying to write a procedure for the purpose like:
create proc emp_checks(@eid varchar(20), @name varchar(20),@age int, @salary int, @city varchar(20))
AS
Begin
Declare @citycount int= (select count(*) from employee where @city=city)

if (@citycount < 2 and @eid like 'E--%')
insert into employee values(@eid,@name,@age,@salary,@city)
else
print 'city exceeded'
End

here the issue is that -- or spaces would insert non-numerics also
here this code also includes few extras *just homework things :)

A: Why would you write a stored procedure?  MySQL now supports check constraints:
alter table employee add constraint chk_employee_eid
    check (eid regexp '^E[0-9]{2}')

Note that this allows anything after the first 3 characters.  If you don't want anything, then add $ to the pattern:
alter table employee add constraint chk_employee_eid
    check (eid regexp '^E[0-9]{2}$')


Q: TCP messages - Durable and fast solution tips? We use Spring integration for TCP socket communication with the hardware.
The client would be sending a sequence number to uniquely identify a message.
My requirement is to store these sequence numbers part of the socket message and validate them for non repetitive sequence numbers.
I went thru IdempotentReceiver, sounds like what i wanted.
But I need a durable and faster mechanism to store it, before unexpected shutdown of service and use the in memory cache for retrieving the latest sequence number.
Thank you in advance.!

A: You can use PropertiesPersistingMetadataStore for idempotent receiver:

The PropertiesPersistingMetadataStore is backed by a properties file and a PropertiesPersister.
By default, it only persists the state when the application context is closed normally. It implements Flushable so you can persist the state at will, be invoking flush().

See more in its JavaDocs.


Q: Contentflow auto resize not working Im using:
Contentflow 1.0.2
jquery 1.6.1
I'm trying use Contentflow using reflection and with maximum width/height so it covers all the screen without any scroll bar vertically or horizontally.
This example shows exactly what I wanna do, but it uses ImageFlow (another plugin)
http://themes.themegoods.com/keres_wp/?page_id=459
At this point my config is like this and everything works fine except that Contentflow doesn't resize when I change the browser size.
var cf = new ContentFlow('contentFlow', {
                    reflectionColor: "#000000",
                    circularFlow: false,
                    startItem: 0,
                    fixItemSize: true,
                    scaleFactor:1.5
                });


Q: Numba and KeyboardInterrupt Exception conflict I'm having a problem compiling KeyboardInterrupt exception using Continuum Numba module. Here's my data acquisition code:
@jit
def lockinmeasurement(x):
    Measurement=np.empty((0,5))
    XMeas=np.empty((0,2))
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path_to_watch, recursive=True)
    observer.start()
    try:
       while x:
           SQData=pd.read_csv(path_to_watch,sep=',',skiprows=14)
           Temp=SQData['Temperature (K)']
           Field=SQData['Field (Oe)']
           XMeas=np.append(XMeas,[[time.clock(),lockin.x]],axis=0)
           Measurement=np.append(Measurement,[[a,b,c,d,e]])
           p1.plot(XMeas,clear=True,label='Lockin X',pen='y')
           pg.QtGui.QApplication.processEvents()
           rd=pd.DataFrame(Measurement)
           rd.to_csv('fileout.csv',sep='\t',index=False)
           time.sleep(0.2)
    except KeyboardInterrupt:
       print('interrupted!')

lockinmeasurement(True)

The code compiles perfectly fine without '@jit', however when I'm trying to use numba it returns an error:
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 231, in next
    info = BYTECODE_TABLE[opcode]
KeyError: 121

During handling of the above exception, another exception occurred:

lockinmeasurement(True)

  File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 165, in _compile_for_args
    return self.compile(sig)

  File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 303, in compile
    flags=flags, locals=self.locals)

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 595, in compile_extra
    return pipeline.compile_extra(func)

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 316, in compile_extra
    raise e

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 311, in compile_extra

    bc = self.extract_bytecode(func)
  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 303, in extract_bytecode

    bc = bytecode.ByteCode(func=self.func)

  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 333, in __init__
    table = utils.SortedMap(ByteCodeIter(code))

  File "C:\Anaconda3\lib\site-packages\numba\utils.py", line 109, in __init__
    for i, (k, v) in enumerate(sorted(seq)):

  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 235, in next
    raise NotImplementedError(ts % tv)

NotImplementedError: offset=80 opcode=0x79 opname=SETUP_EXCEPT

Is there any way I can overcome this issue ?

A: Thanks to Travis' innovation teams' efforts numba is a great and powerful tool for scientific computing. One shall however take a due care to use it where feasible and where jit-compilation can bring some fruit to our hard and fast lives.
Numba Documentation states this explicitly, saying:

2.4.1.1. Constructs
  Numba strives to support as much of the Python language as possible, but some language features are not available inside Numba-compiled functions:- Function definition-
  Class definition-
  Exception handling (try .. except, try .. finally)-
  Context management (the with statement)-
  Comprehensions (either list, dict, set or generator comprehensions)-
  Generator delegation (yield from)
  The raise statement is supported in several forms:
raise (to re-raise the current exception)
raise SomeException
raise SomeException(<arguments>): in nopython mode, constructor arguments must be compile-time constants
  Similarly, the assert statement is supported with or without an error message.


Q: Material sidenav causing problem with translate and flex css properties So, currently working with my electron app having a sidenav structure like this:

<mat-drawer-container>
  <mat-drawer>parent sidenav</mat-drawer>

  <mat-drawer-content>
    parent content
    <mat-drawer-container>
      inside child container
      <mat-drawer>inside child sidenav</mat-drawer>
      <mat-drawer-content>
        inside child content
        <app-route>current problem occurs here</app-route>
      </mat-drawer-content>
    </mat-drawer-container>
  </mat-drawer-content>

</mat-drawer-container>

So, suppose at first route I'm having Html like this:

info

Nothing to show you here as your specified folders for checking music files are currently empty

Add new music search directories

Also scss:

@mixin widthheight100{
   width: 100%;
   height: 100%
}

.box-empty-container{
      position: relative;
      @include widthheight100() ;

      .box-empty-msg{
         position: absolute ;
         left: 50% ;
         top: 45% ;
         transform: translate(-50%, -50%);
         text-align: center;
       .box-empty-logo{
            span.material-icons{
               font-size: 2.5rem;
            }
       }

       .box-empty-title{
            font-family: 'jost-bold';
            font-size: 12pt;
       }

       .box-empty-subtitle{
            font-family: 'jost-regular';
            font-size: 10pt;
       }
}

I have tried to centralize div.box-empty-msg with both flex and translate method in scss and they are still not at center. When page loads this div is at center but when i open & close the sidenav it's position gets displaced form center. How can I solve this problem ?
Edit: Currently changed the scss style to postion: absolute strategy. Link here for similar code in stackblitz. It seems to work fine in stackblitz but in my actual project when screen size is large or medium the div.box-empty-msg is actually shifted some distance away from center. Also I think somehow in my project the sidenav is pushing the div tag away from center.

A: @ReneVanDerLende After thoroughly checking my project due to css properties set for mat-drawer-content as { width: 100% ; height: 100% } it interfered with the styles of box-empty-container, hence shifting that slightly towards right.


Q: Variable assigned in dispatch block coming back null I'm trying to make a network call run in a background thread so it doesn't freeze my app while it's waiting.
The call happens when I do:
nextTime = [myObj getNextTime];

I do an NSLog as soon as I get it, and that one works.
However, when I'm outside of the dispatch block, the same
NSLog prints out null.
myObj *current = ((myObj *)sortedArray[i]);
__block NSString *nextTime;
dispatch_queue_t queue =     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
    nextTime = [myObj getNextTime];
    NSLog(@"inside%@",nextTime);
    dispatch_sync(dispatch_get_main_queue(), ^{

    });
});

NSLog(@"outside%@",nextTime);

Any ideas why the outer log is printing null? Am I doing something horribly wrong and I just missed it? Thanks!

A: That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable.
From the GCD docs on dispatch_async():

This function is the fundamental mechanism for submitting blocks to a
  dispatch queue. Calls to this function always return immediately after
  the block has been submitted and never wait for the block to be
  invoked. The target queue determines whether the block is invoked
  serially or concurrently with respect to other blocks submitted to
  that same queue. Independent serial queues are processed concurrently
  with respect to each other.

A: Your "outside" NSLog statement should actually go in that inner dispatch_async block that is set to run on the main thread, because that block will execute after you've set the value of nextTime. Any code you place below your asynchronous block call will likely execute way before the code inside the block.


Q: Trying to remove duplicates from large list of objects, keep certain one I have a large list of objects in Python that I'm storing in a text file (for lack of knowledge of how to use any other database for the present).
Currently there are 40,000 but I expect the list length eventually may exceed 1,000,000. I'm trying to remove duplicates, where duplicates are defined as different objects having the same value for a text string attribute, but keep the most recent version of that object (defined as having the highest value in another attribute).
What I want to make is a function that returns only objects 2 and 3 from the following list, reliably:
Object 1: text="hello"            ID=1
Object 2: text="hello"            ID=2
Object 3: text="something else"   ID=3

Doing this manually (looping through the list each time for each object) is too slow already and will get slower with O(l^2), so I need a smarter way to do it. I have seen hashing the objects and using the set function recommended multiple times, but I have two questions about this that I haven't found satisfactory answers to:

*

*How does hashing improve the efficiency to the degree it does?

*How can I do this and retain only the most recent such object? The examples I have seen all use the set function and I'm not sure how that would return only the most recent one.
EDIT: I can probably find good answers to question 1 elsewhere, but I am still stuck on question 2. To take another stab at explaining it, hashing the objects above on their text and using the set function will return a set where the objects chosen from duplicates are randomly chosen from each group of duplicates (e.g., above, either a set of (Object 2, Object 3) or (Object 1, Object 3) could be returned; I need (Object 2, Object 3)).

A: change to using a database ...
import sqlite3
db = sqlite3.connect("my.db")
db.execute("CREATE TABLE IF NOT EXISTS my_items (text PRIMARY KEY, id INTEGER);")
my_list_of_items = [("test",1),("test",2),("asdasd",3)]
db.execute_many("INSERT OR REPLACE INTO my_items (text,id) VALUES (?,?)",my_list_of_items)
db.commit()

print(db.execute("SELECT * FROM my_items").fetchall())

this may have maginally higher overhead in terms of time ... but you will save in RAM

A: Hashing is a well-researched subject in Computer Science. One of the standard uses is for implementing what Python calls a dictionary. (Perl calls the same thing a hash, for some reason. ;-) )
The idea is that for some key, such as a string, you can compute a simple numeric function - the hash value - and use that number as a quick way to look up the associated value stored in the dictionary.
Python has the built-in function hash() that returns the standard computation of this value. It also supports the __hash__() function, for objects that wish to compute their own hash value.
In a "normal" scenario, one way to determine if you have seen a field value before would be to use the field value as part of a dictionary. For example, you might stored a dictionary that maps the field in question to the entire record, or a list of records that all share the same field value.
In your case, your data is too big (according to you), so that would be a bad idea. Instead, you might try something like this:
seen_before = {}    # Empty dictionary to start with.

while ... something :
    info = read_next_record()   # You figure this out.
    fld = info.fields[some_field]  # The value you care about

    hv = hash(fld)     # Compute hash value for field.

    if hv in seen_before:
        print("This field value has been seen before")

    else:
        seen_before[hv] = True  # Never seen ... until NOW!

A: Could use a dict with the text as key and the newest object for each key as value.
Setting up some demo data:
>>> from collections import namedtuple
>>> Object = namedtuple('Object', 'text ID')
>>> objects = Object('foo', 1), Object('foo', 2), Object('bar', 4), Object('bar', 3)

Solution:
>>> unique = {}
>>> for obj in objects:
        if obj.text not in unique or obj.ID > unique[obj.text].ID:
            unique[obj.text] = obj

>>> unique.values()
[Object(text='foo', ID=2), Object(text='bar', ID=4)]


Q: How to run the backend server/code in re-frame template? Using lein re-frame template I see that there's a -main function that runs a jetty server for the backend code located in clj/. Using emacs I've been able to cider-jack-in-cljs and get the frontend running in the browser, hot reload works and all but I've tried to add routes to the routes function in handler.clj inside the clj/ and haven't been able to figure out how to get that "backend side" of things to work.

I found this other question sort of related but in that case the user just wanted to know why the clj/ folder was there, not how to run that code. I haven't been able to find any documentation so far, any help is greatly appreciated.
PD: I know that having the backend and frontend in the same project/repo is not recommended (it's mentioned in the other question I linked above) but I just want to get a simple "first app" working and running first and then hopefully get the backend out into another project/repo.

A: Assuming you created the project with something like lein new re-frame myapp +handler the code to start the server is on the file src/clj/myapp/server.clj
You can open the file and run cider-jack-in-clj, which will ask if you want to launch lein or shadow-cljs. Since it's a CLJ file, choose lein. Once CIDER starts, you can evaluate the -main function (eg. (-main)) to start the server.
You can open the URL at http://localhost:3000 and Jetty will serve the resources that are already compiled by shadow-cljs, so you'll see the same output as viewing the other port from CLJS directly.
Note that the backend code from the template starts the Jetty server but won't help with reloading the backend. To see how enable hot reloading for the backend, check https://github.com/ring-clojure/ring/wiki/Setup-for-development


Q: Bamboo Failing To Run Task - Null Pointer Exception I have had a set of Bamboo plans running for quite awhile but this morning Bamboo has decided to start throwing an exception when running them.  The instance of Bamboo is on Linux but the plans themselves are ran from a remote agent running Windows.  Specifically these are plans set to build .net framework mvc applications.
The plans fail at different tasks but both with the same error.  The error below fails while trying to restore nuget packages but another plan fails while attempting to run a copy command.  Running the nuget restore outside of Bamboo runs correctly.
I have tried cloning the plan and also reinstalled the remote agent but neither fixed the issue.
Error occurred while running Task 'Nuget(8)' of type com.atlassian.bamboo.plugins.scripttask:task.builder.command.
error   12-Aug-2020 09:40:17    com.atlassian.bamboo.task.TaskException: Failed to execute task
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:65)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:39)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.lambda$executeTasks$3(TaskExecutorImpl.java:288)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.executeTaskWithPrePostActions(TaskExecutorImpl.java:221)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.executeTasks(TaskExecutorImpl.java:288)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.execute(TaskExecutorImpl.java:110)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.build.pipeline.tasks.ExecuteBuildTask.call(ExecuteBuildTask.java:71)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.executeBuildPhase(DefaultBuildAgent.java:203)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.build(DefaultBuildAgent.java:175)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.lambda$waitAndPerformBuild$0(BuildAgentControllerImpl.java:122)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.variable.CustomVariableContextImpl.withVariableSubstitutor(CustomVariableContextImpl.java:185)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.waitAndPerformBuild(BuildAgentControllerImpl.java:117)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent$1.run(DefaultBuildAgent.java:126)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.utils.BambooRunnables$1.run(BambooRunnables.java:48)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper.runWith(ImpersonationHelper.java:26)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper.runWithSystemAuthority(ImpersonationHelper.java:17)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper$1.run(ImpersonationHelper.java:41)
error   12-Aug-2020 09:40:17        at java.lang.Thread.run(Thread.java:748)
error   12-Aug-2020 09:40:17    Caused by: java.lang.NullPointerException
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ExternalProcessBuilder.lambda$env$0(ExternalProcessBuilder.java:78)
error   12-Aug-2020 09:40:17        at com.google.common.base.Predicates$CompositionPredicate.apply(Predicates.java:552)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Iterators$7.computeNext(Iterators.java:652)
error   12-Aug-2020 09:40:17        at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143)
error   12-Aug-2020 09:40:17        at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:138)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Iterators.size(Iterators.java:191)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Collections2$FilteredCollection.size(Collections2.java:211)
error   12-Aug-2020 09:40:17        at java.util.AbstractMap.size(AbstractMap.java:85)
error   12-Aug-2020 09:40:17        at java.util.HashMap.putMapEntries(HashMap.java:501)
error   12-Aug-2020 09:40:17        at java.util.HashMap.putAll(HashMap.java:785)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ExternalProcessBuilder.env(ExternalProcessBuilder.java:78)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.createExternalProcess(ProcessServiceImpl.java:144)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:195)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:210)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:48)
error   12-Aug-2020 09:40:17        ... 17 more

A: I talked with Atlassian support and they helped me work through the issue.  I had setup the remote agent as a windows service which was causing the problems.  I removed the service and started the remote agent via the BambooAgent.bat script.  Mine was located at %InstallDirectory%/bin/BambooAgent.bat


Q: Asp.net WebApi multipart/form-data with id from route definition I'm sending a multipart/form-data request to an action (file upload), but I'm sending it to an action that has the id in the url as specified by the route:
routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}/{action}",
    defaults: new {action = "Index", id = RouteParameter.Optional }
);

Url I'm posting to: /api/Contacts/1/Photo
Action:
[HttpPost]
public HttpResponseMessage Photo(int id)
{

    var task = this.Request.Content.ReadAsStreamAsync();
    task.Wait();
    Stream requestStream = task.Result;

    /* ... */

}

With the id parameter, I get this error: No 'MediaTypeFormatter' is available to read an object of type 'Int32' with the media type 'multipart/form-data'. Without the id parameter, it works fine.
I tried a MediaTypeFormatter in this answer here, but it doesn't seem to get the id from the url and crashes when trying to get it using FirstDispositionNameOrDefault("id"). Is there a way to get the id specified in the route url to bind to the id parameter for the action?

A: FirstDispositionNameOrDefault is for reading the values of form controls.
You can use the [FromUri] attribute on the parameter:
public HttpResponseMessage Photo([FromUri] int id)

This tells Web API not to get the parameter from the message body.


Q: how to display data from json with looping javascript? This is my json code structure
This is my javascript:
$('#kurir').change(function(){
var kurirID = $(this).val();
if(kurirID){
    $.ajax({
       type:"GET",
       url:"{{url('checkout/kurir')}}?kurir_id="+kurirID,
       success:function(res){
        if(res){
            $("#ongkir").prop('disabled', false);
            $("#ongkir").empty();
            $("#ongkir").append('<option>--- Pilih Kurir ---</option>'); $.each(res,function(key,value){ $("#ongkir").append('<option value="'+key['service']+'">'+this.value['service']+'</option>'); }); }else{ $("#ongkir").empty();
        }
       }
    });
}else{
     $("#ongkir").prop('disabled', true);
    $("#ongkir").empty();
    $("#ongkir").append('<option>--- Pilih Kurir ---</option>');
}});

This is my controller
public function getKurirList(Request $request)
{$data = RajaOngkir::Cost(['origin'=> 419,'destination'=> 114,'weight'=> 1700,'courier'=> 'jne',])->get(); return response()->json($data); }

I want to show all "service" data and price "value".
How to iterate this json with a 'each' loop and print the data?
Can anyone help me?

A: You should iterate over  $datas['0']['costs']
foreach ($datas['0']['costs'] as $key =$value){

  echo $value['service'] . ' - ' $value['cost'][0]['value'];

}


Q: How to use Google Cloud PubSub with Proxy? I'm working with an application that interacts with Google Cloud PubSub. It works fine in normal scenario but I want to enable proxy support so I was going through Publisher.Builder and Subscriber classes and their APIs to see if there are any APIs available to enable proxy support. I managed to find only the setChannelProvider but I'm not sure whether that will work or not.
The following code snippet is what I'm thinking of using but that doesn't seem to work.
ManagedChannel channel = ManagedChannelBuilder.forAddress(proxyHost, proxyPort).build();
TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
publisherBuilder.setChannelProvider(channelProvider);

I wasn't able to successfully publish or pull messages to the cloud service. I get the following error:
java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 9978300322ns

So I wanted to know does the PubSub service support proxy through APIs or does it only support the proxy setting i.e. host and port to be provided in the environment path only.

A: You can specify the proxyHost/port directly using JVM args https.proxyHost, https.proxyPort
mvn clean install -Dhttps.proxyHost=localhost -Dhttps.proxyPort=3128  exec:java

then just directly create a client of your choice
TopicAdminSettings topicAdminSettings =   TopicAdminSettings.newBuilder().build();
TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings);

FYI- Setting ManagedChannelBuilder.forAddress() here overrides the final target for pubsub (which should be pubsub.googleapis.com 443 (not the proxy)
Here is a medium post i put together as well as a gist specificlly for pubsub and pubsub+proxy that requires basic auth headers

*

*
finally, just note, its https.proxyHost even if you're using httpProxy, ref grpc#9561

A: Proxy authentication via HTTP is not supported by Google Pub/Sub, but it can be configured by using GRPC_PROXY_EXP environment variable.
I found the same error that you got here (that's why I assume you are using HTTP) and it got fixed by using what I said.

A: You need to set JVM args:  https.proxyHost, https.proxyPort
for proxy authentication an additional configration is needed before any client creation:
 Authenticator.setDefault(new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return
                                    new PasswordAuthentication(proxyUsername,proxyPassword).toCharArray());
                        }


Q: Is there a way to loop backwards after finding a certain line in a txt doc? I am working with using excel data to edit parts of large txt files. Some of these edits require deleting certain sections, and other require copying, pasting, and slightly editing these sections.
For example, the txt doc takes this basic form:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 3
Monitor 4
Monitor 5
Item3 Item4
End

Monitor 6
Item4 Item5
End

Say I am needing to delete the second block (that is, delete from after the first end to the line before monitor 6). I am able to find the block using lookups for Item3 and Item4. Is there a way to assign this block to a variable?
with open(longStr1) as old_file:
    lines = old_file.readlines()
    with open(endfile1, "w") as new_file:
        for line in lines:
            if "Item3 Item4" in line:
                #block = from previous End to after next End
                lines.remove(block)
            new_file.write(line)

So ideally, this would allow me to delete the entire block of text to make the txt file then look like this:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 6
Item4 Item5
End

How can I define this block using python?

A: Iterative approach:
search_item = "Item3 Item4"

with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
    block = ''
    for line in f_in:
        if block:
            block += line
            if line.strip() == 'End':
                if search_item not in block: f_out.write(block + '\n')
                block = ''
        elif line.startswith('Monitor'):
            block = line

output.txt contents:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 6
Item4 Item5
End

A: You could accumulate the lines to write in a separate string that corresponds to the content of one block. Wait until you reach the end of the block ("end" line) before writing the accumulated lines.  If along the way, you find the text pattern that indicates suppression of the block, set a flag that will prevent writing to the file when the end is reached.
For example (not tested):
with open(longStr1) as old_file:
    lines = old_file.readlines()
    lineBlock = ""
    excluded  = False
    with open(endfile1, "w") as new_file:
        for line in lines:
            lineBlock += line
            if line == "End":
                if not excluded:
                    new_file.write(lineBlock)
                lineBlock = ""
                excluded  = False
            if "Item3 Item4" in line:
                excluded  = True


Q: How to query the print queue on Windows We are developing a critical application and need to have the finest control over the documents printed.  To be sure on which documents are printed or not we want to check the printer queue.
How can we query the print queue on Windows (status, queue list, errors, ...)?

A: EnumPrinters to get the list of printers, EnumJobs to get a list of jobs for that printer. GetJob to get info on a specific job and SetJob to change the settings for that job (pause or cancel it).
See more in the Printing and Print Spooler References.
.NET has the PrintQueue and PrintServer classes.

A: Following URLs may be of interest to you,
http://www.codeproject.com/KB/printing/printwatchvbnet.aspx
and
http://www.codeproject.com/KB/printing/EMFSpoolViewer.aspx


Q: Method chaining to communicate between GUI parts in a MVC in Java I am creating a Java Desktop GUI application using the MVC pattern. For the sake of simplicity, I have divided in GUI application into different panels (Scheme of the GUI application) so that each class takes care of something specific. Now, when I am in the Controller part and want to display something in the DRAW PANEL, I have a method chaining. I mean I am calling several methods in a row:
view.getRightPanel().getDrawPanel().appendText(model.getResults());

I am wondering whether or not I am making a mistake somewhere. Is it normal to do so, or should I change my code to make it more efficient and elegant?
Any information is welcome! Thank you!

A: You are not making a mistake if you are doing this in the controller.
In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here,
view.getRightPanel().getDrawPanel().appendText(model.getResults());

I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do.
Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC.
I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable.


Q: How can I fix: "start-stop-daemon: warning: this system is not able to track process names" when starting springboot as a systemd service? When I start my spring boot app as a systemd service I receive this error:
start-stop-daemon: warning: this system is not able to track process names longer than 15 characters, please use --exec instead of --name.
Spring boot seems to build the process name from the jar name and the directory the jar is contained in.  Is there any way to fix this aside from renaming the jar, and the directory it's contained in, to be shorter than 15 characters?
If I try to edit spring boots startup script to use --exec instead of --name then I get another error:
'start-stop-daemon: unable to stat /opt/program/programname_optprogramname (No such file or directory)

A: It appears that this issue is fixed in Spring boot 2.0.2.  So if you run into this issue upgrading might fix it (not to imply that upgrading is always a simple effort)


Q: Need help aligning my textfields with my radio buttons how it looks like right now

i' m placing all my inputs on the right with float: right; in my css file.
But i'm wondering if there is a way to align my radios
to the left side of my text fields?
so they all align under each other on the left side.

A: I would strongly advocate using the more sophisticated, flexible solution even with great browsers support, the flexbox. You could have used align-self to align specify elements along with default alignment to sibling elements. If you did not know about flexbox, It's worth learning right now.


Q: store time from stopwatch Javascript in MySQL database I am using a javascript to start and stop a timer (stopwatch).
What I want is that when the user press the stop button, the data (the time at that moment) will be stored in my MySQL database. Is that possible? And if yes, what do I need to add as code? (I'm just a starter with PHP, if someone can add a small explanation then that would be great so I can learn from it)
The following script is my working javascript code:
var clsStopwatch = function () {

var startAt = 0;
var lapTime = 0;

var now = function () {
    return (new Date()).getTime();
};

this.start = function () {
    startAt = startAt ? startAt : now();
};

this.stop = function () {
    lapTime = startAt ? lapTime + now() - startAt : lapTime;
    startAt = 0;
};

this.time = function () {
    return lapTime + (startAt ? now() - startAt : 0);
};
};

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}

function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';

m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;

newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}

function show() {
$time = document.getElementById('time');
update();
}

function update() {
$time.innerHTML = formatTime(x.time());
}

function start() {
clocktimer = setInterval("update()", 1);
x.start();
}

function stop() {
x.stop();
clearInterval(clocktimer);
}

The next is my PHP code that I use to store data in my database, it's on a separate page.
define('DB_NAME', 'dbname');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) { die('could not connect: ' . mysql_error()); }

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) { die('can not use ' . DB_NAME . ': ' . mysql_error()); }

$sql="INSERT INTO game (name, company, email, time) VALUES
    ('".$_POST['name']."','".$_POST['company']."','".$_POST['email']."','".$_POST['time']."')";

if (!mysql_query($sql)) { die('Error: ' . mysql_error()); }

mysql_close();

and my HTML submit form:

<form action="highscore.php" method="post"/>

name:

<input type="text" name="name"/>

company:

<input type="text" name="company"/>

email:

<input type="text" name="email"/>

Time:

<input type="button" value="start" onclick="start();">
<input type="submit" value="stop" onclick="stop();">

</form>

Maybe a solution could be to post the data in a hidden input field but still i'm struggling to get that one working.

A: Try this:
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}

On your form:
<input type="hidden" value="" id="counter" name="counter" />

A: Use MySQLi instead of MySQL, because there's some serious security problems with MySQL


Q: How to setup static page with css in subdirectory in rails public directory I'm trying to setup jekyll blog in my public/blog directory.
For this question let say I just want to have public/blog directory with index.html and css/site.css with css for this page.
I'm deploying it using capistrano, so I added public/blog to linked_dirs
index.html:

    <link rel="stylesheet" type="text/css" href="css/site.css">

Hello World

css/site.css:
h1 {
  color: red;
}

Now after cap production deploy I can visit domain.com/blog and see Hello World header, but it does not load css file.
I get Failed to load resource: the server responded with a status of 404 (Not Found) error.
Do you know how can I make it work?

A: It was more a nginx question.
I added this to my site nginx file:
  location ^~ /blog/css/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }


Q: Can a number be Romanised this way? I know there are a few different ways to Romanise a number, however I'm trying to make up my own and was wondering if this approach is possible.
It returns Null for every iteration and I can't seem to see what I am missing here. Any help would be much appreciated!

var array;
var result = [];

function convertToRoman(num) {
  array = num.toString().split('').reverse();

  roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
  ];

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = array[i] + j;
    result = result.concat(roman[location]);
  }

  return result.reverse().join();
}

console.log(convertToRoman(123));

A: As array contains strings, you have to parse them back to integers when using them in the arithmetic. This is a possible solution:

var roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
  "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
  "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
];

function convertToRoman(num) {
  var result = [];
  var array = num.toString().split('').reverse();

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = parseInt(array[i]) + j;
    result.push(roman[location]);
  }

  return result.reverse().join('');
}

console.log(convertToRoman(123));

Note that I made some changes regarding variable scope and use of array.push(). I also didn't try the method for multiple inputs. But getting the algorithm correct was not part of your question


Q: Requiring multiple string conditions in WHERE CLAUSE SELECT stu.First_Name, stu.Last_Name, stu.Phone
FROM Student stu
JOIN Enrollment e
ON stu.Student_Id = e.Student_Id
JOIN Section sec
ON e.Section_Id = sec.Section_Id
JOIN Course c
ON sec.Course_No = c.Course_No
WHERE c.Description = 'Systems Analysis' AND c.Description = 'Project Managment'

Hey all, hopefully the last question for today (I'm so sorry).  I was wondering if there is a way to check for multiple string conditions (being an AND, not OR).  When I use just one my joins work alright, but I can't seem to work past using both.  My textbook wants me to solve it with only using the string keywords for the courses.

A: Use OR and filter only the rows having the same number of instances to the the number of filter specified in the WHERE clause.
SELECT  stu.First_Name,
        stu.Last_Name,
        stu.Phone
FROM    Student stu
        JOIN Enrollment e
            ON stu.Student_Id = e.Student_Id
        JOIN Section sec
            ON e.Section_Id = sec.Section_Id
        JOIN Course c
            ON sec.Course_No = c.Course_No
WHERE   c.Description IN ('Systems Analysis', 'Project Managment') -- two values
GROUP   BY stu.First_Name, stu.Last_Name, stu.Phone
HAVING  COUNT(*)  = 2 -- rows must have 2 instances


Q: Controlling x-axis label format for time series plots - R Is there a way force R to print time stamps as %m/%d/%Y on graphs? When I have short (<7 days) of data it prints as days of the week as below?
plot(station_171$datetime, station_171$stageheight, pch=ifelse(station_171$outcode ==122,24,21), col="black", bg=ifelse(station_171$outcode ==122,"red","NA")
     , xlab = "",xlim = c(min(station_101_7$datetime),max(station_101_7$datetime)), ylab = "")
legend("topright","171", bty = "n", cex=2)

A: You can format the axis using axis.POSIXct as seen below:
axis.POSIXct(1,station_171$datetime, format = '%Y-%m-%d %H:%S')

One should also make sure to include the xaxt='n' in the plot function to avoid double printing the x-axis labels.


Q: How to remove label from dynamically generated check box in PyQt5? So I have a table which has several checkboxes dynamically generated using these lines of codes:
chkBoxItem = QTableWidgetItem()
chkBoxItem.setTextAlignment(Qt.AlignHCenter)
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
ui.columnTable.cellChanged.connect(self.checkColumnDataCheckbox)
ui.columnTable.setItem(i , 0, chkBoxItem)

I have tried resizing it to a small value but it's not working:
chkBoxItem.setSizeHint(QSize(10,10))

Seems like it doesn't go beyond a certain minimum width and height.
Here's how it looked:

Basically, I want to remove this text label so the checkbox can be positioned at the center of the cell

A:
void QTableWidget::setCellWidget(int row, int column, QWidget *widget)
Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.

import sys
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *

class Window(QWidget):
    def __init__(self, rows, columns):
        super().__init__()

        self.table = QTableWidget(rows, columns, self)

        for row in range(rows):
            widget   = QWidget()
            checkbox = QCheckBox()
            checkbox.setCheckState(Qt.Unchecked)
            layoutH = QHBoxLayout(widget)
            layoutH.addWidget(checkbox)
            layoutH.setAlignment(Qt.AlignCenter)
            layoutH.setContentsMargins(0, 0, 0, 0)

            self.table.setCellWidget(row, 0, widget)                  # <----
            self.table.setItem(row, 1, QTableWidgetItem(str(row)))

        self.button = QPushButton("Control selected QCheckBox")
        self.button.clicked.connect(self.ButtonClicked)

        layoutV     = QVBoxLayout(self)
        layoutV.addWidget(self.table)
        layoutV.addWidget(self.button)

    def ButtonClicked(self):
        checked_list = []
        for i in range(self.table.rowCount()):
            if self.table.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
                checked_list.append(self.table.item(i, 1).text())
        print(checked_list)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window(3, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())


Q: Shortcut to move the cursor to certain characters in Webstorm I've seen several videos where the user is using Webstorm and hits a keyboard shortcut which brings up a small input field that the user can type a letter, number or other character into. Webstorm then presents the user with several choices denoted by "A", "B", "C", etc. which the user can then type the value of to move to the appropriate spot in the file that is currently being edited. I've searched through Webstorm's shortcuts, but I don't see anything to this effect. Does anyone know what this shortcut is?
I can try to get a screen shot if my explanation wasn't clear enough.
Thanks!

A: It is AceJump plugin - the easiest way to get it - go to Settings-Plugins click on Browse Repository and search for AceJump. Once you install it - the hardest thing for me was to force myself to use it after 2 months - I even type documents in webstorm and then copy it to Word.
Repository is here
https://plugins.jetbrains.com/plugin/7086
Github is here
https://github.com/johnlindquist/AceJump
Good luck :-)


Q: Is there a better way to dynamically build an SQL WHERE clause than by using 1=1 at its beginning? I'm building some SQL query in C#. It will differ depending on some conditions stored as variables in the code.
string Query="SELECT * FROM Table1 WHERE 1=1 ";
if (condition1)
    Query += "AND Col1=0 ";
if (condition2)
    Query += "AND Col2=1 ";
if (condition3)
    Query += "AND Col3=2 ";

It works, but testing 1=1 doesn't seem elegant. If I didn't use it, I would have to remember and check every time if "where" keyword was already added or not to the query.
Is there a nicer solution?

A: Just append two lines at back.
string Query="SELECT * FROM Table1 WHERE 1=1 ";
if (condition1) Query+="AND Col1=0 ";
if (condition2) Query+="AND Col2=1 ";
if (condition3) Query+="AND Col3=2 ";
Query.Replace("1=1 AND ", "");
Query.Replace(" WHERE 1=1 ", "");

E.g.
SELECT * FROM Table1 WHERE 1=1 AND Col1=0 AND Col2=1 AND Col3=2

will become to
SELECT * FROM Table1 WHERE Col1=0 AND Col2=1 AND Col3=2

While
SELECT * FROM Table1 WHERE 1=1

will become to
SELECT * FROM Table1

=====================================
Thanks for pointing out a flaw of this solution:
"This could break the query if, for any reason, one of the conditions contains the text "1=1 AND " or " WHERE 1=1 ". This could be the case if the condition contains a subquery or tries to check if some column contains this text, for example. Maybe this isn't a problem in your case but you should keep it in mind… "
In order to get rid of this issue, we need to distinguish the "main" WHERE 1=1 and those from subquery, which is easy:
Simply make the "main" WHERE special: I would append a "$" sign
string Query="SELECT * FROM Table1 WHERE$ 1=1 ";
if (condition1) Query+="AND Col1=0 ";
if (condition2) Query+="AND Col2=1 ";
if (condition3) Query+="AND Col3=2 ";

Then still append two lines:
Query.Replace("WHERE$ 1=1 AND ", "WHERE ");
Query.Replace(" WHERE$ 1=1 ", "");

A: One solution is to simply not write queries manually by appending strings. You could use an ORM, like Entity Framework, and with LINQ to Entities use the features the language and framework offer you:
using (var dbContext = new MyDbContext())
{
    IQueryable<Table1Item> query = dbContext.Table1;

    if (condition1)
    {
        query = query.Where(c => c.Col1 == 0);
    }
    if (condition2)
    {
        query = query.Where(c => c.Col2 == 1);
    }
    if (condition3)
    {
        query = query.Where(c => c.Col3 == 2);
    }

    PrintResults(query);
}

A: Use this:
string Query="SELECT * FROM Table1 WHERE ";
string QuerySub;
if (condition1) QuerySub+="AND Col1=0 ";
if (condition2) QuerySub+="AND Col2=1 ";
if (condition3) QuerySub+="AND Col3=2 ";

if (QuerySub.StartsWith("AND"))
    QuerySub = QuerySub.TrimStart("AND".ToCharArray());

Query = Query + QuerySub;

if (Query.EndsWith("WHERE "))
    Query = Query.TrimEnd("WHERE ".ToCharArray());

A: Why not using an existing Query Builder ?
Something like Sql Kata.
It supports complex where conditions, joins and subqueries.
var query = new Query("Users").Where("Score", ">", 100).OrderByDesc("Score").Limit(100);

if(onlyActive)
{
   query.Where("Status", "active")
}

// or you can use the when statement

query.When(onlyActive, q => q.Where("Status", "active"))

it works with Sql Server, MySql and PostgreSql.

A: If this is SQL Server, you can make this code much cleaner.
This also assumes a known number of parameters, which may be a poor assumption when I think about the possibilities.
In C#, you would use:
using (SqlConnection conn = new SqlConnection("connection string"))
{
    conn.Open();
    SqlCommand command = new SqlCommand()
    {
        CommandText = "dbo.sample_proc",
        Connection = conn,
        CommandType = CommandType.StoredProcedure
    };

    if (condition1)
        command.Parameters.Add(new SqlParameter("Condition1", condition1Value));
    if (condition2)
        command.Parameters.Add(new SqlParameter("Condition2", condition2Value));
    if (condition3)
        command.Parameters.Add(new SqlParameter("Condition3", condition3Value));

    IDataReader reader = command.ExecuteReader();

    while(reader.Read())
    {
    }

    conn.Close();
}

And then on the SQL side:
CREATE PROCEDURE dbo.sample_proc
(
    --using varchar(50) generically
    -- "= NULL" makes them all optional parameters
    @Condition1 varchar(50) = NULL
    @Condition2 varchar(50) = NULL
    @Condition3 varchar(50) = NULL
)
AS
BEGIN
    /*
    check that the value of the parameter
    matches the related column or that the
    parameter value was not specified.  This
    works as long as you are not querying for
    a specific column to be null.*/
    SELECT *
    FROM SampleTable
    WHERE (Col1 = @Condition1 OR @Condition1 IS NULL)
    AND   (Col2 = @Condition2 OR @Condition2 IS NULL)
    AND   (Col3 = @Condition3 OR @Condition3 IS NULL)
    OPTION (RECOMPILE)
    --OPTION(RECOMPILE) forces the query plan to remain effectively uncached
END

A: The quickest literal solution to what you're asking that I can think of is this:
string Query="SELECT * FROM Table1";
string Conditions = "";

if (condition1) Conditions+="AND Col1=0 ";
if (condition2) Conditions+="AND Col2=1 ";
if (condition3) Conditions+="AND Col3=2 ";

if (Conditions.Length > 0)
  Query+=" WHERE " + Conditions.Substring(3);

It doesn't seem elegant, sure, to which I would refer you to CodeCaster's recommendation of using an ORM.  But if you think about what this is doing here, you're really not worried about 'wasting' 4 characters of memory, and it's really quick for a computer to move a pointer 4 places.
If you have the time to learn how to use an ORM, it could really pay off for you.  But in regards to this, if you're trying to keep that additional condition from hitting the SQL db, this will do it for you.

A: Depending on the condition, it might be possible to use boolean logic in the query. Something like this :
string Query="SELECT * FROM Table1  " +
             "WHERE (condition1 = @test1 AND Col1=0) "+
             "AND (condition2 = @test2 AND Col2=1) "+
             "AND (condition3 = @test3 AND Col3=2) ";

A: I like the fluent interface of stringbuilder, so I made some ExtensionMethods.
var query = new StringBuilder()
    .AppendLine("SELECT * FROM products")
    .AppendWhereIf(!String.IsNullOrEmpty(name), "name LIKE @name")
    .AppendWhereIf(category.HasValue, "category = @category")
    .AppendWhere("Deleted = @deleted")
    .ToString();

var p_name = GetParameter("@name", name);
var p_category = GetParameter("@category", category);
var p_deleted = GetParameter("@deleted", false);
var result = ExecuteDataTable(query, p_name, p_category, p_deleted);

// in a seperate static class for extensionmethods
public StringBuilder AppendLineIf(this StringBuilder sb, bool condition, string value)
{
    if(condition)
        sb.AppendLine(value);
    return sb;
}

public StringBuilder AppendWhereIf(this StringBuilder sb, bool condition, string value)
{
    if (condition)
        sb.AppendLineIf(condition, sb.HasWhere() ? " AND " : " WHERE " + value);
    return sb;
}

public StringBuilder AppendWhere(this StringBuilder sb, string value)
{
    sb.AppendWhereIf(true, value);
    return sb;
}

public bool HasWhere(this StringBuilder sb)
{
    var seperator = new string [] { Environment.NewLine };
    var lines = sb.ToString().Split(seperator, StringSplitOptions.None);
    return lines.Count > 0 && lines[lines.Count - 1].Contains("where", StringComparison.InvariantCultureIgnoreCase);
}

// http://stackoverflow.com/a/4217362/98491
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
    return source.IndexOf(toCheck, comp) >= 0;
}

A: IMHO, I think that your approach is wrong:
Query the database by concatenating string is NEVER a good idea (risk of SQL injection and the code can easily be broken if you do some changes elsewhere).
You can use an ORM (I use NHibernate) or at least use SqlCommand.Parameters
If you absolutely want to use string concatenation, I would use a StringBuilder (it is the right object for string concatenation):
var query = new StringBuilder("SELECT * FROM Table1 WHERE");
int qLength = query.Length;//if you don't want to count :D
if (Condition1) query.Append(" Col1=0 AND");
if (Condition2) query.Append(" Col2=0 AND");
....
//if no condition remove WHERE or AND from query
query.Length -= query.Length == qLength ? 6 : 4;

As the last thought, Where 1=1 is really ugly but SQL Server will optimize it anyway.

A: The Dapper SqlBuilder is a pretty good option. It's even used in production on StackOverflow.
Read Sam's blog entry about it.
As far as I know, it's not part of any Nuget package, so you'll need to copy paste its code into your project or download the Dapper source and build the SqlBuilder project. Either way, you'll also need to reference Dapper for the DynamicParameters class.

A: A slight bit of overkill in this simple case but I've used code similar to this in the past.
Create a function
string AddCondition(string clause, string appender, string condition)
{
    if (clause.Length <= 0)
    {
        return String.Format("WHERE {0}",condition);
    }
    return string.Format("{0} {1} {2}", clause, appender, condition);
}

Use it like this
string query = "SELECT * FROM Table1 {0}";
string whereClause = string.Empty;

if (condition 1)
    whereClause = AddCondition(whereClause, "AND", "Col=1");

if (condition 2)
    whereClause = AddCondition(whereClause, "AND", "Col2=2");

string finalQuery = String.Format(query, whereClause);

This way if no conditions are found you don't even bother loading a where statement in the query and save the sql server a micro-second of processing the junk where clause when it parses the sql statement.

A: Save the conditions in a list:
List<string> conditions = new List<string>();

if (condition1) conditions.Add("Col1=0");
//...
if (conditions.Any())
    Query += " WHERE " + string.Join(" AND ", conditions.ToArray());

A: There is another solution, which may also not be elegant, but works and solves the problem:
String query = "SELECT * FROM Table1";
List<string> conditions = new List<string>();
// ... fill the conditions
string joiner = " WHERE ";
foreach (string condition in conditions) {
  query += joiner + condition;
  joiner = " AND "
}

For:

*

*empty conditions list, the result will be simply SELECT * FROM Table1,

*a single condition it will be SELECT * FROM Table1 WHERE cond1

*each following condition will generate additional AND condN

A: Just do something like this:
using (var command = connection.CreateCommand())
{
    command.CommandText = "SELECT * FROM Table1";

    var conditions = "";
    if (condition1)
    {
        conditions += "Col1=@val1 AND ";
        command.AddParameter("val1", 1);
    }
    if (condition2)
    {
        conditions += "Col2=@val2 AND ";
        command.AddParameter("val2", 1);
    }
    if (condition3)
    {
        conditions += "Col3=@val3 AND ";
        command.AddParameter("val3", 1);
    }
    if (conditions != "")
        command.CommandText += " WHERE " + conditions.Remove(conditions.Length - 5);
}

It's SQL injection safe and IMHO, it's pretty clean. The Remove() simply removes the last AND;
It works both if no conditions have been set, if one have been set or if multiple have been set.

A: I see this used all the time in Oracle while building dynamic SQL within stored procedures. I use it in queries while exploring data issues as well just to make switching between different filters of data faster... Just comment out a condition or add it back in easily.
I find it's pretty common and easy enough to understand to someone reviewing your code.

A: Using string function you can also do it this way:
string Query = "select * from Table1";

if (condition1) WhereClause += " Col1 = @param1 AND "; // <---- put conditional operator at the end
if (condition2) WhereClause += " Col1 = @param2 OR ";

WhereClause = WhereClause.Trim();

if (!string.IsNullOrEmpty(WhereClause))
    Query = Query + " WHERE " + WhereClause.Remove(WhereClause.LastIndexOf(" "));
// else
// no condition meets the criteria leave the QUERY without a WHERE clause

I personally feel easy to to remove the conditional element(s) at the end, since its position is easy to predict.

A: I thought of a solution that, well, perhaps is somewhat more readable:
string query = String.Format("SELECT * FROM Table1 WHERE "
                             + "Col1 = {0} AND "
                             + "Col2 = {1} AND "
                             + "Col3 = {2}",
                            (!condition1 ? "Col1" : "0"),
                            (!condition2 ? "Col2" : "1"),
                            (!condition3 ? "Col3" : "2"));

I'm just not sure whether the SQL interpreter will also optimize away the Col1 = Col1 condition (printed when condition1 is false).

A: public static class Ext
{
    public static string addCondition(this string str, bool condition, string statement)
    {
        if (!condition)
            return str;

        return str + (!str.Contains(" WHERE ") ? " WHERE " : " ") + statement;
    }

    public static string cleanCondition(this string str)
    {
        if (!str.Contains(" WHERE "))
            return str;

        return str.Replace(" WHERE AND ", " WHERE ").Replace(" WHERE OR ", " WHERE ");
    }
}

Realisation with extension methods.
    static void Main(string[] args)
    {
        string Query = "SELECT * FROM Table1";

        Query = Query.addCondition(true == false, "AND Column1 = 5")
            .addCondition(18 > 17, "AND Column2 = 7")
            .addCondition(42 == 1, "OR Column3 IN (5, 7, 9)")
            .addCondition(5 % 1 > 1 - 4, "AND Column4 = 67")
            .addCondition(Object.Equals(5, 5), "OR Column5 >= 0")
            .cleanCondition();

        Console.WriteLine(Query);
    }

A: Here is a more elegant way:
    private string BuildQuery()
    {
        string MethodResult = "";
        try
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("SELECT * FROM Table1");

            List<string> Clauses = new List<string>();

            Clauses.Add("Col1 = 0");
            Clauses.Add("Col2 = 1");
            Clauses.Add("Col3 = 2");

            bool FirstPass = true;

            if(Clauses != null && Clauses.Count > 0)
            {
                foreach(string Clause in Clauses)
                {
                    if (FirstPass)
                    {
                        sb.Append(" WHERE ");

                        FirstPass = false;

                    }
                    else
                    {
                        sb.Append(" AND ");

                    }

                    sb.Append(Clause);

                }

            }

            MethodResult = sb.ToString();

        }
        catch //(Exception ex)
        {
            //ex.HandleException()
        }
        return MethodResult;
    }

A: As has been stated, creating SQL by concatenation is never a good idea. Not just because of SQL injection. Mostly because it's just ugly, difficult to maintain and totally unnecessary. You have to run your program with trace or debug to see what SQL it generates. If you use QueryFirst (disclaimer: which I wrote) the unhappy temptation is removed, and you can get straight in ta doin it in SQL.
This page has a comprehensive coverage of TSQL options for dynamically adding search predicates. The following option is handy for situations where you want to leave the choice of combinations of search predicates to your user.
select * from table1
where (col1 = @param1 or @param1 is null)
and (col2 = @param2 or @param2 is null)
and (col3 = @param3 or @param3 is null)
OPTION (RECOMPILE)

QueryFirst gives you C# null to db NULL, so you just call the Execute() method with nulls when appropriate, and it all just works.
<opinion>Why are C# devs so reluctant to do stuff in SQL, even when it's simpler. Mind boggles.</opinion>

A: For longer filtering steps StringBuilder is the better approach as many says.
on your case I would go with:
StringBuilder sql = new StringBuilder();

if (condition1)
    sql.Append("AND Col1=0 ");
if (condition2)
    sql.Append("AND Col2=1 ");
if (condition3)
    sql.Append("AND Col3=2 ");

string Query = "SELECT * FROM Table1 ";
if(sql.Length > 0)
 Query += string.Concat("WHERE ", sql.ToString().Substring(4)); //avoid first 4 chars, which is the 1st "AND "

A: Concise, elegant and sweet, as shown in the image below.


Q: How to generate Java PKCS12 store to connect to regular SSL website? we run a standard web API over https with a regular purchased SSL certificate. Our clients just access it via https, the certificate is trusted via default system RootCA.
A new client is using a Java communication server that requires the certificate in a PKCS12 keystore. How can we generate the PKS12 keystore from our key/csr/crt/pem files?
I did some research, most examples are requiring a private key. Of course I do not want to share our private key with the client.
Can a PKCS12 keystore be created without private key, similar to standard RootCA in browsers?
Thanks, bluepuma

A: YES-ish.
Although PFX-now-PKCS12 was designed primarily to store or transfer a privatekey and cert and chain cert(s) as a clump, and most commonly is used for that, it is capable of storing one or more 'lone' cert(s) not matched to any privatekey. And you are correct the client wanting to connect to you should have in their truststore ideally the root cert for your server cert's chain, or alternatively your server cert itself, but decidedly not your privatekey.
openssl can actually create such a PKCS12:
 openssl pkcs12 -export -in certfile.pem [-name $name] -nokeys -out blah.p12
 # if you don't specify -name it defaults to 1 (the digit one) which can be mildly confusing
 # instead of being prompted for the password you can use -passout with several forms
 # described on the openssl man page, but consider the warning below

But the result won't work in Java if they use the standard (Sun/Oracle/OpenJDK) cryptoproviders, which (in 8+) support lone cert(s) in a PKCS12 as 'trustedCert' entries in Java only if the(each) certbag has a special Sun-defined attribute which the Java providers write when they create such a file, but OpenSSL doesn't.
Instead use Java's keytool in 8:
jre8/bin/keytool -importcert -keystore blah.p12 -storetype pkcs12 -file $certfile [-alias $name]

or in 9+ where pkcs12 is now the default:
jre9+/bin/keytool -importcert -keystore blah.p12 -file $certfile [-alias $name]

If you don't specify the alias it defaults to mykey. In both cases you can add -storepass $pw to avoid being prompted for it, but as a result the password will be visible on your screen, in the command history of your shell or other command processor it is has one, and in most cases to other processes run on your system concurrently, (any of) which may be a security issue or not. You can also add -noprompt to avoid the confirmation prompt.
But user207421 is (roughly) correct that using such a truststore can break other SSL/TLS connection(s) made from their system, at least from the same JVM, unless the individual calls specify individual, separate truststores, and if they had coded that they would know how to handle (and ask for) a simpler certificate format, such as PEM.


Q: asp.net datasource control parameter outside iframe Hope someone can help me here, i have been searching for a solution for a few days now but havent't found it.
I have build a page with 2 iframes, SelectCustomer which opens a page in where a dropdownlist lives with customer names and iframecontent in which i load a page by clicking a link. This page has a sqldatasource with a parameter. I want to refer to the dropdownlist in this parameter to filter the select query but i haven't found a way to refer to the dropdownlist outside the iframe "iframecontent".
This is the page with the iframes:
<%@ Page Title="" Language="VB" MasterPageFile="~/Dashboard/Sales/Dashboard_Sales.master" AutoEventWireup="false" CodeFile="Index.aspx.vb" Inherits="Dashboard_Sales_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

  <!DOCTYPE HTML>

</asp:Content>

This is the page from the first iframe:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SelectDebiteur.aspx.vb" Inherits="Dashboard_Sales_SelectDebiteur" %>

<!DOCTYPE html>

<title></title>

<form id="form1" runat="server">

    <asp:SqlDataSource ID="ListDebiteur" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [aa-270].cddeb, [ba-001].naamorg AS Debiteur FROM [aa-270] INNER JOIN [ba-001] ON [aa-270].cdorg = [ba-001].cdorg ORDER BY Debiteur"></asp:SqlDataSource>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="ListDebiteur" DataTextField="Debiteur" DataValueField="cddeb">
    </asp:DropDownList>

</form>

This is the page which get's loaded in the second iframe:
<!DOCTYPE html>

<title></title>

<form id="form1" runat="server">

    <asp:SqlDataSource ID="ListCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [aa-270].cddeb, [ba-001].naamorg AS Debiteur FROM [aa-270] INNER JOIN [ba-001] ON [aa-270].cdorg = [ba-001].cdorg ORDER BY Debiteur"></asp:SqlDataSource>
    <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="ListCustomers" DataTextField="Debiteur" DataValueField="cddeb">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [va-211].cdorg, [ba-001].naamorg, RTRIM(YEAR([va-211].[datum-lvoor])) + '-' + CASE WHEN RTRIM(MONTH([va-211].[datum-lvoor])) < 10 THEN '0' + RTRIM(MONTH([va-211].[datum-lvoor])) ELSE RTRIM(MONTH([va-211].[datum-lvoor])) END AS Maand, SUM(CASE WHEN [va-211].cdstatus = 'O' THEN [va-211].aanttelev * ([va-211].prijs / [bb-063].prijsper) WHEN [va-211].cdstatus = 'A' THEN [va-211].aantgelev * ([va-211].prijs / [bb-063].prijsper) END) AS Omzet FROM [ba-001] INNER JOIN [va-211] ON [ba-001].cdorg = [va-211].cddeb LEFT OUTER JOIN [bb-063] ON [va-211].cdprodukt = [bb-063].cdprodukt WHERE ([bb-063].cdprijssrt = 'VERK') AND ([va-211].cdstatus = 'O' OR [va-211].cdstatus = 'A') GROUP BY [ba-001].naamorg, RTRIM(YEAR([va-211].[datum-lvoor])) + '-' + CASE WHEN RTRIM(MONTH([va-211].[datum-lvoor])) < 10 THEN '0' + RTRIM(MONTH([va-211].[datum-lvoor])) ELSE RTRIM(MONTH([va-211].[datum-lvoor])) END, [va-211].cdorg HAVING (SUM(CASE WHEN [va-211].cdstatus = 'O' THEN [va-211].aanttelev * ([va-211].prijs / [bb-063].prijsper) WHEN [va-211].cdstatus = 'A' THEN [va-211].aantgelev * ([va-211].prijs / [bb-063].prijsper) END) > 0) AND ([va-211].cdorg = @param1) ORDER BY Maand, [ba-001].naamorg">
    <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList2" Name="param1" PropertyName="Text" DefaultValue="00000739" />
    </SelectParameters>
</asp:SqlDataSource>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" EnableModelValidation="True" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="cdorg" HeaderText="cdorg" SortExpression="cdorg" />
            <asp:BoundField DataField="naamorg" HeaderText="naamorg" SortExpression="naamorg" />
            <asp:BoundField DataField="Maand" HeaderText="Maand" ReadOnly="True" SortExpression="Maand" />
            <asp:BoundField DataField="Omzet" HeaderText="Omzet" ReadOnly="True" SortExpression="Omzet" />
        </Columns>
        <EditRowStyle BackColor="#7C6F57" />
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#E3EAEB" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>

</form>

And it's code behind page:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Dashboard_Sales_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        DropDownList2.SelectedValue = Request.QueryString["value"];
}
}

New challenge:
Omzet in portefeuille

A: One of the solutions is to refresh the second iframed page sending the DropDownList selected value as its query string, using jQuery (to make things easier).
To demonstrate, I'm basically updating a DropDownList on the second iframed page, but you can easily adapt to your needs:
Main page (where the iframes are placed):

First iframed page:

<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true">
    <asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
    <asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>

Second iframed page:
<asp:DropDownList ID="ddl2" runat="server" AutoPostBack="true">
    <asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
    <asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        ddl2.SelectedValue = Request.QueryString["value"];
}

UPDATE
Regarding your question posted on the comments, you can find out what's the second page iframe's src (and subsequently change it) this way:
$("#iframe2", parent.document).attr("src", $("#iframe2", parent.document).attr("src") + "?value=" + $(this).val());

UPDATE #2
As per your request, you want to load the iframe source dynamically, at the page load.
That's how you can achieve this:
Main page (where the iframes are placed):

First iframed page: