text:
Q: How to turn a string into a ClassName and execute a Linq query My question is how to make it possible to have a function that takes a string convert it to a class and than execute a linq query.
This is a simple example of how it should work:
 // DBContext
 DataView _db = new DataView();

 public static void ... (){
       Create("somedesc", "someabbr", "vwFunctieScheidingMetacom", "someiconstring");
 }
 // the function
 public static void Create(string description, string abbrevition, string cn, string icon)
 {
        // cn is classname
        // convert cn into a class
        var class = Convert.Class(cn);
        // Execute Linq query
        _db.class.ToList<dynamic>();
 }

This is my dbcontext:
public partial class DataView : DbContext
{
    public DataView()
        : base("name=DataView")
    {
    }

    public virtual DbSet<vwFunctieScheidingMetacom> vwFunctieScheidingMetacom { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}

Now there is only one model loaded, but in the future there will be more. these models will all be different and I want to make it as dynamic as possible.
I tried to use reflection but it didn't work yet, i have no idea where to start.
Any help would be appreciated.
update
This is one of the class that needs to be used dynamicly:
namespace Portal.ModelViews
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

[Table("vwFunctieScheidingMetacom")]
public partial class vwFunctieScheidingMetacom
{
    public int? PermissiesID1 { get; set; }

    public int? PermissiesID2 { get; set; }

    [StringLength(255)]
    public string PermName1 { get; set; }

    [StringLength(255)]
    public string PermName2 { get; set; }

    public string Omschrijving { get; set; }

    public int? Prioriteit { get; set; }

    [StringLength(50)]
    public string Login { get; set; }

    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int FunctieScheidingID { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(60)]
    [DisplayName("ID")]
    public string ID { get; set; }
}

}

A: Since you don't seem to like the answers so far I'll interpret your question differently. Put references to your classes in a dictionary.
Assuming your code defines a class Foo...
var clash = new Dictionary< string, Type>();
clash["Foo"] = Foo.GetType();

Populate this hash table with your strings and the types to which they resolve.


text:
Q: How to select a limited amount of rows for each foreign key? I have this table:
id
feed_id
...

Let's say that I have 500 rows and I want to select 3 entries for each feed_id? And 50 as total limit.
How to write this SQL?

A: Use:
SELECT x.feedid
  FROM (SELECT t.feedid,
               CASE WHEN @feed != t.feedid THEN @rownum := 1 ELSE @rownum := @rownum + 1 END AS rank,
               @feed := t.feedid
          FROM TABLE t
          JOIN (SELECT @rownum := NULL, @feed := 0) r
      ORDER BY t.feedid) x
 WHERE x.rank <= 3
 ORDER BY x.feedid
 LIMIT 50

What's not clear is the details of what you want returned - all the rows in your table, or just the feedid.

A: Have you tried using a subselect and limit?
Something like
SELECT  *
FROM    Table t
WHERE   ID IN (SELECT ID FROM @Table WHERE FEED_ID = t.FEED_ID LIMIT 3)
LIMIT 500

A: You can do this with help of stored procedure.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_feed`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE a INT;
DECLARE cur1 CURSOR FOR SELECT id FROM test.id LIMIT 50;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO a;
    IF NOT done THEN
        SELECT * FROM feed_id WHERE id=a LIMIT 3;
    END IF;
UNTIL done END REPEAT;
CLOSE cur1;

END$$
DELIMITER;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Receive Map in ktor server using kotlinx.serialization I have a Ktor server running with kotlinx.serialization as it's json (de)serializer
I send my Ktor a message like this one:
{
  "Brick(partNumber=004229, partName=Sticker Sheet for Set 295-1, dataSource=Rebrickable, brickImage=null, categoryID=58)": 5
}

which is a pair of an Int and this class:
import kotlinx.serialization.Serializable

@Serializable
data class Brick(
    val partNumber: String,
    val partName: String,
    val dataSource: String,
    val brickImage: String?,
    val categoryID: Int?
)

But I get this error
kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 0: Expected '[, kind: MAP'
    at kotlinx.serialization.json.internal.JsonReader.fail(JsonReader.kt:293)

Which to me means that kotlinx.serialization expects a different syntax for the map class. Which is odd to me. When I change the type into List> it throws the same exception but with LIST instead of MAP.
EDIT: Upon further inspection, it expects a [ instead of a { at the start of the line.
My (partial) application implementation
fun Application.module(testing: Boolean = false) {
    install(ContentNegotiation) { serialization() }
    routing {
        route("user") {
            route("brick") {
                post {
                    call.request.queryParameters["userName"]
                        ?.let { userRepository.login(it) } // Someone else is still working login nvm this
                        ?.let { user ->
                            val bricks = call.receive<Map<Brick, Int>>() // This throws an error
                            userRepository.addBricks(user, bricks)
                            call.respond(HttpStatusCode.OK)
                        }
                        ?: call.respond(HttpStatusCode.Unauthorized)
                }
            }
        }
    }
}

The android retrofit function that sends the class (using GSON):
    @POST("/user/brick")
    suspend fun setBricksAmounts(
        @Query("userName")
        userName: String,
        @Body
        brickAmounts: Map<Brick, Int>
    )

A: I think using a class as a key does not work in kotlinx serialization
and it looks like that class is just serialized into a string to use it as key
Instead you can receive it as Map<String, Int>
and afterwards run
bricks.mapKeys { (jsonString, number) ->
   Json(JsonConfiguration.Stable).parse(Brick.Serializer, jsonString)
}

or the equivalent jackson code if you want


text:
Q: Aws S3 Filter by Tags. Search by tags We have our bucket with new Aws SDK API on AWS S3. We uploaded and tagged lots of files and folders with tags.
How can we filter on key-value tag, or only one of them? I'd like to find all the objects with key = "temp", or key = "temp" and value = "lol".
Thanks!

A: There seems to be one way to achieve what you're looking for, although it's not ideal, or particularly user-friendly.
The AWS S3 tagging documentation says that you can grant accounts permissions for objects with a given tag. If you created a new account with the right permissions then you could probably get the filtered list.
Not particularly useful on an ongoing basis, though.

A: AFAIK - Resource Groups don't support tags on an S3 Object level only on a bucket level.
Source: https://aws.amazon.com/blogs/aws/new-aws-resource-tagging-api/ (scroll down the page to the table).

A: This is now possible using AWS Resource Tagging API and S3 Select (SQL). See this post: https://aws.amazon.com/blogs/architecture/how-to-efficiently-extract-and-query-tagged-resources-using-the-aws-resource-tagging-api-and-s3-select-sql/.
However, the Resource Tagging API supports only tags on buckets for the S3 service, not on objects: New – AWS Resource Tagging API

A: I also hoped that AWS will eventually support "search files by tags" because that would open up possibilities like e.g. having a photo storage with the names, descriptions, location stored in tags so I wouldn't need a separate database.
But, apparently AWS explicitly is not supporting this, and will probably never do so. Quoting from their storage service white paper:

Amazon S3 doesn't suit all storage situations. [...] some storage needs for which you should consider other AWS storage options [...]
Amazon S3 doesn't offer query capabilities to retrieve specific objects. When you use Amazon S3 you need to know the exact bucket name and key for the files you want to retrieve from the service. Amazon S3 can't be used as a database or search engine by itself.
Instead, you can pair Amazon S3 with Amazon DynamoDB, Amazon CloudSearch, or Amazon Relational Database Service (Amazon RDS) to index and query metadata about Amazon S3 buckets and objects.

AWS suggests using DynamoDB, RDS or CloudSearch instead.

A: There's no way to filter/search by tags. But you can implement this yourself using S3.
You can create a special prefix in a bucket, e.g. /tags/. Then for each actual object you add and want to assign a tag (e.g. Department=67), you add a new object in /tags/, e.g: /tags/XXXXXXXXX_YYYYYYYYY_ZZZZZZZZZ, where
XXXXXXXXX = hash('Department')
YYYYYYYYY = hash('67')
ZZZZZZZZZ = actualObjectKey

Then when you want to get all objects that have a particular tag assigned (e.g. Department), you have to execute the ListObjectsV2 S3 API for prefix /tags/XXXXXXXXX_. If you want objects that have particular tag value (e.g. Department=67), you have to execute the ListObjectsV2 S3 API for prefix /tags/XXXXXXXXX_YYYYYYYYY_
https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
It's not that fast but still does the job.
Obvious downside is that you have to remove the tags yourself. For example, you can do all of this above with a S3 triggers and lambda.

A: You should be able to query tags and values that you added
using resource-groups/query resource:
https://${region}.console.aws.amazon.com/resource-groups/resources

A: There is many way to get filter list of s3 by tag. I used in my code:
import boto3
from botocore.exceptions import ClientError

def get_tag_value(tags, key):
    for tag in tags:
        if tag["Key"] == key:
            return tag["Value"]
    return ""

def filter_s3_by_tag_value(tag_key,tag_value):
    s3 = boto3.client('s3')
    response = s3.list_buckets()
    s3_list=[]
    for bucket in response["Buckets"]:
        try:
            response_tags = s3.get_bucket_tagging(Bucket=bucket["Name"])
            if get_tag_value(response_tags["TagSet"],tag_key) == tag_value:
                s3_list.append(bucket["Name"])
        except ClientError as e:
            print(e.response["Error"]["Code"])

    return s3_list

def filter_s3_by_tag_key(tag_key):
    s3 = boto3.client('s3')
    response = s3.list_buckets()
    s3_list=[]
    for bucket in response["Buckets"]:
        try:
            response_tags = s3.get_bucket_tagging(Bucket=bucket["Name"])
            if get_tag_value(response_tags["TagSet"],tag_key) != "":
                s3_list.append(bucket["Name"])
        except ClientError as e:
            print(e.response["Error"]["Code"])

    return s3_list

print(filter_s3_by_tag_value(tag_key,tag_value))

print(filter_s3_by_tag_key(tag_key))

A: AWS now supports tagging of S3 images.
They have APIs to add/remove tags.
Amazon S3 Select, Amazon Athena can be used to search for S3 resources with TAGS.
Currently the max number of tags per resource is 10 (thanks Kyle Bridenstine for pointing out the correct number).


text:
Q: Acronym not defined warning I'm getting some strange warnings when I build my latex files with pdftex (texlipse). I have defined an acronym list like this:
\chapter*{Acronyms}
\addcontentsline{toc}{chapter}{Acronyms}

\begin{acronym}

\acro{AL} {Authentication List}
\acro{AM} {Authentication Module}

...

\end{acronym}

And I when I refer to these acronyms (everyone in the list, but didn't include all here) like this:
... of the \ac{AL} periodically ...

I get lots of warnings like this in texlipse:
Acronym `AL' is not defined on input line 117

However, the PDF file is produced correctly. My only issue is that I want to go through the warnings to find things that actually needs attention (like overfull /hboxes) but with hundreds of these errors that gets quite tedious.
Does anyone know how to get around this problem? Is there maybe some settings in my texlipse that is wrong? I know texlipse don't automatically recognize the acronyms package as when I press ctrl+space I never get the 'ac' option, while other latex commands such as 'begin' will show up.

A: I am not familiar with texlipse but, if you have not yet got to the bottom of this I would expect a second compile run should resolve the warnings. For the second run to be effective you need to keep the output files from the first run (especially the .aux file, see below).
1) I assume the package declaration \usepackage{acronym} is in your .tex file preamble.
[If not then it would still work (sort of) in that there would be lots of errors (e.g. '! Undefined control sequence. l.8 the \ac{AL} periodically and the \ac{AM} once.') but the acronyms appear in the text (all unexpanded of course) and the acronym list appears in the acronyms list.]
2) With the acronym package then the following compiles without error but with lots of warnings of the type you report (e.g. 'Package acronym Warning: Acronym `AL' is not defined on input line 8'.):
\documentclass{book}
\usepackage{acronym}
\begin{document}
\chapter{Text sample}
\addcontentsline{toc}{chapter}{Text sample}

Not much to be said here other than to note
the \ac{AL} periodically and the \ac{AM} once.

The second \ac{AL} occurrence, as discussed.

\chapter*{Acronyms}
\addcontentsline{toc}{chapter}{Acronyms}

\begin{acronym}
\acro{AL} {Authentication List}

\acro{AM} {Authentication Module}
\end{acronym}

\end{document}

However, the PDF file does not look correct as the acronyms are rendered as, for example, 'the AM! (AM!)'. The reason for this is that on the first pass of the compiler it cannot resolve the acronyms but by the end of the pass it has written the details into a .aux file with the same name as the .tex file. e.g., for the simple .tex above the .aux file generated by pdflatex was:
\relax
\reset@newl@bel
\@writefile{toc}{\contentsline {chapter}{\numberline {1}Text sample}{1}}
\@writefile{lof}{\addvspace {10\p@ }}
\@writefile{lot}{\addvspace {10\p@ }}
\@writefile{toc}{\contentsline {chapter}{Text sample}{1}}
\undonewlabel{acro:AL}
\newlabel{acro:AL}{{1}{1}}
\acronymused{AL}
\undonewlabel{acro:AM}
\newlabel{acro:AM}{{1}{1}}
\acronymused{AM}
\acronymused{AL}
\@writefile{toc}{\contentsline {chapter}{Acronyms}{3}}
\newacro{AL}[\AC@hyperlink{AL}{AL}]{Authentication List}
\newacro{AM}[\AC@hyperlink{AM}{AM}]{Authentication Module}

A second pass of the compiler can then use the information in the .aux file as it parses the .tex file to generate a complete .pdf file, including, by default, the expansion of the acronym on the first occurrence. On my system this generated the .pdf file as expected and with no errors or warning from pdflatex.


text:
Q: Make WPF Datepicker's foreground/background look like those in a Textbox when IsEnabled=False When IsEnabled=false, the datepicker's text looks light grey whereas the textbox's text is a crisp black, which is what I want to acheive.
I have tried using the following, but no joy:
<Style TargetType="{x:Type DatePickerTextBox}">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="LightGray"></Setter>
            <Setter Property="FontWeight" Value="Normal"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>

I'll be grateful for some pointers.

A: I solved this binding to the IsEnabled Property and using a  Converter:
XAML:
<Style TargetType="DatePickerTextBox">
    <Setter Property="Background" Value="{Binding IsEnabled, Mode=OneWay, RelativeSource={RelativeSource Self}, Converter={StaticResource BoolToBackgroundConverter"/>
</Style>

Converter-Methods:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if ((bool)value)
        return System.Windows.Media.Brushes.White;
    else
        return System.Windows.Media.Brushes.WhiteSmoke;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    throw new NotImplementedException("One way conversions only!");
}

A: Try
<Style TargetType="{x:Type DatePickerTextBox}">
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="LightGray"></Setter>
            **<Setter Property="FontWeight" Value="Black"></Setter>**
        </Trigger>
    </Style.Triggers>
</Style>

A: Following seems to work, in case it helps anyone else with similar issue:
<Style TargetType="{x:Type customControls:DatePicker}">
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Border BorderBrush="LightGray" BorderThickness="1">
                            <TextBlock Margin="4,0,0,0" Text="{Binding Path=Text, StringFormat={}{0:d}, RelativeSource={RelativeSource TemplatedParent}}"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>


text:
Q: Which one of these 5 pin 3 phase connectors is more standard? Images: http://imgur.com/a/BItbR
One is rated 16A "Dafr-164m" and another is rated 32A "Typ 2"
We have a 16A breaker quite a ways from our house ~50m.
We asked someone and they said they use both.
We have 230v, 380v 50Hz
We have to change the connectors because our house uses the old Soviet connector and... we have no incoming earth! Only 3ph+N because ~50% of the electrical wiring in my town is Soviet-era and there's no earth

A: Either two of them, the difference is in rated current 16A or 32A. Usually the 32A is well suited for a medium/small machine, the power connected is 32*0.4*1.73 <= 22kW, while the smaller one is more frequenty in use, because is the minimal 3 phase connector, therefore all hand tools, small electric machines, P<=11kW goes on 16A connector. The conclusion is: probably you wil need more 16A connectors.
The 3ph+N, what you are reffering is a 3PH+PEN, it's normal in most places in the world, in EU also. At your main cabinet you should split this PEN wire into two wires PE and N. The distribution network is never 2PH+N+PE, you won't find this enywhere, its not a Soviet madness.


text:
Q: What is it called when you use the word 'you' like in this sentence to refer to any person and not just you specifically? While having a conversation, I say: "When you say atheist, most people would imagine an anti-religious person". What I meant by 'you' is actually anybody. When I am using 'you' in such a manner, what am I doing? Is there a name/word for it? Is it using a 'figure of speech'?
Thank you

A: This informal usage of the second person pronoun not directed to a specific person or group is called the ubiquitous you. It substitutes for the indefinite one, which seems too formal to some, although someone or somebody does equally well in most registers.
Addendum
The term is found in these grammar exercises in Sweden,  a discussion of a Maya Angelou poem, a blog for teachers of composition, a handout for high school students, an explanatory parenthetical in a forum post, and finally, not quite understood in a blog post. Considering how long ago I learned the term, if it hadn't been in use since that time, I doubt seriously if it would show up at all. Perhaps others learned and use a different terminology, but the main point is that this usage is not as a second personal pronoun addressing a specific person or group, but as an indefinite third person. Whatever terminology conveys that meaning is sufficient.

A: It's called an indefinite or generic use of you.
It's equivalent to the more formal indefinite pronoun one:

*

*You never know what you'll find there.

*One never knows what one will find there.
or other indefinite NPs, like

*

*People never know what they'll find there.
In all these examples, the subject NPs don't refer to any specific individual,
but rather to anyone who fits the description in the sentence.
In my experience, the use of the indefinite you is especially frequent in giving advice,
where the you can refer either specifically to the addressee, or to an indefinite person,
or to both, which makes it convenient.


text:
Q: OpenSSH: How to run a command upon ssh connection I need to customize OpenSSH server, so that when a new SSH connection is being made to the server, it runs some command (like running a bash script). This command is supposed to "prepare" the server for the SSH connection.
So, from client side it is just a normal SSH connection: ssh user@server.com
But on the server side, it runs a command, then allows the SSH session to start.
Is this possible with OpenSSH? or do I need to write my own SSH server?
Can the same be done when SSH connection is terminated?

A: Maybe I have misunderstood you but if you want to run a command in the server context as opposed to ForceCommand which runs for the user connection you may want to use a socket activated SSHD installation which is described here:
http://0pointer.de/blog/projects/socket-activated-containers.html
In case you want to run scripts before sshd is launched, use multiple ExecStart statements where sshd is the last.

A: Yes, use ForceCommand in sshd_config. It is well described in the manual page for sshd_config:
https://linux.die.net/man/5/sshd_config
To allow the connection to proceed, you just execute the original command (stored in SSH_ORIGINAL_COMMAND env. variable) in your wrapper script.


text:
Q: Arduino MySQL connector - SELECT statement returns NULL I am trying to get DB data using SELECT. But Unfortunately, I always get NULL even though I have data in the database. The following is my code ( i didn't include the server details and include statements). If I put all the codes inside the void loop, instead of a function like void check_parameter(), everything works !. But why it isn't working when it is inside a function?
int device_id = 1;
String Parameter[3] = {"one", "two", "three"};   // aim is to update these values with db data

EthernetClient client;
MySQL_Connection conn((Client *)&client);

const char QUERY_PARA[] = "SELECT ref_time, val_first, val_second  FROM test_db.test_table WHERE Id=  %lu;";
char query[128];

void setup()
{
    Serial.begin(115200);
    while (!Serial);
    Ethernet.begin(mac_addr);
}

void loop()
{
    Serial.println("inside the loop....");
    delay(10000);
    check_parameter();
}

void check_parameter()
{
  if (conn.connect(server_addr, 3306, user, password))
    {
        Serial.println("calling the check_para....");
        delay(5000);

        MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
        sprintf(query, QUERY_PARA, device_id);

        cur_mem->execute(query);
        column_names *cols = cur_mem->get_columns();

        Serial.println();
        row_values *row = NULL;

        do
        {
            row = cur_mem->get_next_row();
            if (row != NULL)
            {
              // here is the problem. the row is always NULL! I dunno why ??
                Parameter[0] = String(row->values[0]);
                Parameter[1] = String(row->values[1]);
                Parameter[2] = String(row->values[2]);

                cur_mem->free_row_buffer();
            }
        } while (row != NULL);
        cur_mem->free_columns_buffer();
        delete cur_mem;

        Serial.println("printing parameters");
        Serial.println(Parameter[0]);
        Serial.println(Parameter[1]);
        Serial.println(Parameter[2]);

        conn.close();
    }
    else
    {
        Serial.println("Connection failed.");
    }
}


text:
Q: How can I find the equation of a parabola only given it's x-intercepts? I received a problem in my math class the other day that left me stumped. The problem went something like this.

Mr. Lots-O-Cash would like to order a parabola that passes through the points $(-4, 0)$, and $(2, 0)$. Create an equation for this so you can pass the information onto the manufacturing department.

I'm wondering, how can I find the equation for this parabola. It seems like to little info to find one. Please don't give me an answer, just a way to solve it.

A: The general form of a parabola/quadratic is:
$$y=ax^2+bx+c$$
You should be able to construct a pair of simultaneous equations using the two points and solve for $a,b,c$.
Another method is to consider:
$$y=\lambda(x-\alpha)(x-\beta)$$
Where $\alpha , \beta$ are the roots of the parabola.


text:
Q: Error in backend UI for GCM devappserver I get the following error when I try to access my registered devices local dev app server while testing the GCM. Can someone please help. I am following the steps as here https://developers.google.com/eclipse/docs/endpoints-androidconnected-gae
I am able to see the registered device in //:localhost:8888/_ah/admin. But when I open //:localhost:8888/ I see the error below. The page loads but the registered devices does not show up and I see this error message below the Send button.
There was a problem contacting the server when attempting to list the registered devices.
Please refresh the page and try again in a short while. Here's the error information:
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
 <title>Error 500 INTERNAL_SERVER_ERROR</title>
HTTP ERROR 500

Problem
 accessing /_ah/api/rpc. Reason:
 INTERNAL_SERVER_ERROR

Caused
 by:

java.lang.NullPointerException at
 com.google.api.server.spi.tools.devserver.ApiServlet.addDefaultParams(ApiServlet.java:264) at
 com.google.api.server.spi.tools.devserver.ApiServlet.addParametersToMap(ApiServlet.java:257) at
 com.google.api.server.spi.tools.devserver.ApiServlet.doSingleBackendCall(ApiServlet.java:239)
 at com.google.api.server.spi.tools.devserver.RpcApiServlet.doSingleBackendCall
 (RpcApiServlet.java:131) at com.google.api.server.spi.tools.devserver.RpcApiServlet.service
 (RpcApiServlet.java:112) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at
 org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) at
 com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.appengine.tools.development.ResponseRewriterFilter.doFilter
 (ResponseRewriterFilter.java:123) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.appengine.tools.development.HeaderVerificationFilter.doFilter
 (HeaderVerificationFilter.java:34) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter
  (TransactionCleanupFilter.java:43) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 com.google.appengine.tools.development.DevAppServerServersFilter.doDirectRequest
 (DevAppServerServersFilter.java:369) at
 com.google.appengine.tools.development.DevAppServerServersFilter.doDirectServerRequest
 (DevAppServerServersFilter.java:352) at
 com.google.appengine.tools.development.DevAppServerServersFilter.doFilter
 (DevAppServerServersFilter.java:115) at
 org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at
 org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at
 org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at
 org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at
 org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at
 org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) at
 com.google.appengine.tools.development.DevAppEngineWebAppContext.handle
 (DevAppEngineWebAppContext.java:97) at org.mortbay.jetty.handler.HandlerWrapper.handle
 (HandlerWrapper.java:152) at
 com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle
 (JettyContainerService.java:438) at org.mortbay.jetty.handler.HandlerWrapper.handle
 (HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at
 org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at
 org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938) at
 org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755) at
 org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) at
 org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at
 org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409) at
 org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

Powered by Jetty://


text:
Q: React JS useState hook not working with curly braces Can someone explain why this code won't run properly with curly braces around prev + 1 in the increment function?
export default function Counter() {
  const [clickCount, setClickCount] = useState(0);

  useEffect(() => {
       document.addEventListener('mousedown', increment);
       return () => {
           document.removeEventListener('mousedown', increment);
      };
   });

   // your code here
  const increment = () => {
      setClickCount((prev) => {prev + 1})
  }

  return (

Document Clicks: {clickCount}

  );
}

A: Arrow function returns expression result by default, but only without that {}
If you want to use {} remember to add return: (prev) => {return prev + 1}

A:  setClickCount((prev) => { return prev + 1})

you have to return a value for this to work

A: Either you use return statement for existing setClickCount or remove the arrow function and directly update the value.
 const increment = () => {
      setClickCount((prev) => {return prev + 1})
  }

or
const increment = () => {
      setClickCount(clickCount + 1)
  }

Jsfiddle link : https://jsfiddle.net/sureshpoosapati/85yhs4r1/1/


text:
Q: Matching lists in sql I am building a system that contains consultant profiles. In this system, each consultant can choose which certifications he or she has. Right now I am expanding the system to contain titles when a consultant has a certain set of certifications. The interesting tables is:
Person(stores ID, Firstname etc. of a person)

Certification(stores ID, Name of a certification)

PersonCertification(stores PersonID and CertificationID as a linking table (name?) )

Title(stores the title: ID, Shortname and Fullname)

TitleCertifications(stores which certifications is needed for a title)

As an example, say we have a title with ID 1 called MCSA. The certifications required for this title is certifications with ID 1 and 2. TitleCertifications-table could look like this:
TitleID | CertificationID
1       | 1
1       | 2

If a consultant has both certification with ID 1 and 2, he or she would be granted the title MCSA with ID 1. If the consultant does not have any of the certifications, he does not earn this title.
The problem I have is that I do not know how to check if the user has all the requred certifications that is defined in the TitleCertifications-table. i have started with this, but it lacks any check against if the person has all certifications that is needed.
SELECT t.Fullname
FROM Title t
JOIN TitleCertifications tc ON t.ID = tc.TitleID
JOIN PersonCertification pc ON tc.CertificationID = pc.CertificationID

The result of the query above will yield the titlename for each rows with a match on certification, as an example it will yield two rows if a user has two of the three required certifications to gain a title.
Does anyone know how to write a query that will match the required certifications and only give an answer if the user has all the required certifications for a title?
I am using a SQL Server 2012 using T-SQL (in Azure if that matters).
Sorry for writing kinds of fuzzy, I am not sure about all the terms in English.

A: Try this approach:
;with pc as (
    select p.personid, tc.titleid, count(*) as cnt_pc
    from person p
    inner join personcertification pc on p.personid = pc.personid
    inner join titlecertifications tc on pc.certificationid = tc.certificationid
    group by p.personid, tc.titleid
),
tc as (
    select t.titleid, count(*) as cnt_tc
    from title t
    inner join titlecertifications tc on t.titleid = tc.titleid
    group by t.titleid
)
select p.firstname, t.shortname
from pc
inner join tc on pc.titleid = tc.titleid
inner join person p on pc.personid = p.personid
inner join title t on pc.titleid = t.titleid
where cnt_pc = cnt_tc

The general idea is to select how many certs for a certain title is needed, and how many certs one have for that title -- if it's a match, than we assume that one has the title as well. Counting could be done in numerous ways.

A: There are a number of ways of doing this. Here is one:
select p.ID, p.Name, tcount.ID
from Person p
inner join
(
    -- Get the count of certs for each title for each person
    select pc.PersonID, t.ID TitleId, count(*) CertCount
    from PersonCertification pc
    inner join Certification c on c.ID = pc.CertificationID
    inner join TitleCertification tc on tc.CertificationId = c.ID
    inner join Title t on t.ID = tc.TitleID
    group by pc.PersonID, t.ID
) cntByTitle on cntByTitle.PerdonID = p.ID
left outer join
(
    select t.TitleID, count(*) CertCount
    from Title t
    inner join TitleCertification tc on tc.TitleId = t.ID
    group by t.ID
) tcount on tcount.TitleID = cntByTitle.TitleID and tcount.PersonID = p.ID
            and tcount.CertCount = cntByTitle.CertCount

Notes: the cntByTitle sub-query might need to be a left outer rather than an inner join: if a person has to Certs then I think they won't be returned by this unless you make it a left outer. I also assume all indexes are in place. If a Person has no Titles, the query will return the Person.ID and null.
You could wrap this up as a View and then just use the View in a more straight-forward query.

A: If you are using SQL Server 2012 you can use the IIF function for this.
SELECT IIF(TitleID = '1' AND CertificationID= '1', 1, 0) AS fullName, *
FROM   Title t

...? I Think :/
EDIT: the new CASE option
SELECT 'name'
CASE
WHEN TitleId = '1' AND CertificateId = '1' THEN MCSA = 1
ELSE MCSA = 0
END
FROM 'table'

A: COUNT(columnName) will not count nulls.
The following query uses left join to get nulls for certificates the person does not have
SELECT MAX(Title.FullName)
FROM Title
     INNER JOIN TitleCertifications
         ON TitleCertifications.TitleID = TitleCertifications.TitleId
     LEFT JOIN PersonCertifications
         ON PersonCertifications.CertificationId = TitleCertifications.CertificationId
WHERE PersonCertifications.PersonId = @Person
      AND TitleCertifications.TitleId = @Title
HAVING COUNT(TitleCertifications.CertificationId) = COUNT(PersonCertifications.CertificationId)

A: This should give you some direction sql fiddle link
    DECLARE @Person TABLE
(
    Id INT,
    FirstName VARCHAR (20)
)

DECLARE @Certification TABLE
(
    Id INT,
    CertificateName VARCHAR (20)
)

DECLARE @Title TABLE
(
    TitleId INT,
    Name VARCHAR (20)
)

DECLARE @TitleCertifications TABLE
(
    TitleId INT,
    CertificateId INT
)

DECLARE @PersonCertification TABLE
(
    PersonId INT,
    CertificateId INT
)

INSERT INTO @person VALUES (1, 'tyy'),(2,'Jon'), (3, 'James')

INSERT INTO @Certification VALUES (1, 'MSCA PreReq 1'),(2,'MSCA PreReq 2'),(3,'MSCC PreReq 1')

INSERT INTO @Title VALUES (1, 'MSCA'),(2,'MSCC')

INSERT INTO @TitleCertifications VALUES (1, 1),(1,2), (2,3)

INSERT INTO @PersonCertification VALUES (1, 1),(1,2), (2,1), (3,3)

SELECT * INTO #FlattenedTitleCerts
FROM
(SELECT g.TitleId, g.Name, STUFF( (SELECT ',' + CAST(CertificateId AS VARCHAR(10))
                              FROM @TitleCertifications v
                              WHERE v.TitleId = g.TitleId
                              ORDER BY CertificateId
                              FOR XML PATH('')),1, 1, '') Combination
FROM @Title g
) t

SELECT * INTO #FlattenedPersonCerts
FROM
(
    SELECT g.Id, g.FirstName, STUFF( (SELECT ',' + CAST(CertificateId AS varchar(10))
                                  FROM @PersonCertification v
                                  WHERE v.PersonId = g.id
                                  ORDER BY CertificateId
                                  FOR XML PATH('')),1, 1, '') Combination
    FROM @Person g
) t

--SELECT * FROM #FlattenedTitleCerts
--SELECT * FROM #FlattenedPersonCerts

--to get title
SELECT fpc.FirstName Name,
       ftc.Name Title
FROM #FlattenedPersonCerts fpc
LEFT JOIN #FlattenedTitleCerts ftc ON ftc.Combination = fpc.Combination

DROP TABLE #FlattenedTitleCerts
DROP TABLE #FlattenedPersonCerts


text:
Q: Jquery dynamic hide and show for drop down menu I am having trouble making my drop down menu dynamically show blocks of html code which are labelled style="display:none".
I have following code.

<form action="addQuestion.php" method="post">
  <select name="questiontype">
    <option name="questiontype" value="multiple" click="return showMultiple();">Multiple Choice< /option>
    <option selected name="questiontype" value="programming" click="return showProgramming();">Programming< /option>
</select>

<input type="hidden" name="course" value="'.$course.'" />

   Multiple

   Programming

</form>

i tried these functions to .show() the div's by id from the dropdown menu but no luck and I'm not sure what I'm doing wrong. I also removed some code in the div id blocks to make it easier to read.

A: demo
HTML
<select id="selectMe">
    <option value="multiple">multiple</option>
    <option value="programming">Programming</option>
</select>

   Multiple

   Programming

JS
$(document).ready(function () {
    $('.group').hide();
    $('#multiple').show();
    $('#selectMe').change(function () {
        $('.group').hide();
        $('#'+$(this).val()).show();
    })
});

A: In your select option you are using click instead of onclick event
<select name="questiontype">
    <option name="questiontype" value="multiple" onclick="return showMultiple();">Multiple Choice</option>
    <option selected name="questiontype" value="programming" onclick="return showProgramming();">Programming< /option>
</select>

And no need to use escape for single quotes,

   Multiple

   Programming

and in script tag
$('select[name="questiontype"]').change(function(){

A: Try this:
<form action="addQuestion.php" method="post">
            <select name="questiontype" id="questiontype">
                <option value="multiple">Multiple Choice</option>
                <option selected value="programming">Programming</option>
            </select>

                Multiple

                Programming

        </form>

Put this code in head section:


text:
Q: QString compare with digits I'm looking for a comparison function between QString that take in account digits.
For example:
std::vector<QString> init { "test22", "test4", "test1", "test10", "test2" };

If I use basic QString::compare, it sorts the list like:
"test1", "test10", "test2", "test22", "test4"

But I'd like the list to be sorted like:
"test1", "test2", "test4", "test10", "test22"

In Win32 API, it corresponds to the function StrCmpLogicalW, but I'm looking for the equivalent with QString.
Thanks in advance


text:
Q: Pandas strftime with 24 hour format QUESTION
How can I convert 24 hour time to 12 hour time, when the time provided is two characters long? For example: How to format 45 as 12:45 AM.
ATTEMPT
I can get most of the time conversions to format properly with the following:
df=df.assign(newtime=pd.to_datetime(df['Time Occurred'], format='%H%M').dt.strftime("%I:%M %p"))
df.head()

Date Reported   Date Occurred  Time Occurred    newtime
9/13/2010       9/12/2010       45          4:05 AM
8/9/2010        8/9/2010        1515        3:15 PM
1/8/2010        1/7/2010        2005        8:05 PM
1/9/2010        1/6/2010        2100        9:00 PM
1/15/2010       1/15/2010       245         2:45 AM

In the above the values in newtime are properly formatted, except where in the input time is "45" - that time had the result 4:05 AM. Does anyone know how to create the proper output?

A: to_datetime
times = pd.to_datetime([
    f'{h:02d}:{m:02d}:00' for h, m in zip(*df['Time Occurred'].astype(int).__divmod__(100))
])
df.assign(newtime=times.strftime('%I:%M %p'))

   Time Occurred   newtime
0             45  12:45 AM
1           1515  03:15 PM
2           2005  08:05 PM
3           2100  09:00 PM
4            245  02:45 AM


text:
Q: Deserializing objects sent through ObjectOutpoutStream I'm having issues while trying to receive a 2-d/ array of String through the ObjectOutputStream.
My code for sending the array is :
String [][] sendable = new String [n][5];
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
os.writeObject(sendable);

Assume my array is initialized with all the values, how can I unpack the received data back into a 2-d array ? My first approach was this but it's been causing problems as I'm relatively new to Java and socket programming.
ObjectInputStream ois =new ObjectInputStream(clientSocket.getInputStream());
String insa[][] = null;

try{
    insa= (String[][]) ois.readObject();
} catch (ClassNotFoundException ex){
    ex.printStackTrace();
}

System.out.println(insa[0][1]);

How can I retrieve the 2-d array sent as an object ?

A: *

*You need to construct the ObjectOutputStream before the ObjectInputStream, at both ends. Otherwise the peers can deadlock reading the object stream header.

*You need to construct both streams once for the life of the socket, not once per send or receive.

A: I suggest flushing os after writing sendable:
os.writeObject(sendable);
os.flush();

You probably also want to call os.flush() immediately after constructor as recommended by official docs:

Creates an ObjectOutputStream that writes to the specified OutputStream. This constructor writes the serialization stream header to the underlying stream; callers may wish to flush the stream immediately to ensure that constructors for receiving ObjectInputStreams will not block when reading the header.

See http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#ObjectOutputStream%28java.io.OutputStream%29


text:
Q: Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible? Given two lists/vectors, one of which is a subset of another, how can I align them in the most efficient way possible? For context, I'm slicing a matrix (in C++) and I need to also slice the labels. Since these lists will be labels they should be considered unique within the list.
import unittest
from typing import List, Tuple

def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
    pass

#The elements in the lists are labels, so they should be unique - i.e. we won't
# ever have [5, 5, 6, 7, 8].

class AlignTests(unittest.TestCase):

    def test1(self):
        v1 = [1, 2, 3, 4, 5, 6]
        v2 = [1, 2]
        first, last = doAlignment(v1, v2)
        self.assertEqual((0, 1), (first, last))

    def test2(self):
        v1 = [1, 2, 3, 4, 5, 6]
        v2 = [2, 3, 4]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 3), (first, last))

    def test3(self):
        v1 = [7, 3, 4, 6, 9]
        v2 = [3, 4, 6]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 3), (first, last))

    def test4(self):
        v1 = [7, 3, 4, 6, 9]
        v2 = [3, 4, 6, 9]
        first, last = doAlignment(v1, v2)
        self.assertEqual((1, 4), (first, last))

A: As the values in list1 are unique, just get the index of the first item of list2 to get the the first tuple value, add len(list2)-1 for the second:
def doAlignment(list1: List[int], list2: List[int]) -> Tuple[int, int]:
    a = list1.index(list2[0])
    return (a, a+len(list2)-1)

example:
>>> doAlignment([7, 3, 4, 6, 9], [3, 4, 6, 9])
(1, 4)


text:
Q: url for getintent in watson assistance returns Resource not found Please help I am unable to consume this API service for getting Intent using the source code below,
var assistant = new watson.AssistantV1({
    username: '********',
    password: '******',
    url:'https://gateway.watsonplatform.net/assistant/api/v1 /workspaces/{workspaceid}  /message?version=2018-09-20',
    version: '2018-02-16'});

assistant.getIntent({
   intent: "Hello",
   workspace_id: '******'}, function(err, response){
   if(err){
      console.error(err);
   }else {
      console.log(JSON.stringify(response, null, 2));
   }
});

The return error message is
Error: Resource not found
code: 404,
error: 'Resource not found',
'x-global-transaction-id': 'ffea405d5c4ef5012b3fd98b'

A: Maybe it is just that trivial, but the URI has illegal spaces? Have you tried this?
url:'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/{workspaceid}/message?version=2018-09-20'

A: If you are using the SDK, then your url value should point to the API version only.
For example:
url:'https://gateway.watsonplatform.net/assistant/api/v1'

If it is still the same error, then you need to ensure you are using the right end point for where your Watson Assistant is hosted.
Latest details here: https://console.bluemix.net/apidocs/assistant#service-endpoint
Summary:

*

*Dallas: https://gateway.watsonplatform.net/assistant/api

*Washington, DC: https://gateway-wdc.watsonplatform.net/assistant/api

*Frankfurt: https://gateway-fra.watsonplatform.net/assistant/api

*Sydney: https://gateway-syd.watsonplatform.net/assistant/api

*Tokyo: https://gateway-tok.watsonplatform.net/assistant/api

*London: https://gateway-lon.watsonplatform.net/assistant/api

A: There are all sorts of errors in your small snippet of code as @Simon O'Doherty and @data_henrik have pointed out. It looks like you are coding in Node.js so this reference to the API documentation will help.
https://cloud.ibm.com/apidocs/assistant?language=node#get-intent
In summary

*

*You have the URL wrong

*I am guessing that you are using a new instance of Assistant, in which case your credentials will be an IAM Key rather than a username / password credentials

*If you are running getIntent then you need to provide the identifier for the Intent that you are retrieving, is this really 'Hello' or is that a copy from somewhere else? If you run listIntents that will provide you with an indication of its real identifier.


text:
Q: What should be the file folder structure in Codeigniter with Angularjs I have just started to work on an app in Codeigniter with AngularJS. I want to use font-awesome offline but can't make it to work.
I suspect the file folder structure of my application which is:
CI-AJS-APP
 -app
 -application
 -assets
  -css
  -font-awesome
   -font-awesome.css
   -font
  -js
 -system
 ...

Now in my font-awesome.css file I have a reference to the fonts folder as:
@font-face {

    font-family: "FontAwesome";
    src: url('font/fontawesome-webfont.eot');
    src: url('font/fontawesome-webfont.eot?#iefix') format('eot'),
    url('font/fontawesome-webfont.woff') format('woff'),
    url('font/fontawesome-webfont.ttf') format('truetype'),
    url('font/fontawesome-webfont.svg#FontAwesome')
    format('svg');
    font-weight: normal;
    font-style: normal;

          }

In my application header I have included the font-awesome.css file as:
<link rel="stylesheet" href="<?php echo base_url();?>assets/
font-awesome/font-awesome.css">

I have not fully integrated AngularJS in CI however just for a page or two on which I want to show the font-awesome icons.
Any kind of help will be much appreciated.

A: Well I have found that file structure is alright. The reason for the problem was that I was using ng-class the wrong way.
This is what I was doing...
ng-class="{{fa fa-sort-asc}}"

But I found that the correct way to achieve this is...
ng-class="{{'fa fa-sort-asc'}}"

Notice the missing single quotes with the classname in the former code.
So, this mistake was not displaying the font-awesome icon at all in the browser.
Hope will be helpful to some out there :-).


text:
Q: Config file not being loaded in game I have edited my config.ini file in C:\Riot Games\League of Legends\Config to set my left click to attack move click, based on this reddit post.
When I go into a game, none of my changes to the file work. When I look at the settings in game, it simply ignores the file completely. It is as if it doesn't look at the file unless it is edited in game. How can I force it to load the changes to the config file?
I have tried changes settings in game and saving them, in the hope that it would load the rest of the saved settings in the file, but this does not work.

A: The simple answer is, it doesn't work anymore.
The long answer requires researching all the patches over the last 2 years (the age of the quoted post), and then figuring out when the INI options were changed/disabled.  I'll post this as an incomplete answer for now, but the 2 year old post is not reliable and you should look into newer tutorials.
EDIT:
Sometime around 2011 there seems to be some changes to how the INI was accessed.
http://forums.euw.leagueoflegends.com/board/showthread.php?t=189212&page=1
But that's pretty old still, even older than your post, but it is only a reference that the client can and does change its way of accessing the INI files.
The LoL Wiki has more details:
http://leagueoflegends.wikia.com/wiki/Hotkeys_and_commands
But it also may not be 100% accurate.

A: This is a little tedious however it works I have tested it multiple times.

*

*Login and stay on the lol client window.

*While the lol client is open (very important) open the lol config folder and delete "input.ini" and "PersistedSettings.json"

*Copy an edited "input.ini" into the config folder and start a custom game to commit the settings on the server side.

For anyone who does not have the settings: League Config
Both the default and left mouse click can be found there
related to the question but not useful to the solution
The reason why it was changed was so riot could track people who use multiple accounts, so keep that in mind before you use a friends account you could easily get them banned if you make these changes as they would check if it matches other users there is also another file in this folder

C:\Riot Games\League of
Legends\RADS\projects\lol_air_client\releases\0.0.1.187\deploy\preferences

that riot uses to track user configurations.

A: Looks like there's some kind of persistent setting file that needs to be deleted. I don't know if this fix still works, since I can't check on it, but it apparently worked as of 6 months ago.
From the thread:

Was having same problem
  removed the "persisent setting" file. works fine now
  no problems either

I have the answers to your problem. You have to go into persistent settings and find the certain key your trying to change. such as in my case I had to change evtAttackMoveClick with the button I wanted to set it to and save. Input.ini no longer overides league systems. You have to change it through Persistent Settings. Hope this helped.


text:
Q: MySQL data recovery with INNODB Recently our server got shutdown unexpectedly and next time when I tried to start mysql it was giving error. We did not have any data backup, so we just copied our data folder to some safe location. I have ib log files and ib data files along with all the database names with frm and ibd files. How can I restore my databases?
I can see my database and table names in MySQL Workbench, but when I query the table, it says that the table does not exist.

A: These steps helped me in a very similar case:

*

*Set innodb_force_recovery = 1 in the my.cnf configuration to forcibly start InnoDB. Don't forget to actually (re)start the service. MySQL should be running now.

*Use mysqldump to create an SQL dump

*(Optionally) Use pt-show-grants to additionally dump grants

*Reinstall the database, or delete ibdata and ib_logfile files (see https://dba.stackexchange.com/questions/23361/innodb-force-recovery-when-innodb-corruption)

*Import both SQL dumps: the actual database dump, and the grants dump


text:
Q: How to externalize configurations with spring.config.additional-location? I added the following property into my application.properties to separate sensitive account infos from the main application.
#/src/main/resources/application.properties
spring.config.additional-location=/etc/java/myapp/

spring.datasource.url=jdbc:mysql://localhost/mytable

Additional:
#/etc/java/myapp/application.properties:
spring.datasource.username=theuser
spring.datasource.password=thepw

Result: the properties are not found!
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
What am I doing wrong here?
Sidenote: if I add default values, the problem remains. The properties are not overridden!
spring.datasource.username=replaceme
spring.datasource.password=replaceme
Result:
java.sql.SQLException: Access denied for user 'replaceme'@'localhost' (using password: YES)

A: Note : from doc, from spring boot 2.0 spring.config.location upgraded to spring.config.additional-location
Command line : java -jar name --spring.config.additional-location=/etc/java/myapp/
spring.config.name and spring.config.location are used very early to determine which files have to be loaded, so they must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument).


text:
Q: set_exception_handler tries to catch Error Here is the code I use to catch at the global level missed exceptions and errors:
set_exception_handler( function( Exception $e ) {
    $exceptionCode = $e->getCode();

    switch ( $exceptionCode ) {
        case '42000': # Database
            FlashMessages::flashIt( 'message', 'There is a syntax error in the db query' );
            include( Settings::ABSPATH . '/src/views/message.php' );
            var_dump( $e );
            exit;
            break;
        default:
            FlashMessages::flashIt( 'message', 'Something unpredicted happened.' );
            include( Settings::ABSPATH . '/src/views/message.php' );
            var_dump( $e );
            exit;
            break;
    }
} );

set_error_handler( function( $errno, $errstr, $errfile, $errline ) {
    FlashMessages::flashIt( 'message', 'An error happened.' );
    include( Settings::ABSPATH . '/src/views/message.php' );
    var_dump( $errstr );
    exit;
} );

What I expected:
All exceptions caught by set_exception_handler.
All errors caught by set_error_handler.
What I have: set_exception_handler tries to catch errors and generate problems: Fatal error: Uncaught TypeError: Argument 1 passed to {closure}() must be an instance of Exception, instance of Error given
set_error_handler doesn't catch this kind of error even if I completely remove the set_exception_handler.
Question: how can I catch from those global functions the kind of error that is missed by both of these function ?

A: Change exception handler param type from Exception to Throwable.
http://php.net/manual/en/function.set-exception-handler.php#refsect1-function.set-exception-handler-changelog


text:
Q: Spilt a string into half and join it with another string I wanna ask if say i have a string "abcdefgh" and I want to half it to become "abcd" and "efgh" and store it into their own strings say I call it "UpperHalf" and "LowerHalf". So the way to do this is to first make use of the strlen() to find out the length of my input and half it? Then I would need to use strcpy() and copy it to their respective strings right?
Actually I don't even know if my code makes any sense. Anyone can give me some comments on it?
I realized I only need to consider even input numbers which means I do not need to worry about odd inputs. Previously I was trying to spilt a 1d string into half and then strcat it with something else. But now I am given a series of input strings that are stored in 2d array format. In this case, how do I retrieve these strings and manipulate them as though it is the same as the previous 1d case? I don't think I need to use for loops? Can I just point to the row?
int d = strlen(str); // just an example where str = the characters inside my string
strcpy(temp, &str[0]); // store original string into a temp string starting from 0 to \0
str[d/2] = '\0';
strcpy(UpperHalf, &str[0]); // starts copying from position 0 to \0 which is the half way point
str[0] = temp;  //revert back to normal -> Does this line even make sense?
strcpy(LowerHalf, &str[d/2]);

A: Yes you definitely need to consider the odd number string lengths.  There are code approaches which will either round it up or down (so that the first or second string will have the extra character) but you need to decide which way you want it to go.
Looking at your code, I would suggest that using the temp string is not needed.  You can copy directly from the original 'str' and save that memory and processor overhead.  A few changes will be needed:
Currently you're overwriting one of the characters in your source string with the '\0' character, and your second strcpy is starting at that '\0' which will return a zero length string.
To copy a fixed number of characters, you can use strncpy which will work better here than strcpy by simplifying your code and keeping things clear.
Don't forget to terminate your strings with a \0, or you could initialise the buffers with 0 values as I have here.
So, an example might look like this:
char UpperHalf[MAX_LENGTH];
char LowerHalf[MAX_LENGTH];

int l = strlen(str);
int half = l / 2;
memset(LowerHalf, '\0', MAX_LENGTH);
strncpy(LowerHalf, str, half);
memset(UpperHalf, '\0', MAX_LENGTH);
strncpy(UpperHalf, str + half, l - half);

This will put the longer part of an odd length string into the UpperHalf char array.
To make the code safe you should also consider doing length comparisons to ensure that all strings will fit in the buffers provided (with at least one character left over for the string terminating \0 character).

A: Yes, you must first use strlen to get the length of the input string, and halve it to give the length of upper_half:
size_t length = strlen(str);
size_t upper_length = length / 2;
size_t lower_length = length - upper_length;

In this case, if the length of the input string is odd, then due to integer division, upper_length will equal lower_length - 1, e.g.:
length == 3
upper_length == 3 / 2 == 1
lower_length == 3 - 1 == 2

It's easier to do the actual copying without modifying the original string, as your code is doing.
You must allocate space to store the copies of the string halves, with null terminators:
char *upper_half = malloc(upper_length + 1);
char *lower_half = malloc(lower_length + 1);

Then use memcpy to copy the string data:
memcpy(upper_half, &str[0], upper_length);
upper_half[upper_length] = '\0';

(Similarly for lower_half.)
strcpy copies characters until a null byte, while memcpy copies a given number of bytes.

A: While it is fine to use all the standard functions to copy the lower/upper halves to separate strings, you can also split the string using only pointers and a separate buffer to hold the lower-half of the string.
Basically, you can find the length of the string, adjust the odd/even location of the midpoint (if desired to always but the additional char on odd lengths in the lower-half), and then use a simple loop to copy to lower-half. At the end of the loop, the pointer used points to the upper-half (or you can simply use the pointer for the location of the midpoint). A short example would be:
#include <stdio.h>

#define MAXC 64

int main (int argc, char **argv) {

    if (argc < 2 ) {
        fprintf (stderr, "error: insufficient input, usage: %s string\n",
                argv[0]);
        return 1;
    }

    char lower_half[MAXC] = {0};    /* array to hold lower_half */
    char *p = argv[1];              /* poiter to string         */
    char *pl = lower_half;          /* pointer to lower_half    */
    char *split = NULL;             /* pointer to split point   */
    size_t len = 0;                 /* string length            */

    for (; *p; p++);        /* find end of string   */
    len = p - argv[1];      /* get string length    */
    p = argv[1];            /* reset pointer        */
    split = p + len/2;      /* set split at middle  */
    if (len & 1) split++;   /* if odd, add 1        */

    for (; p < split; p++)  /* for each ch < split  */
        *pl++ = *p;         /* copy to lower_half   */
    *pl = 0;                /* null-terminate       */

    /* print results */
    printf ("\n lower_half : '%s'    upper_half : '%s'\n",
            lower_half, split);

    return 0;
}

Output
$ ./bin/str_half 123456789

 lower_half : '12345'    upper_half : '6789'

$ ./bin/str_half 1234567890

 lower_half : '12345'    upper_half : '67890'

Regardless of whether you use pointers or use strlen, strncpy, or memcpy, etc., just be sure you null-terminate the separated strings. Above, the explicit null-termination is not required due to lower_half being initialized to all 0 at the beginning. However, it is good practice to always insure your code is null-terminating your strings.


text:
Q: uploading files in ASP.NET MVC When I select a file and submit the file for upload, I can't get the value of the File path in my Model. In the Controller it shows as null. What am I doing wrong?
View
<form method="post" action="/Account/Profile" enctype="multipart/form-data">
    <label>Load photo: </label>
    <input type="file" name="filePath" id="file" />
    <input type="submit" value="submit" />
</form>

Controller
public ActionResult Profile(ProfileModel model, FormCollection form)
{
    string path = Convert.ToString(model.FilePath);
    return View();
}

Model
public HttpPostedFileBase FilePath
{
    get
    {
        return _filePath;
    }
    set
    {
        _filePath = value;
    }
}

public bool UploadFile()
{
    if (FilePath != null)
    {
        var filename = Path.GetFileName(FilePath.FileName);
        FilePath.SaveAs(@"C:\" + filename);
        return true;
    }
    return false;
}

A: I don't think model binding works with HttpPostedFileBase...
It should work if you take it out of your ViewModel and do it like this:
public ActionResult Profile(HttpPostedFileBase filePath)
{
    string path = Convert.ToString(filePath);
    return View();
}

HTHs,
Charles
Ps. This post could help explain things: ASP.NET MVC posted file model binding when parameter is Model

A: I don't have VS to simulate your problem. So im not sure bout the answer.
Try this, might work
<input type="file" name="model.FilePath" id="file" />

If not work then,
Try look it on your formcollection & HttpContext.Request.Files
It should be there.

A: Instead of using HttpPostedFileBase I would use IFormFile
public class ModelFile
{
     .....
     public string Path{ get; set; }
     public ICollection<IFormFile> Upload { get; set; }
}

public async Task<IActionResult> Index([Bind("Upload,Path")] ModelFile modelfile)
{
     ...
     msg = await storeFilesInServer(modelfile.Upload,modelfile.Path);
}

private async Task<Message> storeFilesInServer(ICollection<IFormFile> upload, string path)
        {
            Message msg = new Message();
            msg.Status = "OK";
            msg.Code = 100;
            msg.Text = "File uploaded successfully";
            msg.Error = "";
            string tempFileName = "";
            try
            {
                foreach (var file in upload)
                {
                    if (file.Length > 0)
                    {
                        string tempPath = path + @"\";
                        if (Request.Host.Value.Contains("localhost"))
                            tempPath = path + @"\";

                        using (var fileStream = new FileStream(tempPath + file.FileName, FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                            tempFileName = file.FileName;
                        }
                    }
                    msg.Text = tempFileName;
                }
            }
            catch (Exception ex)
            {
                msg.Error = ex.Message;
                msg.Status = "ERROR";
                msg.Code = 301;
                msg.Text = "There was an error storing the files, please contact support team";
            }

            return msg;
        }


text:
Q: C execlp() not correctly parsing parameters string I'm building a shell for an Operating Systems class that must use exec() or one of its variants to execute external commands. Currently, I'm using execlp(command,command_parameters, (char *) NULL). This runs the command just fine (e.g. ls returns a standard directory listing), but doesn't seem to parse any of the parameters (e.g. running mkdir hello throws an error "hello: missing operand... Try 'hello --help' for more information). What am I missing?
            else // Try to handle an external command
        {
            char *command_parameters = malloc(sizeof(raw_command)-sizeof(command));
            strcpy(command_parameters, raw_command+strlen(command)+1);
            pmesg(1, "Command is %s.\n", command);
            pmesg(1, "The command parameters are %s.\n", command_parameters);
            pid_t pid = fork();
            pmesg(1, "Process forked. ID = %i. \n", pid);
            int status;
            if (fork < 0)
            {
                printf("Could not fork a process to complete the external command.\n");
                exit(EXIT_FAILURE);
            }
            if (pid == 0) // This is the child process
            {
                pmesg(1, "This is the child process, running execlp.\n");
                if (execlp(command, command_parameters, (char *) NULL) < 0)
                {
                    printf("Could not execute the external command.\n");
                    exit(EXIT_FAILURE);
                }
                else    { pmesg(1, "Executed the child process.\n"); }
            }
            else {while(wait(&status) != pid); } // Wait for the child to finish executing
            pmesg(1, "The child has finished executing.\n");
        }

(pmesg is a debug tag that prints the statement given a certain debug level).
Thanks!

A: A couple of issues here:

*

*execlp( const char *file,  const char *arg, ...) expects the arguments to be split up and passed separately, not as one big string.

*The first arg (after const char *file) is by convention, the name of the executable you're running, which gets put into argv[0] in the called program.  The first parameter, thus, will need to go after that.

e.g.:
execlp( command, command, arg1, arg2, ..., (char *)NULL );

With what you have, doing it like:
execlp( command, command, command_parameters, (char *)NULL );

will probably, as-is, take care of your issue with "mkdir", "hello", but you're still not splitting the command_parameters string up, so it won't work without modification for commands with more than one argument.
EDIT: P.S. Your line
if (fork < 0)

should be
if (pid < 0)


text:
Q: How to change bottom line color of an edit text? I have a dialog layout in that i have 3 edit texts, for the 1st edit text it shows the underline color as green(primary color), and other two edit text shows the color pink(color accent).

Why so? It should be same as other two edit texts.
Tried to change this with :
 name.getBackground().mutate().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
                name.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);

also by the SO solutions. But nothing helped.
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">

        ....
        <item name="android:editTextStyle">@style/EditTextStyle</item>
</style>

<style name="EditTextStyle" parent="Widget.AppCompat.EditText">
         <item name="colorControlNormal">@color/border_gray</item>
         <item name="colorControlActivated">@color/border_gray</item>
         <item name="colorControlHighlight">@color/border_gray</item>
</style>

layout :
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <LinearLayout android:layout_height="50dp"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Schedule"
            android:textColor="@android:color/white"
            android:textAppearance="@android:style/TextAppearance.Medium"
            android:layout_gravity="center"
            android:layout_marginLeft="20dp" />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp">

        <EditText
            android:id="@+id/edt_name"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:textColor="#000000"
            android:textSize="14sp"
            android:inputType="textCapSentences"
            android:hint="Name"
            android:cursorVisible="false"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp" />

        <EditText
            android:id="@+id/edt_dateTime"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:textColor="#000000"
            android:textSize="14sp"
            android:cursorVisible="false"
            android:inputType="textCapSentences"
            android:hint="Date and Time"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/edt_name"
            android:layout_alignStart="@+id/edt_name"
            android:layout_below="@+id/edt_name"
            android:layout_alignRight="@+id/edt_name"
            android:layout_alignEnd="@+id/edt_name"
            android:layout_marginTop="05dp" />

        <EditText
            android:id="@+id/edt_budget"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:textColor="#000000"
            android:textSize="14sp"
            android:cursorVisible="false"
            android:hint="Budget"
            android:layout_below="@+id/edt_dateTime"
            android:layout_alignLeft="@+id/edt_dateTime"
            android:layout_alignStart="@+id/edt_dateTime"
            android:layout_alignRight="@+id/edt_dateTime"
            android:layout_alignEnd="@+id/edt_dateTime"
            android:layout_marginTop="05dp"
            android:inputType="number" />

    </RelativeLayout>

</LinearLayout>

This is what i got after implementing drawable.

Thank you..

A: It simply consists of overriding the value for colorControlActivated, colorControlHighlight and colorControlNormal in your app theme definition
<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">#c5c5c5</item>
        <item name="colorControlActivated">@color/accent</item>
        <item name="colorControlHighlight">@color/accent</item>
    </style>

or by java
editText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_ATOP);

A: by changing your "colorAccent" color you will change color or edittext bottom line and text input layout as well.

A: Create textfield_bg_drawable.xml in drawable folder. and set it as background resource in EditText.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="2dp"
        android:left="-2dp"
        android:right="-2dp"
        android:top="-2dp">
        <selector>
            <item
                android:state_enabled="true"
                android:state_focused="true">
                <shape android:shape="rectangle">
                    <stroke
                        android:width="2dp"
                        android:color="@color/focused_line_color" />
                </shape>
            </item>
            <item android:state_enabled="true">
                <shape android:shape="rectangle">
                    <stroke
                        android:width="1dp"
                        android:color="@color/normal_line_color" />
                </shape>
            </item>
        </selector>
    </item>
</layer-list>

A: Try with this following code properly working on my side
        Drawable drawable = editText.getBackground(); // get current EditText drawable
        drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP); // change the drawable color

        if (Build.VERSION.SDK_INT > 16) {
            editText.setBackground(drawable); // set the new drawable to EditText
        } else {
            editText.setBackgroundDrawable(drawable); // use setBackgroundDrawable because setBackground required API 16
        }

Where editText is the id of your EditText

A: I think it is because Your 1st editText focusing, when your alert layout appear.
add this line in your editText
android:focusable="true"

A: You need to disable focus from your first edittext when the activity is opened, so set
android:requestFocus= "false"
in your xml file. Or try the following
edittext.clearFocus();
in your java file.
It will not pick your primary color then.
Hope it works!


text:
Q: Getting Synax error: SyntaxError unexpected token in json at position 2 aws-lambda Through Bitbucket, I'm passing an environmental variable object through the development tab that looks similarly to:
{ "var1": "tets.var.com",   "port": "34",   "username": "john",   "password": "pass", "env": "dev" }
I am also passing these variables through my Bitbucket pipeline as:
npx cdk deploy app --require-approval never -c credentials="$BITBUCKET_CRED"
However, when invoking my lambda with the credentials, I am getting the error:
"SyntaxError: Unexpected token \\ in JSON at position 2"

A: My problem was that the object I passed in was too long, hence the "//" in the response. I'm assuming the "//n" was left off


text:
Q: Bit stuffing in CAN bus How does the receiving node (CAN bus) know that a bit stuffing is not an actual bit part of the data?
Check this example below. Both are valid streams, but they have different contents:
Valid - Bit stuffed stream (my stuffed zero in bold)

11111010101

Valid - Not bit stuffed stream

11111010101

A: You misunderstood the stuffing concept.
Because there are additional bits stuffed in the data stream.
The sender and the receiver know by rule, that after five zeros or five ones the next bit will be an alternated stuffing bit and no data.
Stuffed after five equal bits

111110010101

Without stuffing:

11111010101

So a message with alternating bits will be shorter on the bus, because there are no additional stuffing bits needed.
The stuffing is needed because CAN is an asynchronous bus and it needs a falling or rising edge every five bits for clock resynchronisation between the different CAN controllers.
If the stuffing would start after three bits for example, you could use oscillators on the different controllers with higher tolerances. But this would increase the stuffing overhead and vice versa.
So five bits is kind of a trade-off.


text:
Q: Validated Textbox in a UserControl I have created a UserControl - a Labeled TextBox which is working pretty well, except for the validation template. When there's an error the validation control template shows up but it fills the whole space including the Label. I only want it to be as big as the TextBox. How to fix this?
Here's the xaml:
<UserControl x:Class="Infrastructure.CustomControls.LabelTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="LTB">

    <Grid HorizontalAlignment="{Binding}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBlock x:Name="tbl"
                   FontFamily="{Binding}"
                   FontSize="{Binding}"
                   Text="{Binding ElementName=LTB, Path=LabelText}"
                   Height="{Binding ElementName=LTB, Path=LabelHeight}"
                   Width="{Binding ElementName=LTB, Path=LabelWidth}"
                   VerticalAlignment="Center"/>
        <TextBox x:Name="tbx"
                 Grid.Column="1"
                 FontFamily="{Binding}"
                 FontSize="{Binding}"
                 IsReadOnly="{Binding ElementName=LTB, Path=IsReadOnly}"
                 MaxLength="{Binding ElementName=LTB, Path=TextMaxLength}"
                 Text="{Binding ElementName=LTB, Path=Text}"
                 Height="{Binding ElementName=LTB, Path=TextHeight}"
                 Width="{Binding ElementName=LTB, Path=TextWidth}"
                 VerticalAlignment="Center">
            <Validation.ErrorTemplate>
                <ControlTemplate>
                    <DockPanel LastChildFill="True"
                               ToolTip="{Binding ElementName=aep, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                        <TextBlock DockPanel.Dock="Right"
                                   Foreground="Red"
                                   FontSize="14pt" Text="*"
                                   Margin="-15,0,0,0"
                                   FontWeight="Bold"/>
                        <Border BorderBrush="Red" BorderThickness="1">
                            <AdornedElementPlaceholder Name="aep"/>
                        </Border>
                    </DockPanel>
                </ControlTemplate>
            </Validation.ErrorTemplate>
        </TextBox>
    </Grid>
</UserControl>

A: The reason why this happens is that you're implementing IDataErrorInfo in your view and not your UserControl. This causes the default WPF red border to appear for the entire usercontrol.
To get your defined error template to appear, you'll need to implement IDataErrorInfo in your usercontrol and add ValidatesOnDataErrors=True to your binding expression.
If you'd like to keep the IDataErrorInfo logic in your view and not in your UserControl (which is pretty reasonable), you'll need to define a validation template for the user control in the view:
<Window>
    <local:UserControl>
        <Validation.ErrorTemplate>
            <ControlTemplate>
                ...
            </ControlTemplate>
        </Validation.ErrorTemplate>
    </local:UserControl>
</Window>

To get it to only show the border for the TextBox, you can play with the border's width using a converter that'll take the entire usercontrol's width as a parameter and return the width of the textbox; possibly something like this:
<Border BorderBrush="Red" BorderThickness="1" Width="{Binding ElementName=ph, Path=ActualWidth, Converter={StaticResource myConverter}}">
    <AdornedElementPlaceholder Name="ph" />
</Border>

A: Thanks for the response, it helped me figure out where the problem is. And for that i vote it as useful.
What i did was programmatically query the UserControl validation for errors in the TextBoxChangedEvent and set the validation error manually (http://wpftutorial.net/ValidationErrorByCode.html) for the TextBox.


text:
Q: How to migrate Ubuntu12.04 to LVM without any data loss The current system is installed on the traditional disk, now I want to migrate it to LVM managed disk, how can I migrate it without any data loss?
I'm working with vSphere, so I can add and remove disk easily, change system to another virtual disk and rebooting are acceptable.
Is there someone can help me? Thank you!

A: To my knowledge it has no real easy way. I've done this operation by making a backup / restore from a partition to another.
Have you watched the btrfs file system that provides some similar functionality to LVM ? I recently installed a machine with this file system and I'm very happy. In addition, there are commands to convert ext4 to btrfs.


text:
Q: Ownerdrawn tray icon (winapi)? Is it possible to make an ownerdrawn tray icon using winapi ? ( c++ non-mfc.)
For now im using server generated png -> ico -> tray but this is ugly and slow ......

A: You could just dynamically create the HICON, no?   Build up the image that you want (or convert from jpg/bmp/png) as a DIB and convert to an HICON.  Use your created icon to send to Shell_NotifyIcon().
Old reference, but it should get you started.   Icons in Win32.


text:
Q: How can I prevent a re-start of my app when the phone is rotated? In my app I don't want to restart a media player once it starts if the user rotates the phone. How can I prevent a re-start of my app when it is rotated because it stops the running sound file that is playing?
Please show me the code I need to add and where to add it.
Thanks.
Truly,
Emad

A: use this
  <activity android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:name="VncCanvasActivity">

see this

A: You have to redesign your application to play the music from a service instead of from your main activity. Your main activity can at any time be killed by the operating system if it decides it needs memory.
See What is a service


text:
Q: Layout of three JPanels in A JFrame I have one Object-Jpanel and two Jpanel in Jframe how to add this object in to two jpanel in Jframe. I tried and just one of them add this object
add one panel-object into three frame how to do that?
I've tried and just one of them added this object.
    pnmnf = new pnlMemuFilm(pnlRoom1.getX() * 25 / 100, pnlRoom1.getHeight());
    pnmnf.setBounds(pnlRoom1.getX() * 75 / 100, 0, pnlRoom1.getX() * 25 / 100, pnlRoom1.getHeight());
    tbMovieSchedule = new Table();
    tbMovieSchedule.setBounds(0, 0, x * 75 / 100, y * 30 / 100);

    tbMovieScheduleTemp = new Table();
    tbMovieScheduleTemp.setBounds(0, y * 70 / 100, x * 75 / 100, y * 30 / 100);

    pnlRoom1.add(tbMovieScheduleTemp);
    pnlRoom2.add(tbMovieScheduleTemp);
    pnlRoom3.add(tbMovieScheduleTemp);

    pnlRoom1.add(tbMovieSchedule);
    pnlRoom2.add(tbMovieSchedule);
    pnlRoom3.add(tbMovieSchedule);

    pnlRoom1.add(pnmnf);
    pnlRoom2.add(pnmnf);
    pnlRoom3.add(pnmnf);


text:
Q: Inline onchange script to external JS I have a form selector element, which has an inline script following onchange:
<select onchange="this.className=this.options[this.selectedIndex].className">
     <option value="select">Select color</option>
     <option class="greenOpt" value="green" >Green</option>
    <option class="yellowOpt"   value="yellow" >Yellow</option>
    <option class="blueOpt" value="blue" >Blue</option>
</select>

This works perfectly for my output, changing the background color of the options the same color as their word, Green is green, Yellow is yellow, etc.
.greenOpt{
background-color: green;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

.blueOpt{
  background-color: blue;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
  }

.yellowOpt{
  background-color: yellow;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

But I want to move that onchange script into an external function and I am unsure of how that should look.  I understand what I need to do in the <select> tag, is onchange="colorSel()"
My function so far:
function colorSel() {
  var colors = document.getElementById("colors");
  colors = this.className = this.options[this.selectedIndex].className;
  }

I am stumped.  I have changed the parameter the of the function and the getElement type to many different things.  I just don't get it.

A: You need to attach a handler for the change event
document.getElementById("colors").addEventListener('change', function (){
//Your logic goes here
});

A: You have not provided the code for the colors element, so I have demonstrated something with what you have given:

change = function(selectObject) {
   selectObject.className= selectObject.options[selectObject.selectedIndex].className
}
.greenSel{
  background-color: green;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

.blueSel{
  background-color: blue;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
  }

.yellowSel{
  background-color: yellow;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
<select onchange="change(this)">
    <option value="select">Select color</option>
    <option class="greenSel" value="green" >Green</option>
    <option class="yellowSel"   value="yellow" >Yellow</option>
    <option class="blueSel" value="blue" >Blue</option>
</select>

You missed passing in this to your onchange method and grabbing the value from the selected choice.


text:
Q: React Country -> Province/State -> City selector? I feel like this is pretty common that people want a selector that when you pick a country it narrows down province/states to that country then you pick state or province and it narrows down the city for you. Is there nothing on NPM for that? I saw country selector and country-province but nothing that goes from country to city. If nothing exists should I store all those in the DB or front-end? I'm assuming DB.

A: You could use either of the two libraries.

*

*https://github.com/country-regions/react-country-region-selector [React Component -> Provides Country and State]

*https://www.npmjs.com/package/country-state-city, [Standalone Library which provides Country -> State -> City]

If you want to store the data and search results on your own, i would suggest you to stored it in a DB, loading the data on frontend would be expensive on network.

A: You can use this React component react-places-autocomplete based on Google Places API.

A: I would recommend using react country-state-city, but it consumes lot of space.


text:
Q: Jave, I am trying to save a binary search tree to a file and restore, so it would save the info even after program terminated All i am trying to use call these two methods restore and save to obviously save a binary search tree to a file after an interface of ADD, DELETE, FIND... and process() is the method to process these operations. how ever I am trying to work on these two restore and save.
I am totally lost on how to implement this solution i found:
http://leetcode.com/2010/09/saving-binary-search-tree-to-file.html
                     private Menu() {
                Interface_1();
            // restore();
            process();
            // save();
               }

    private BinarySearchTree<Person, String> phoneBook;

     private void add(String takeName, String takePhone) {
            if (pBook.add(takeName, takePhone)) {
            System.out.println(String.format("add(%s, %s) Operation Succeded.",
                            takeName, takePhone));
                    } else {
                        System.out.println(String.format("add(%s, %s) Operation Failed.",
                    takeName, takePhone));
    }
}

           private void add(String takeName, String takePhone) {
    if (pBook.add(takeName, takePhone)) {
        System.out.println(String.format("add(%s, %s) Operation Succeded.",
                takeName, takePhone));
    } else {
        System.out.println(String.format("add(%s, %s) Operation Failed.",
                takeName, takePhone));
    }
}

A: Pardon my understanding, but is the problem that you are facing is how to reconstruct your tree elsewhere? If it is so then you can use the Inorder and Postorder/Preorder traversals to save a tree in a file and then reconstruct it later. This is a generalized process and can be used for Binary Tree even, hence BST can be reconstructed the same way even.
For this, do the inorder and preorder traversal and save them to some file and then reconstruct. You can take a look at the following example for an idea about how to reconstruct
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
Hope it helps.
BR,
ShallOvercome.


text:
Q: How to assign a the value of a variable from the adjacent cells of another cell in google sheets Hi so i created a script in sheets to pull a value from a cell everyday but im looking to add another row which shows profit or loss for the day.
// Record history from a cell and append to next available row
function recordValue() {
   var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Matt");
    var formattedDate = Utilities.formatDate(new Date(), "GMT", "dd/MM/yy");
    Logger.log(formattedDate);
    var value =sheet.getRange("$c$14").getValue();
    // var profit = ((cell to the left) - (cell above the cell to the left));
    sheet.appendRow([,formattedDate, value, profit]);
}

I'm looking to create the variable "profit" by grabbing the value from the cell to the left of the active cell and subtracting the cell above that one (left and up one from the active cell). Any help would be appreciated, thanks
this image shows what i want to be part of the script

A: Doing some operations with the column letter and the row number:
it is almost your code, except that we have two new variables
cellLeftValue and cellAboveLeftValue, both of them  calculate the left by using String.fromCharCode  to calculate the left letter:
function recordValue() {
   var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Matt");
    var formattedDate = Utilities.formatDate(new Date(), "GMT", "dd/MM/yy");
    Logger.log(formattedDate);
    var rowIndex = 14;
    var colIdx = 'c' ;
    var leftColIdx = String.fromCharCode(colIdx.charCodeAt(0) - 1);
    var value =sheet.getRange("$" + colIdx + "$" +rowIndex).getValue();
    var cellLeftValue = sheet.getRange("$" + leftColIdx + "$" +rowIndex).getValue();
    var cellAboveLeftValue = sheet.getRange("$" + leftColIdx + "$" + (rowIndex -1)).getValue();
    var profit = cellLeftValue - cellAboveLeftValue ;
    sheet.appendRow([,formattedDate, value, profit]);
}

you should add code to validate corner cases.


text:
Q: executable file imediatly closes with "NotImplementedError" I'm trying to use pyinstaller to turn a project into an executable. Pyinstaller creates the directories with sucess, but when I try to run the executable, It gives the following Error.
./main
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "main.py", line 51, in <module>
    font = pygame.font.Font("freesansbold.ttf", 30)
  File "pygame/pkgdata.py", line 50, in getResource
  File "setuptools-40.8.0-py3.6.egg/pkg_resources/__init__.py", line 1134, in resource_exists
  File "setuptools-40.8.0-py3.6.egg/pkg_resources/__init__.py", line 1404, in has_resource
  File "setuptools-40.8.0-py3.6.egg/pkg_resources/__init__.py", line 1457, in _has
NotImplementedError: Can't perform this operation for unregistered loader type
[8482] Failed to execute script main

This is the main code:
import pygame
from pygame.locals import *
from board import Board
from button import Button

# Initialization and screen surface loading
pygame.init()
screen = pygame.display.set_mode()
screenSize = pygame.display.get_surface().get_size()
width = screenSize[0]
height = screenSize[1]
pygame.display.set_caption("Sudokey: Sudoku's Solver")

# Image and music loading
bgMenu = pygame.image.load("background/sudokey2Menu.png")
bgMenu = pygame.transform.scale(bgMenu, (width, height - 30))
bgStart = pygame.image.load("background/sudokeyCustom.png")
bgStart = pygame.transform.scale(bgStart, (width - 40, height - 55))
pygame.mixer.pre_init()
pygame.mixer.init()
pygame.mixer.music.load("musica/lullabyGhostInYourPiano.mp3")
pygame.mixer.music.play(-1)
click = pygame.mixer.Sound("sons/click.ogg")

# Default screen and game state
running = 1
menu = 1
start = 0
credit = 0

# Mouse logic to detect click
currentSquare = (9, 9)
clickedCell = None

# Creating board using class "Board"
tabuleiro = Board()

# Creating menu buttons using class "Button"
buttonStart = Button(400, 186, 530, 90)
buttonTutorial = Button(400, 325, 530, 90)
buttonOptions = Button(400, 464, 530, 90)
buttonCredits = Button(400, 603, 530, 90)

# Creating start buttons using class "Button"
buttonSolve = Button(898, 40, 380, 80)
buttonReset = Button(898, 159, 380, 80)
buttonGoBack = Button(898, 279, 380, 80)
buttonOptionsStart = Button(898, 398, 380, 80)

# Font loading
font = pygame.font.Font("freesansbold.ttf", 30)

# Visually updates the board
def drawGrid(board):
    for i in range(9):
        for j in range(9):
            if (board[i][j]):
                text = font.render(str(board[i][j]), True, (0, 0, 0))
                textRect = text.get_rect()
                textRect.center = (j * 90 + 45, i * 80 + 45)
                screen.blit(text, textRect)

# Plays music based on input
def jukebox(number):
    if number == 0:
        pygame.mixer.music.stop()
    elif number == 1:
        pygame.mixer.music.load("musica/lullabyGhostInYourPiano.mp3")
        pygame.mixer.music.play(-1)
    elif number == 2:
        pygame.mixer.music.load("musica/adventureGhostInYourPiano.mp3")
        pygame.mixer.music.play(-1)
    elif number == 3:
        pygame.mixer.music.load("musica/liebestrau.mp3")
        pygame.mixer.music.play(-1)
    elif number == 4:
        pygame.mixer.music.load("musica/Kiss_the_Sky.mp3")
        pygame.mixer.music.play(-1)
    elif number == 5:
        pygame.mixer.music.load("musica/Lullaby.mp3")
        pygame.mixer.music.play(-1)
    elif number == 6:
        pygame.mixer.music.load("musica/Gentle_Breeze.mp3")
        pygame.mixer.music.play(-1)
    elif number == 7:
        pygame.mixer.music.load("musica/Eternal_Hope.mp3")
        pygame.mixer.music.play(-1)
    elif number == 8:
        pygame.mixer.music.load("musica/Pressure.mp3")
        pygame.mixer.music.play(-1)
    elif number == 9:
        pygame.mixer.music.load("musica/01 To the Moon - Main Theme.mp3")
        pygame.mixer.music.play(-1)

while running:
    while menu:
        pygame.display.flip()
        screen.blit(bgMenu, (0, 0))
        for event in pygame.event.get():
            if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                running = 0
                menu = 0
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                start = 1
                menu = 0
            if event.type == pygame.MOUSEBUTTONUP:
                x, y = pygame.mouse.get_pos()

                if buttonStart.isOn(x, y):
                    #click.play()
                    #click.stop()

                    print(x, y)
                    menu = 0
                    start = 1

                elif buttonTutorial.isOn(x, y):
                    print(x, y)
                    print('tutorial')
                    menu = 0
                    start = 1

                elif buttonOptions.isOn(x, y):
                    print(x, y)
                    print('Options')
                    menu = 0
                    start = 1

                elif buttonCredits.isOn(x, y):
                    print(x, y)
                    print('Credits')
                    menu = 0
                    start = 1

            if (event.type == pygame.KEYDOWN):
                if (pygame.K_0 <= event.key <= pygame.K_9):
                    number = int(event.unicode)
                    jukebox(number)

    while start:
        pygame.display.flip()
        screen.blit(bgStart, (0, 0))
        drawGrid(tabuleiro.tabuleiro)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print('stopping')
                running = 0
                start = 0

            elif event.type == pygame.KEYDOWN and (event.key == pygame.K_m or event.key == pygame.K_ESCAPE):
                start = 0
                menu = 1

            if (event.type == pygame.MOUSEBUTTONUP):
                coords = pygame.mouse.get_pos()
                col = coords[1] // 80
                line = coords[0] // 90
                clickedCell = (line, col)

            if (event.type == pygame.KEYDOWN):
                if (clickedCell != None):
                    if (pygame.K_0 <= event.key <= pygame.K_9):
                        line = clickedCell[1]
                        col = clickedCell[0]
                        number = int(event.unicode)
                        if 0 <= line <= 8 and 0 <= col <= 8:
                            tabuleiro.setCell(line, col, number)
                            clickedCell = None

            if (event.type == pygame.KEYDOWN):
                if event.key == pygame.K_s:
                    tabuleiro.findFirst()
                    tabuleiro.solve()
                elif event.key == pygame.K_r:
                    tabuleiro.reset()

            if event.type == pygame.MOUSEBUTTONUP:
                x, y = pygame.mouse.get_pos()
                print(x, y)

                if buttonSolve.isOn(x, y):
                    print('solving')
                    tabuleiro.solve()

                elif buttonReset.isOn(x, y):
                    tabuleiro.reset()
                    tabuleiro.show()

                elif buttonGoBack.isOn(x, y):
                    start = 0
                    menu = 1

                elif buttonOptionsStart.isOn(x, y):
                    start = 0
                    menu = 1

pygame.quit()

Thanks in advance. I tried to search for the error on the internet, but didn't had any luck. I'll be grateful if someone can help :)


text:
Q: Where to write some of Android Codings in Cordova I have designed cordova web application which works in Android. But I am not getting code for thermal printer code.
I have developed this Thermal printer code in Android and same I want to add in Cordova.
How can I write Android coding in Cordova?

A: To implement Java functionality in your Cordova app, you must use plugins. In this case you'll have to write your own. These links will get you started in the right direction:
Plugin Development Guide
Sample Hello World Cordova Plugin
Start with the sample plugin first, once you understand its structure you should simply edit it to suit your needs, but make sure you constantly test it to ensure it still works.