text:
Q: Failing to match the required number of dimensions for Keras LSTM model I have tried to set up a bare minimum example for building a neural network. I got 5 prices for a car over 5 different dates. No matter how I rearrange my data, I get 1 out of 2 types of errors.
Either
ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (1, 1)

or
ValueError: Data cardinality is ambiguous:
x sizes: 5
y sizes: 1
Make sure all arrays contain the same number of samples.

I've begun to suspect that no matter how I arrange this data, it will never work. Do I need to add another dimension (e.g. both prices and amount of tax)?
Full code:
import numpy as np
from keras.models import Sequential #, LSTM
from keras.layers.core import  Dense;
from keras.layers import LSTM
import tensorflow as tf

time_list = [ 1296000.0, 19350000.0, 29635200.0, 48294000.0, 45961200.0] # my sample data
price_list = [ 0.05260218,0.05260218,0.0,0.96769388,1.0 ]

these_dates = np.array(time_list)
prices = np.array(price_list)

#these_dates = these_dates.reshape(-1, 1)  # ive tried every variery of dimensions, nothing works.
#prices = prices.reshape(-1, 1)

model = Sequential()
model.add(LSTM(10 , return_sequences = True , input_shape =(len(prices) , 1) ,input_dim=2))
model.compile(optimizer = 'adam' , loss = 'mean_squared_error')
model.fit( prices ,these_dates , batch_size = 1 , epochs =1)

Specifying the input_ndim doesn't seem to help. What do I need to do to get these dimensions to match? Will it ever work?

A: As explained in the keras documentation the required input shape is (batch, timesteps, features). In your case this is (5, 1, 1) since batch=5, timesteps=1 and features=1, see the example below.
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, LSTM
tf.random.set_seed(0)

# generate the features
X = np.array([1296000.0, 19350000.0, 29635200.0, 48294000.0, 45961200.0])

# generate the target
y = np.array([0.05260218, 0.05260218, 0.0, 0.96769388, 1.0])

# rescale the features
X = (X - np.min(X)) / (np.max(X) - np.min(X))

# reshape the features
X = X.reshape(len(X), 1, 1)
print(X.shape)
# (5, 1, 1)

# define the model
model = Sequential()
model.add(LSTM(10, return_sequences=False, input_shape=(X.shape[0], X.shape[1])))
model.add(Dense(1))

# compile the model
model.compile(optimizer='adam', loss='mse')

# fit the model
model.fit(X, y, batch_size=1, epochs=10)

# generate the model predictions
model.predict(X)
# array([[0.05585098],
#        [0.0940358 ],
#        [0.11524458],
#        [0.152216  ],
#        [0.14772224]], dtype=float32)


text:
Q: How do I make a JavaScript Array in PHP going of the last array number id +1? Okay, I have been searching for an answer for this somewhat trick question. I have a site that runs random Google searches by using a list of JavaScript arrays. I have another site that goes with the other site that allows users to enter in their own search topic. These user entered values go into a giant text file that I like to call, the playground.
What I want to do is make the Php script write the user entered value into a JavaScript array, but use the array number id from the last entered JavaScript array, plus 1.
Example:
The last array entered is rand[60] = "hello";
Jon Doe enters "test".
The php script writes into the topics.js fie, rand[61] = "test";
I already have a file writing script for php...
<?php
//Idea Poster
$idea = $_POST['idea'];

//Idea DATA
$data = "$idea \n\n ";

//Idea Writer
$fh = fopen("Ideas.txt", "a");
fwrite($fh, $data);

//Closer
fclose($fh);
//Reload Page
$page = "POSindex.php";
$sec = "0";
header("Refresh: $sec; $page");
?>

A: You can keep the writing script as it is, and then write a script to read the .txt file and convert it to a JSON array on-the-fly.
Assuming you want to form a valid JS file:
echo 'var topics = ', json_encode(file('Ideas.txt'));

Optimize
The above script would always read the file and encode the contents into JSON; this can be optimized by keeping a cache file.
if (!file_exists('topics.json') || filemtime('topics.json') < filemtime('Ideas.txt')) {
    // changes were made to Ideas.txt
    $topics_js = 'var topics = ' . json_encode(file('Ideas.txt'));
    // update cache file
    file_put_contents('topics.json', $topics_js);
    echo $topics_js;
} else {
    // read from cached file
    readfile('topics.json');
}

A: Use a JSON array instead. Read the JSON from the file, decode it, add the element to the array, encode it, and write it out.

A: Just store your data in json format in the first place.
<?php
//Idea Poster
$idea = $_POST['idea'];

//Idea DATA
$data = "$idea \n\n ";

//Idea File (contains a json array)
$fh = fopen("Ideas.json", "r");
$contents = fread($fh, filesize("Ideas.json"));
fclose($fh);

// decode json
$ideas = json_decode($contents);
// add the new entry
$ideas[] = $idea;

// write it out
$fh = fopen("Ideas.json", "w");
fwrite($fh, json_encode($ideas));
fclose($fh);

//Reload Page
$page = "POSindex.php";
$sec = "0";
header("Refresh: $sec; $page");
?>

Or, if you really need that file to be single lines of plain text, you can use the php 'file' function to read it in as a php array and then run that through 'json_encode' to get a json array. You might have to do something about the double spacing in the file but basically you should get what you're looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is cloning an object, map or array and then using delete for example, considered immutable? If I have an existing object, array or map and I want to delete or add and item, is copying (shallow copy) a map first for example and then using the delete method on the new map, considered the correct way to maintain immutability?
EDIT
In functional languages I've learned like Elixir, data structures such as Lists return a new List. JS doesn't work this way. Even array methods like reduce under the hood are still taking an empty array as an initial parameter, and pushing items
 (mutating the initial array) into it.
const map = new Map([
  ['dog', 'Dog'],
  ['cat', 'Cat'],
  ['chicken', 'Chicken'],
])

const map2 = new Map([
  ...map,
])
map2.delete('dog')

A: You are mutating map2. However, on reasonable encapsulation logic (such as putting the clone+delete in a function), it's still considered a pure operation, and the original that you pass as an argument would stay unmutated.
The functions
function withoutDog(map) {
    const map2 = new Map(map);
    map2.delete('dog');
    return map2;
}

function withoutDog(map) {
    return new Map(Array.from(map).filter(([key, _]) => key !== 'dog'));
}

are indistinguishable from the outside.

A: When something is immutable it simply means it does not change state.
Since you are not changing the object's state (i.e. object.foo = 'bar'), rather you are cloning it and mutating the clone, it is immutable.

A: No, this is not an example of immutability.
An object is immutable if it's not possible to modify its contents. Making a copy of an object allows you to modify the copy without modifying the original, but you can still modify the original if you want.
const map = new Map([
  ['dog', 'Dog'],
  ['cat', 'Cat'],
  ['chicken', 'Chicken'],
])

const map2 = new Map(map) // clone the Map
map2.delete('dog') // modify the clone -- doesn't affect the original
map.delete('cat') // modify the original -- it's not immutable

A: Is the OP asking if the data structure is immutable, or whether the patterns being used here are immutable? The question is inherently confusing because we typically use immutable as an adjective for data structures, not algorithm implementations; we typically describe algorithm implementations designed for use with immutable data structures as "pure functions" or "pure operations".
According to the usual definition of "immutable", @Barmar is correct that the answer is that the data structures in the question are not immutable, since objects in JS are mutable. Even when we use const declarations, the const keyword just makes the reference to the object immutable, but the values within the object can still be mutated; we're now holding an immutable, atomic reference to a mutable, compound value.
But the OP's wording ("is cloning ... considered immutable") suggests that really the question is asking whether the process in question is immutable. Therefore, @Bergi's answer is a good attempt to answer the question as it seems intended, by parsing "immutable" as "pure". If this logic were encapsulated in an API, that API would provide a pure operation / function to callers, even though the implementation would not be internally pure, since it modifies a local value before returning it.


text:
Q: Adding action listener to jtable cell text value! not whole cell? I want to add an actionListener to JTable cell value which means when the user clicks on cell text, an action going to call. The text of the cell value will show like a hyperlink. which allows the user to click on it.

*

*Important note: I know how to add an action to the whole cell. My problem is that I want to add it to just a text like a link.

A: Try DefaultTableCellRenderer.getTableCellRendererComponent() to customize the look and feel of cell item.
Sample code:
public class CustomTableCellRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object obj,
            boolean isSelected, boolean hasFocus, int row, int column) {

       JLabel label = (JLabel) super.getTableCellRendererComponent(table, obj, isSelected,
                hasFocus, row, column);

       label.setText(some_html_code_that_look_like_hyperlink);
    }
}


text:
Q: Struts jQuery CKEditor Always Output UBB rather than traditional HTML My question is by using this CKEditor plugin: "http://code.google.com/p/struts2-jquery/wiki/CkeditorEditor" in Java/JSP Struts2.
I always get the ubb code(like [b][i]test[/i][/b]), not html code (like test).
I've searched for resources on the web for several hours and still cannot find any solutions ... very few people use this plugin and very very little resource can be found...
My struts config and ckeditor work fine.
My code:
<sjr:ckeditor
            id="richtextEditor"
            name="richtextEditor"
            rows="8"
            cols="80"
            width="800"
            uploads="false"
            loadingText="Loading..."
            toolbar="MyToolbar"
            skin="kama"
            dataType="html"
            customConfig="/xxx/js/ckeditor.config.js"
    />

Please help~~

A: Two great rules for performing effective searches are:

*

*use proper names when searching: UBB is the Ultimate Bullettin Board forum software, while the code itself it's called BBCode, Bullettin Board Code. It would be hard to find something searching UBB instead of BBCode;

*when a plugin incorporates a third party software, always (first) search for the third party software itself, not for the plugin customization: you will find more informations searching CKEditor instead of Struts2-jQuery-Richtext plugin.

That said, both CKEditor and Struts2-jQuery-Richtext starts by default on HTML mode, you must explicitly ask for turning on BBCode mode on startup;
Try restarting with the default configuration, then add stuff once at time, trying it until it breaks. Then, bypass that parameter...
You can find the default configuration on the Showcase of Struts-jQuery (under Widgets -> Richtext):
<sjr:ckeditor
                    id="richtextEditor"
                    name="echo"
                    rows="10"
                    cols="80"
                    width="730"
                    height="250"
                    uploads="true"
                    onFocusTopics="focusRichtext"
                    onBlurTopics="blurRichtext"
                    onChangeTopics="highlightRichtext"
                    value="Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia mauris vel est. Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."
                />

Hope that helps


text:
Q: libc.so not found error installing android x86 to usb I am trying to install android x86 that can be run from usb. In order to install, I fallow this link:  http://www.keyables.com/2011/12/install-and-boot-android-x86-40-ice.html
I completed the installation without problem, but when I run Android x86 from BIOS boot menu, I have the error: libc.so not found CANNOT LINK EXECUTABLE.
Is there anyone who have seen this error? Or can you think about what is the problem?
Or can you suggest me another tutorial on how to run Android from usb?


text: Q: How to set up ldap pagination in TeamCity I am using LDAP login and synchronization in teamcity, but recently we have tipped over the sizeLimit in number of users, which has broken synchronization. I cannot limit the users being looked at any further. Is it possible to enable pagination in the ldap group synchronization?


text:
Q: How to make join query in Hibernate using Spring MVC I have two tables. : Airport, FlightSchedule.
They have one-two-many relation each other.
Below is the hibernate data file.
Airport.java :
public class Airport implements java.io.Serializable {

    private Integer airportId;
    private String airportName;
    private String airportCountry;
    private String airportCity;
    private Set<FlightSchedule> depFlightSchedule = new HashSet<FlightSchedule>(0);
    private Set<FlightSchedule> arrFlightSchedule = new HashSet<FlightSchedule>(0);

}

FlightSchedule.java :
public class FlightSchedule implements java.io.Serializable {

    private Integer flightscheduleId;
    private Date depDay;
    private Date depTime;
    private Date arrDay;
    private Date arrTime;
    private Double flightTime;
    private Integer price;
    private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);

    private Airplane airplane;
    private Airport depAirport;
    private Airport arrAirport;

}

In FlightSchedule, they must have two relations with Airport. Because they need 'departure airport information' and 'arrival airport information'.
So, if I get two string input (departure airport name, arrival airport name), I want to make join table (FlightSchedule X Airport) and print all the information.
For example, If I have two input 'Korea' and 'Austrailia', then I want to print information about departure Korea, arrival Austrailia.
Like this! :
departureDate | departureAirport | arrivalDate | arrivalAirport
2017-12-01 | Incheon International Airport | 2017-12-10 | Sydney International Airport
-- departure Date, arrival Date come from 'FlightSchedule' table.
-- departureAirport name, arrivalAirport name come from 'Airport' table.
Actually, I tried this on mysql:
SELECT * FROM flight_schedule as f
inner join airport
on f.dep_airport_id=(select id from airport where airport.country='korea')
and f.arr_airport_id=(select id from airport where airport.country='Austrailia')
but it wasn't what I want.
Is there any solution?

A: Right now you want to perform a join with airport with the condition where airport has two different values at the same time, so this is impossible. You have to make two joins with this table for each condition.
SELECT * FROM flight_schedule as f

inner join airport a1

on f.dep_airport_id=(select id from airport where a1.country='korea')

inner join airport a2

on f.arr_airport_id=(select id from airport where a2.country='Austrailia')


text:
Q: android imageview curtain style animation in an android application, I have an imageview. I want to put another image on top of it. And while the user is touching the image, the top image will slide up like a curtain, to reveal the image below it. When the user removes his finger, I will go to another page
How can I achieve this?

Basically I know I have to implement the OnTouch Listener and worl on the "ACTION_DOWN" and "ACTION_UP" cases. But what I don't know is how to do that curtain slide up animation? because translation would translate the whole image and not just in the image canvas.
Thanks for any help

A: It's possible to achieve it by having two ImageViews under FrameLayout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/solid_blue"
        android:id="@+id/img_back"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/solid_green"
        android:id="@+id/img_front"/>
</FrameLayout>

And in the activity adding onTouchListener and translating the front ImageView would do the job:
ObjectAnimator mSlideAnim;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.curtainstyle);

    final ImageView imgFront = (ImageView) findViewById(R.id.img_front);

    FrameLayout parent = (FrameLayout) findViewById(R.id.parent);
    parent.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    if (mSlideAnim == null) {
                        triggerSlideUpAnimation(imgFront);
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    goToAnotherPage();
                    break;
            }
            return true;
        }
    });
}

private void triggerSlideUpAnimation(ImageView imgFront) {
    int height = imgFront.getHeight();
    mSlideAnim = ObjectAnimator.ofFloat(imgFront, "translationY", 0, -height);
    mSlideAnim.setDuration(300);
    mSlideAnim.start();
}

private void goToAnotherPage() {
    Toast.makeText(this, "Go to another page", Toast.LENGTH_SHORT).show();
}


text:
Q: Count a number of rows in a dataframe per hour I have a dataframe with two columns: timeStamp and eventMessage (string).
timeStamp:                                  eventMessage:
2020-10-19T10:07:56.7450775+02:00           transaction successful
2020-10-19T10:08:13.025169+02:00            transaction successful

I want to end up with a dataframe that has two columns : hour and numberOfEvents per that hour.
 hour:     numberOfEvents:
 1         41
 2         0
 ...       ...
 24        32

I've tried the df.resample('H', on='timeStamp', how='count'), but I think the how='count' is deprecated now?
Is there a new quick pandas way to do it?
UPDATE: thanks to Ami Tavory's tip the df now looks like this:
timeStamp
10    792
11    792
14    594
15    198
16    198

I'm not actually sure if it's a dataframe with one column or some other type completely. And how do I fill in the hours that had zero events?
Miniupdate: It's pandas.core.series.Series
Converted it to df with:
series = df.message.groupby(pd.to_datetime(df.timeStamp).dt.hour).count()
df2 = pd.DataFrame({'hour': series.index, 'counted': series.values})

Now I just need to figure out how to add and fill in other hours from 1 to 24 that had no events with a zero.

A: Regarding your new question (after the edit).

Converted it to df with:

You can more easily convert it with
df = series.to_frame().

Now I just need to figure out how to add and fill in other hours from 1 to 24 that had no events with a zero.

new_index = Index(arange(0,23,1), name="hour")
df.set_index("hour").reindex(new_index).fillna(0)

A: Group by the hour, and count:
df.eventMessage.groupby(pd.to_datetime(df.timeStamp).dt.hour)).count()


text:
Q: How to specify top N rows matching criteria? I am using SSMS 2008 and I have create a dataset with an sproc that returns many records.  There is a date column however that can have the same value within this dataset.  Now what I want to do is filter these records to only include the latest data from this dataset.  How do I do this in T-SQL?  (I only want to see the 2/5 records below).
For example:
col A     col B     col C
AAAAAA    BBBBBB    2/5/2012
AAAAA2    BBBBB2    2/5/2012
AAAAA3    BBBBB3    2/1/2012
AAAAA4    BBBBB4    1/25/2012
AAAAA5    BBBBB5    1/25/2012
AAAAA6    BBBBB6    1/10/2012

I tried your solutoin Andreas, but I am getting the error now:

Msg 102, Level 15, State 1, Line 74 Incorrect syntax near ')'.

Here is a code snippet:
select *
from (
    select *, row_number() over(partition by [test_details_answers_expanded_view].[actual_date]
    order by [test_details_answers_expanded_view].[actual_date] desc) rowno
    from
    (
Select
    [test_details_answers_expanded_view].[event_log_id],
...
[test_details_answers_expanded_view].[actual_date],
...
FROM #TEMP_EVENT_LOG A
JOIN [evolv_reports].[dbo].[test_header_rv] ON A.[event_log_id] = [test_header_rv].[event_log_id]
CROSS APPLY [dbo].[fn_getTestSetupFormDetails](null, [test_header_rv].[test_setup_header_id]) AS [test_header]
CROSS APPLY [dbo].[fn_getTestSetupFormDetails]([test_header].[test_setup_details_id], null) AS [test_details]
JOIN [evolv_reports].[dbo].[test_details_answers_expanded_view] ON
        [test_header_rv].[test_header_id] = [test_details_answers_expanded_view].[test_header_id]
    AND [test_details].[test_setup_details_id] = [test_details_answers_expanded_view].[test_setup_details_id]
Where
(@TestHeaderCode Is Null OR [test_header].[test_header_code] = @TestHeaderCode)
   AND (@TestHeaderID Is Null OR [test_header_rv].[test_header_id] = @TestHeaderID)
) t
where rowno = 1

Can you tell what I did wrong here?

A: Here's an example using row_number:
select *
from (
    select *, row_number() over(partition by [col c] order by [col c] desc) rowno
    from table
) t
where rowno = 1


text:
Q: Change date format of Datepicker control
i am using excel 2007.i am unable to change the date format after selecting the date from date picker as shown in the image. i tried to change the format by right clicking the excel cell but still not working. i am not that expert in visual basic but still i can do if i get any suggestion. visual basic code as i found written is as follows
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  With Sheet2.DTPicker1
    .Height = 20
    .Width = 20
    If Not Intersect(Target, Range("a13:l28")) Is Nothing Then
      .Visible = True
      .Top = Target.Top
      .Left = Target.Offset(0, 1).Left
      .LinkedCell = Target.Address
     Else
      .Visible = False
    End If
  End With
 End Sub


text:
Q: have waited for a successfull wait? I read that "have waited" can be used if the wait is over (or you don't want to wait) and if the person or thing  waited is not successful.
My question is: in case the wait is over but the thing or person waited is successfull can I use "have waited"for example:

I received the parcel that I had waited for?

A: Your sentence is correct.
The sentence "I have waited for the parcel" doesn't imply that you have received it or that you haven't received it.
All three are possible:

I had waited for two hours when the parcel arrived.

I had waited for two hours when I gave up and went out.

I had waited for two hours when I checked my watch, and I waited several hours after.

That is you can wait when the thing waited for arrives, when it doesn't arrive and you stop waiting and when it doesn't arrive and you continue waiting.


text: Q: Xcode 6 not running the test target when testing After upgrading to Xcode 6, I noticed that the macros I defined for the Test target were not working. After further examination, it seems like Xcode 6 is not running the test target, but rather the actual app target, when testing. Has anyone else encountered this? Any suggestions on how to fix it?


text:
Q: Highlight all traces connected to a component in Altium? I have a chip that I'm testing voltages on. I can highlight the chip by alt-clicking on it, at which point the pads are highlighted. At this point, is there a command to highlight everything these pads are connected to? As opposed to looking up each trace one by one in the schematic.
Using a simpler component as an example, I'd like to click on a resistor and see the highlighted traces emanating from both pads, to another component.

A: Right-click on component > Component actions > Select Component Nets (highlights all nets, routed or unrounted). Select Component Connections will only highlight physically routed connections from the component. This is explained in the Altium Documentation.


text:
Q: UPDATE строк БД MariaDB через PhpMyAdmin на хостинге Пытаюсь сделать UPDATE строк БД MariaDB через PhpMyAdmin, где определенное поле (FK) <> 1. Перепробовал все следующие варианты:
UPDATE friend SET `CityDistrict_id`=NULL,`Street_id`=NULL,`House_id`=NULL,`Apartment`=NULL WHERE City_id IN (SELECT DISTINCT `City_id` FROM `friend` WHERE City_id!=1)

UPDATE friend SET `CityDistrict_id`=NULL,`Street_id`=NULL,`House_id`=NULL,`Apartment`=NULL WHERE City_id!=1

UPDATE friend SET `CityDistrict_id`=NULL,`Street_id`=NULL,`House_id`=NULL,`Apartment`=NULL WHERE City_id<>1

Везде пишет затронуто 0 записей и результата от апдейта нет.
При этом когда я выгружаю:
SELECT `City_id` FROM `friend` WHERE City_id!=1

мне выдает 1519 строк.


text:
Q: How to retrieve id for each row and then assign it to a link $connect = mysql_connect("localhost", "username", "password");
if($connect) {
            mysql_selectdb('phplogin');
            $query = mysql_query("SELECT * FROM forum ORDER BY time desc");
            $query2 = mysql_query("SELECT * FROM forum");
            $data2 = mysql_fetch_array($query2);
            $id = $data2['id'];

            while($data = mysql_fetch_array($query)) {
                echo "
" . "
" . "
" . $data['user'] . "
" . "
" . $data['time'] . "
" . "
" . "
" . "
" . "
" . "
" . "" . htmlspecialchars($data['title']) . "" . "
" . "
" . htmlspecialchars($data['description']) . "
"  . "
" . "
" . "
" . "
";
            }

This is what ive tried but it assigns the first rows id to all links and i don't know how to do it, i am new to php and mysql thanks for the help in advance.

A: The problem is  that you are saving the id in $id - a variable. This can hold only one value.
Why are you even doing this? Both your queries are selecting from forum, can't you use $data['id']?
while($data = mysql_fetch_array($query)) {
    echo "
" . "
" . "
" . $data['user'] . "
" . "
" . $data['time'] . "
" . "
" . "
" . "
" . "
" . "
" . "" . htmlspecialchars($data['title']) . "" . "
" . "
" . htmlspecialchars($data['description']) . "
"  . "
" . "
" . "
" . "
";
}

Keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.

Doing this with MySQLi and printf() could look like this.
$link = mysqli_connect("localhost", "username", "password", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
}

$query = mysql_query("SELECT * FROM forum ORDER BY time desc");

if ($result = mysqli_query($link, $query)) {
        /* fetch associative array */
        while ($data = mysqli_fetch_assoc($result)) {
                printf ("

%s

%s

%s

%s

",
                    $data['user'],
                    $data['time'],
                    $data['id'],
                    htmlspecialchars($data['title']),
                    htmlspecialchars($data['description']));
        }

        /* free result set */
        mysqli_free_result($result);
}


text:
Q: Shift Operators! Show that the cyclic shift operator is unitary and determine its diagonalization: $$A=\begin{bmatrix}
       0&1     \\[0.3em]
      &0&1 \\[0.3em]
        & & \ddots \\
&&&.&1\\
1&&&&0
     \end{bmatrix}.$$

A: $A$ preserves norms, so it's unitary.
Suppose $x = \begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_{N-1} \end{bmatrix}$ is a (nonzero) eigenvector of $A$, with eigenvalue $\lambda$.  Then
\begin{align}
Ax &=
\begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_{N-1} \\ x_0 \end{bmatrix} \\
&= \lambda \begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_{N-1} \end{bmatrix}
\end{align}
so we see that
\begin{align}
x_1 &= \lambda x_0, \\
x_2 &= \lambda x_1,\\
\vdots & \\
x_{N-1} &= \lambda x_{N-2}, \\
x_0 &= \lambda x_{N-1}.
\end{align}
If $x_0$ were equal to $0$, we would find that $x = 0$, which is not the case.
WLOG, we can assume $x_0 = 1$.  (Otherwise we could just scale $x$ to obtain an
eigenvector whose $0$th component is $1$.)
Using the fact that $x_0 = 1$, we see that
\begin{align}
x_0 &= 1 ,\\
x_1 &= \lambda ,\\
x_2 &= \lambda^2 ,\\
\vdots & \\
x_{N-1} &= \lambda^{N-1}, \\
1 &= \lambda^N.
\end{align}
The last equation shows that $\lambda$ is an $N$th root of unity, which narrows $\lambda$ down to $N$ possible values.  Let $\omega = e^{\frac{2 \pi i}{N}}$.  The
eigenvalues of $A$ are $\lambda_j = \omega^j$, for $j = 0,\ldots, N-1$.
An eigenvector with eigenvalue $\lambda_j$ is
\begin{equation}
x_j = \begin{bmatrix} 1 \\ \lambda_j \\ \lambda_j^2 \\ \vdots \\ \lambda_j^{N-1}
\end{bmatrix}.
\end{equation}
We can normalize $x_j$ so that it's a unit vector.  The orthonormal basis of eigenvectors of $A$ that we obtain, which is called the discrete Fourier basis, is of great importance in math.  It's an orthonormal basis of eigenvectors not just of $A$, but of any circulant matrix.  (This is not surprising, because every circulant matrix is built from powers of $A$.)

A: I'm not sure how much math.SX allows "hint answers". I would like to provide a hint:
Eigenvalue is a root of the characteristic polynomial, which is the determinant
$$p_A(t)=\begin{vmatrix}
-t & 1 & 0 & 0 & 0\\
0 & -t & 1 & 0 & 0\\
0 & 0 & -t & 1 & 0\\
0 & 0 & 0 & -t & 1\\
1 & 0 & 0 & 0 & -t
\end{vmatrix}$$
(This example is for dimension $5$.) Try to enumerate this determinant for this dimension and find the eigenvalues. You should then be able to generalize the result for other sizes as well.


text:
Q: "System.Net.HttpListener" not available in IAppBuilder properties I am developing a web app with mix authentication (Owin Token Based and Windows authentication). I have implemented Owin token based authentication and want to implement windows authentication for the users which are marked as active directory users.
In Owin middleware, I want to get requesting user's windows username. I am getting object in OwinContext.Request.User.Identity. However, OwinContext.Request.User.Identity.Name is always blank string.
I found that I should add below lines in startup.cs:
var listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

However, I am getting key not found exception. "System.Net.HttpListener" is not present in Properties array. I have installed Microsoft.Owin.SelfHost, Microsoft.Owin.Host.HttpListener. However, I am still getting the error.
Any help is greatly appreciated.
Thanks,
GB

A: For me issue was that project was started as shared lib, not a web app.
Solution was to add a line into .cspro file after <ProjectGuid> line.
<ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Then you dont need to add HttpListener explicitly, just reload project and follow this instructions starting from Properties edition part.
Enabling Windows Authentication in Katana
You can access principal the same ways:
Get the user in an OWIN middleware:
public async Task Invoke(IDictionary<string, object> env)
{
    OwinContext context = new OwinContext(env);
    WindowsPrincipal user = context.Request.User as WindowsPrincipal;

    //...
}

Get the user in a Web API Controller:
// In a web api controller function
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;

UPD: List of Visual Studio Projects GUIDs


text:
Q: Generics of generics in Swift 3 I'm facing a strange problem, here it is: I wish to constraint one generic type with another generic type.
Let me explain, I have a simple generic type:
class Simple<T : Equatable> { ... }

And I wish to have another generic type constraint with this simple (generic) type:
class Complex<U : Simple> { ... } // WRONG!

Of course that does not compile nor this:
class Complex<U : Simple<T : Equatable>> { ... } // WRONG!

nor:
class Complex<U : Simple<T>> where T : Equatable { ... } // WRONG!

The only way I found is:
class Complex<T : Equatable, U : Simple<T>> { ... }

So I need to repeat T on each instanciation:
let x = Complex<Date, Simple<Date>>()

Worst, imagine if I have something like that:
class SimpleThing : Simple<Thing> { ... }
let y = Complex<Thing, SimpleThing>()

How can I declare Complex for using it this way?:
let x = Complex<Simple<Date>>()
let y = Complex<SimpleThing>()

Is it only possible in Swift 3?
Thanks in advance.

A: If I'm understanding what you want to do correctly, this can be achieved with a protocol with an associated type. You can make your Simple class conform to it, and then constrain the type parameter on Complex to be its conforming types, and finally, place qualifications on the associated type. Should be something like this:
protocol SimpleType {
    associatedtype Assoc
}

class Simple<T: Equatable>: SimpleType {
    typealias Assoc = T
}

class Complex<U: SimpleType> where U.Assoc: Equatable {
    init() {

    }
}

let c = Complex<Simple<Date>>()


text:
Q: Apache2 Ubuntu: Virtualhost redirects to localhost I wanted to set up a virtualhost for my apache2 running on my computer. So when I browse to: "invision.jan.pcsg" I get the page contents/folder structure from "/var/www/html/invision"
This is the virtualhost file "invision.jan.pcsg.conf" I created:
<VirtualHost invision.jan.pcsg:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/invision
    ServerName invision.jan.pcsg
    ServerAlias hkl.mor.pcsg hkl_at.mor.pcsg

    <Directory />
            Options FollowSymLinks
            AllowOverride FileInfo
    </Directory>
    <Directory /var/www/html/invision/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

When I browse to "invision.jan.pcsg" now, I get redirected to localhost and the "php is working"-page is displayed.
When browsing to "jan.pcsg" the folder contents of "/var/www" is displayed.
Does anyone have an idea why this happens?

A: I had the same issue but in my case I realized I had forgotten to enable the host .conf file.
sudo a2ensite myvhost.conf

Then I just reloaded apache and everything worked out as expected.

A: Change your DocumentRoot to directory where your web application ('view' if its MVC) is located.
Usually its : DocumentRoot /home/www-data/ /


text:
Q: Can't calculate the height of the attributed string I try to solve the issue with the NSAttributedString and the html in it. I try to draw it in the UILabel as the attributed text in the UITableViewCell.
I have a html string:
Безвозмездно

So I made an attributed string with the method:
+ (NSAttributedString *)attributedStringWithHTML:(NSString *)HTML {
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType };
    return [[NSAttributedString alloc] initWithData:[HTML dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:NULL error:NULL];
}

and then I try to calculate the string height in the class method to get the cell height. I use:
if (attrString.length > 0) {
    height += truncf([attrString boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                              context:nil].size.height) + 1.0f;
}

So I get the height of the label that is smaller than the label which I get with:
[self.titleLabel sizeToFit];

Can anyone help me with this issue?

A: I have met this question as well as. And at present I find it appears in UILabel and UITextView. In my opinion it's a bug of Apple. Thus, in order to guarantee the accuracy of result, I prefer to get the height with : [self.titleLabel sizeToFit]


text:
Q: How can I insert in database values from dropdown list based on a relationship between 2 tables? I am using ASP.NET c# Entity framework, Code first I am not talking about the id of the element in the list, but the id of it from a table if the value is in another table. E.g I have a FullName and an ID in one table and I have the same ID and some other stuff in another table(one to zero or one relationship). I have bound the FullName to a dropdown list control,but when saving,I need to refer to it's ID from the table, not the string value.

A: If you place something in a drop down list, you can place the ID in the value field and something else as a text, for example :
ddlCategorie.DataTextField = "Texte";
ddlCategorie.DataValueField = "ID_GLOBAL";
ddlCategorie.DataSource = db.GLOBAL.Where(t => t.DATE_FIN > dt).OrderByDescending(t => t.ID_GLOBAL).ToList();
ddlCategorie.DataBind();

As you see, I already placed the reel database value "ID" of the object inside the value field of the drop down list. So I can immediately retrieve is ID by doing :
int i = Convert.ToInt32(ddlCategorie.SelectedValue);


text:
Q: Why does my LIKE search return everything? I am trying to make an image search in my page full of images.
Whatever I search, it always returns all images with tag info in the database.
I made it so when someone enters text into the searchbox, the page is redirected to this:
ob_start();

$input = abs($_GET['input']);
$query = "SELECT * FROM `photo`.`photo` WHERE `tags` LIKE '%$input'";
$result = mysql_query($query);
$data = mysql_fetch_array($result) or die (mysql_error());
$rows = mysql_num_rows($result);
$image = $data['image'];

if ($rows==0) {
    echo 'no results found';
}  else {
    $jpgimage = imagecreatefromstring($image);

    $image_width = imagesx($jpgimage);
    $image_height = imagesy($jpgimage);

    $new_size = ($image_width + $image_height)/($image_width*($image_height/45));
    $new_width = $image_width * $new_size;
    $new_height = $image_height * $new_size;

    $new_image = imagecreatetruecolor($new_width, $new_height);

    imagecopyresized($new_image, $jpgimage, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
    $imagearray = imagejpeg($new_image, null);
    header('Content-type: image/jpeg');

    echo $imagearray;
}

The photos are stored as BLOBS so here I turn them into jpegs and resize them.
Most of this is just re-sizing the images but I have no idea why the LIKE part in my mysql query line isn't working. It always gives me all the images with any pictures that have tags.

A: I suspect $input is empty.  If your variable $input is null or empty string it will create a where clause:
 SELECT * FROM `photo`.`photo` WHERE `tags` LIKE '%'

This will match wildcard '%' to everything.

A: One problem I see is the abs on the first line. If you do an abs of a text string you get a zero.

A: You code use $input = mysql_real_escape_string($_GET['input']) for a more secure code.
There is no need to use the abs() function in your case.


text:
Q: Android: integrating Google signin under android M -> use_credentials? The official google doc for integration still says to have the permission use_credentials:
https://developers.google.com/identity/sign-in/android/start-integrating
where it says: "
To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user's Google account from an app.

"
however, this permission (use_credentials) has been retired under android M, so the recommendation to include it seems out of place. Is there a more recent integration guide/doc that takes into account the change with the permission under M?


text:
Q: Image transitioning jquery At the moment I'm developing a site and this is my first project using jquery. I'm using jquery to handle the calling of the images, but at the moment I'm not really liking how it is handling the transition from one image to another, the previous image which is about to be replaced is moved shifted due to the change of width to the image container and then replaced. I was wondering if there is a better way in which this can be handled as so far I have tried using the ready method to guarantee the new image is completely loaded before width of the container is changed, but it does nothing.
the link to my site is below
http://www.neuromanga.com/mangaReader1.0.php?cid=1

A: Use load instead of ready to determine if the image is loaded.
ready indicates that the document-tree has been loaded.


text:
Q: Canvas is already in use. Chart with ID '3' must be destroyed before the canvas can be reused I am trying to update Bar chart when a dropdown values getting change on a field. I tried all the answers here Destroy chart.js bar graph to redraw other graph in same <canvas>, but no luck. Can you please help me?
Below is the code that I have written to remove canvas element and recreate it
html

                <canvas id="myBarChart"></canvas>

TS
const ctx: any = document.getElementById('myBarChart')
            ctx.remove();
            const canvas = document.createElement("canvas");
            canvas.setAttribute("id", "myBarChart");
            canvas.setAttribute('width','1007');
            canvas.setAttribute('height','503');
            canvas.setAttribute('style','display: block; box-sizing: border-box; height: 64vh; width: 35vw;');
            const element = document.getElementById("chart-bar");
            element.appendChild(canvas);

            new Chart(ctx, {
                type: 'bar',
                data: chartData.value,
                options: chartOptions,
            })

Tried destroy() option as below. It didn't work
const chart = ref(null)

 if(chart.value){
                chart.value.destroy()
            }

            const ctx: any = document.getElementById('myBarChart')

           chart.value =  new Chart(ctx, {
                type: 'bar',
                data: chartData.value,
                options: chartOptions,
            })

I can see it's there in the DOM, but graph is not displaying

A: Because you have removed that and after create new now you have to add again.
 ctx = document.getElementById('myBarChart');
     new Chart(ctx, {
                    type: 'bar',
                    data: chartData.value,
                    options: chartOptions,
                })


text:
Q: How to invoke a form inside another form task In my Windows Form application I have created 2 Forms. In form 1 when I click button1, a new task will start. Inside the task I have created an instance of the form2 and show form2. I am calling the showData Method of Form2.
//Form1
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(int a1, EventArgs e);

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        Form2 form2 = new Form2();
        form2.Show();
    }
}

//Form2
public void showData(Form1 m)
{
    m.Tick += new Form1.TickHandler(test);
}

public void test(int a1,EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        for (int i = a1; i < 1000; i++)
        {
            label1.Invoke(new MethodInvoker(delegate { label1.Text = i.ToString(); }));
        }
    });
}

A: As kenny suggested i have modified the code. now it running how i am expected.
 public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                Action act1 = (() =>
                {
                    Form2 form2 = new Form2();
                    form2.StartPosition = FormStartPosition.CenterParent;
                    form2.Show();
                });
                this.BeginInvoke(act1);
            });
        }
}

// FORM2
private void Form2_Load(object sender, EventArgs e)
        {
            test(1);
        }
        public void test(int a1)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = a1; i < 1000; i++)
                {
                    label1.Invoke(new MethodInvoker(delegate { label1.Text = i.ToString(); }));
                }
            });
        }

Once again thanks Kenny


text:
Q: OSG - Creating overlaying, always on top rendering statusbar? I made a scene, where I detect some collisions (intersections) and I want to show progress of that collision (like interaction with objects). For example, you are pointing at light switch and there is circle which is filled based on time spent pointing at the switch, so the light would turn on/off after some timer period.
That "filling cricle/ status bar" is saved in images 1.png, 2.png...
//that "filling circle progress" is saved in images
osg::ref_ptr<osg::Image> image1 = osgDB::readImageFile("1.png");
osg::ref_ptr<osg::Texture2D> texture1 = new osg::Texture2D;
texture1->setImage( image1.get() );

//create textured quad
osg::ref_ptr<osg::Geometry> quad1 = osg::createTexturedQuadGeometry( osg::Vec3(-0.5f, 0.0f,-0.5f),
                                                                            osg::Vec3(1.0f,0.0f,0.0f),
                                                                            osg::Vec3(0.0f,0.0f,1.0f) );

osg::StateSet* ss1 = quad1->getOrCreateStateSet();
ss1->setTextureAttributeAndModes( 0, texture1.get() );
ss1->setMode(GL_BLEND,osg::StateAttribute::ON);
ss1->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

// I want that the "filling circle" will be always faced toward camera, so I use Billboards
osg::ref_ptr<osg::Billboard> timer1 = new osg::Billboard;
timer1->setMode(osg::Billboard::POINT_ROT_EYE);
timer1->addDrawable( quad1.get());

// I switch between 4 different states - 1/4 of circle, 2/4, 3/4, 4/4..
// thats why I use Switch
osg::Switch* switcher = new osg::Switch;
switcher->addChild( timer1.get(),true);

// just rootNode of scene
rootNode->addChild( switcher);

So, this works great but the problem is that sometimes the "statusbar=filling circle" is covered by some other object ( based on depth buffer I guess). What should I use to make my status bar render always on top of everything?
I tried to make a HUD camera, but that didnt work for me ( it just didnt render ) and I dont know if it's even the right way how to do it.
Thanks

A: Usually you turn off depth testing and depth writes and put the HUD-like item into a renderbin that renders after all the other stuff. I think there are examples of how to do this, probably in the osg HUD examples.


text:
Q: Importing Word Document Data into Excel (Multiple Documents) All,
How can I modify the code below to not just grab the first table of each word document in a specific folder but to extract all of the tables from each document? I've tried manipulating the code myself but I can't seem to get it right. Any help would be greatly appreciated.
Option Explicit

Sub test()

Dim oWord As Word.Application
Dim oDoc As Word.Document
Dim oCell As Word.Cell
Dim sPath As String
Dim sFile As String
Dim r As Long
Dim c As Long
Dim Cnt As Long

Application.ScreenUpdating = False

Set oWord = CreateObject("Word.Application")

sPath = "C:\Users\Domenic\Desktop\" 'change the path accordingly

If Right(sPath, 1) <> "\" Then sPath = sPath & "\"

sFile = Dir(sPath & "*.doc")

r = 2 'starting row
c = 1 'starting column
Cnt = 0
Do While Len(sFile) > 0
Cnt = Cnt + 1
Set oDoc = oWord.Documents.Open(sPath & sFile)
For Each oCell In oDoc.Tables(1).Range.Cells
    Cells(r, c).Value = Replace(oCell.Range.Text, Chr(13) & Chr(7), "")
    c = c + 1
Next oCell
oDoc.Close savechanges:=False
r = r + 1
c = 1
sFile = Dir
Loop

Application.ScreenUpdating = True

If Cnt = 0 Then
   MsgBox "No Word documents were found...", vbExclamation
End If

End Sub

A: Dim tbl

'........
Set oDoc = oWord.Documents.Open(sPath & sFile)
For each tbl in oDoc.Tables
    For Each oCell In tbl.Range.Cells
        Cells(r, c).Value = Replace(oCell.Range.Text, Chr(13) & Chr(7), "")
        c = c + 1
    Next oCell
    r = r + 2 'couple of blank rows between tables
    c = 1
Next tbl

oDoc.Close savechanges:=False
'.........


text:
Q: Function taking a string as table and column name I'm trying to write a function that will create a new column in a participation table based on the presence of a id in survey_name table:
CREATE OR REPLACE FUNCTION survey_participated(_sn text)
  returns void AS
$func$
BEGIN
  EXECUTE format($$ALTER TABLE participation ADD COLUMN %I integer DEFAULT 0$$,_sn);
  EXECUTE format($$UPDATE TABLE participation SET %I = 1 WHERE participation.participant_id = %I.participant_id$$,_sn,_sn);
END
$func$ LANGUAGE plpgsql;

I keep getting the error:
[2017-10-19 12:38:09] [42601] ERROR: syntax error at or near "TABLE"
[2017-10-19 12:38:09] Where: PL/pgSQL function survey_participated(text) line 4 at EXECUTE

Can someone point out my mistake?

A: The first problem is the syntax for UPDATE doesn't permit an optional TABLE after. It's just not needed. UPDATE only operates on tables; ALTER works on many targets. The second problem is that should be %s (literal/string) and not %I (identifier).
EXECUTE format(
  $$ALTER TABLE participation ADD COLUMN %I integer DEFAULT 0;$$,
  _sn
);
EXECUTE format(
  $$
    UPDATE participation
    SET %I = 1
    WHERE participation.participant_id = quote_literal(%s||participant_id);
  $$,
  _sn,
  _sn
);

That all said, this seems like a horrible idea. You're adding a column to the table, and setting the value of that column to the "colname+id"? How is that useful?


text:
Q: Avoiding a large amount of hidden elements for in place editing with angularjs I have a rather large list with todo items for which I want to add in place editing for:
  [ ] first todo
  [ ] second todo
  [ ] third todo

after clicking on the second todo, the text of the second todo can be edited but you can also set some properties on the todo:
  [ ] first todo
 -----------------------------------------------------------
| [ ] second todo__________________                         |
|     due: __/__/____                                       |
|     assigned: ______________                              |
|                                                           |
|     [save] [cancel]                                       |
 -----------------------------------------------------------
  [ ] third todo

Now I can do something like:

    <input type="checkbox"> {{todo.title}}

    <input type="checkbox"><input type="text" ng-model="todo.title">

    <input type="date" ng-model="todo.due">

    <input type="text" ng-model="todo.assigned">

    <button ng-click="doedit = false">save</button>

This should work (ignoring how the cancel button should work) but if I have a large todo list (100+ items) it will create a large amount of hidden elements which are probably never used but still bound to variables.
Is there a better way to do this? I looked at angular-xeditable which seems to dynamically add elements but it only works for simple input elements.
Or is having a large amount of hidden elements not an issue in angular?

A: ng-if removes the element from DOM entirely if it evaluates to false, including any watchers. For example:

This post explains some of the differences between ng-if and ng-show.

A: Having large amounts of hidden elements is not an issue only with the js but also with the DOM itself. you should not be doing that.
What can be done instead is
1. Using ng-if - keep a state of all the element lets say isEdited after the user clicks on the todo. Set the variable / state isEdited = !isEdited. This would set it to true if it is not already. Then inside your DOM write HTML using ng-if. Something like this

Since ng-if does not render the html till the condition is true. There wont be too much load on the DOM.
2. If the template for editing the to do item is same for all the todo items. You should prefer using ng-include with ng-if. This way the template would be downloaded the first time you try to edit the element. Then you can cache it so not network lag. Also there is no extra hidden html. Whatever needs to be on the page is on the page and is not hidden.

A: Wrapping all of that editing section into one container with an ng-if would reduce the number of internal watches down to one for the whole section when it wasn't active


text:
Q: Convertir .pyw a .exe con cx_freeze (TKINTER) He creado un reproductor MP3 con la libreria tkinter y quiero pasarlo a .exe
He probado con pyinstaller y no funcionaba
Cuento con la ultima version de python la 3.7.4
Aqui estan los modulos usados:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import pygame
from mutagen.id3 import ID3
import os
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import mutagen
import pygame
import getpass

Y aqui el setup.py:
import sys
from cx_Freeze import setup, Executable

build_exe_options = {"includes": ["tkinter"]}
base = None

setup(
    name = "Reproductor",
    version = "1.0",
    description = "Un reproductor mp3 simple",
    options = {"build_exe": build_exe_options},
    executables = [Executable("reproductor.pyw", base = base)])

Una vez que abro  el .exe se abre la terminal y se repentinamente se cierra

A: Tengo entendido que para usar tkinter en Windows con cx_freeze, tienes que incluir explícitamente los .DLLs de la librería, así que pondrías esto en tu setup.py (reemplazando tu usuario de Windows):
os.environ['TCL_LIBRARY'] = r'C:\Users\<USER>\AppData\Local\Programs\Python\Python36\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\<USER>\AppData\Local\Programs\Python\Python36\tcl\tk8.6'
include_files = [r"C:\Users\<USER>\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll",
                 r"C:\Users\<USER>\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll"]

Así mismo, debes incluir todos los paquetes que importas en el arg packages:
packages = ["tkinter", "pygame","os",[etc...]]

Luego en tu build_exe_options, incluyes los dlls que se especificaron y los paquetes:
build_exe_options = {
    "includes": ["tkinter"],
    "include_files": include_files,
    "packages": packages
}


text:
Q: Python: Problems of steganography in process of saving(cv2.imwrite) and reading(cv2.imread) using openCV I have a steganography code that hiding image inside another image.
I inject a watermark into the my image through this code.
The principle is very simple.
I used the source_image and watermark_images for insert the watermark.
This will randomly distribute the watermark_images.

First, scatter x and y of the watermark image using random seeds.
And then, convert source_image to frequency area using Fast Fourier Transform.
Finally, combine the watermark_layer with the frequency area of the source_image.

This encoding process works perfectly well. However, there is a problem in the process of decoding.
Decoding code is collects pixels scattered by random seeds in one place on the same principle.
This is Result of decoing:

this problem, if i try to encoded image to save(cv2.imwrite) and recalled(cv2.imread), the decoding doesn't work.
If I use the encoded object as it is, there is no problem. Is the pixel damaged during the saving and recall process?
this is my full code:
import cv2 as cv
import numpy as np
import random
import time

class Watermark:
    def __init__(self):
        self.watermark_image = cv.imread('../Watermark/google_logo.png')
        self.result_image_path = '../Watermark/result.jpg'
        self.random_seed = 2021
        self.alpha = 5

    def encoding(self, image_path):
        # Code Start
        start_time = time.time()

        # Read Image
        source_image = cv.imread(image_path)
        source_height, source_width, _ = source_image.shape
        watermark_height, watermark_width, _ = self.watermark_image.shape

        print('source height : ', source_height, ', source_width : ', source_width)
        print('watermark height : ', watermark_height, ', watermark width : ', watermark_width)

        # Convert image to frequency area with Fast Fourier Transform (image -> frequency)
        source_frequency = np.fft.fft2(source_image)

        # Get random seed
        y_random_indices, x_random_indices = list(range(source_height)), list(range(source_width))
        random.seed(self.random_seed)
        random.shuffle(x_random_indices)
        random.shuffle(y_random_indices)

        print('y random seed : ', y_random_indices)
        print('x random seed : ', x_random_indices)

        # Injection watermark
        watermark_layer = np.zeros(source_image.shape, dtype=np.uint8)
        for y in range(watermark_height):
            for x in range(watermark_width):
                watermark_layer[y_random_indices[y], x_random_indices[x]] = self.watermark_image[y, x]

        # Encoding frequency area + watermark layer
        result_frequency = source_frequency + self.alpha * watermark_layer

        # Apply Inverse Fast Fourier Transform (frequency -> image)
        result_image = np.fft.ifft2(result_frequency)
        result_image = np.real(result_image)
        result_image = result_image.astype(np.uint8)

        # Show elapsed time
        end_time = time.time()
        print('Encoding elapsed time : ', end_time - start_time, '\n')

        # Visualization
        cv.imshow('source_image', source_image)
        cv.imshow('watermark', self.watermark_image)
        cv.imshow('watermark_layer', watermark_layer)
        cv.imshow('result_image', result_image)

        # Save and Close
        cv.imwrite(self.result_image_path, result_image)
        cv.waitKey(0)
        cv.destroyAllWindows()

        return result_image

    def decoding(self, source_image_path, encoded_image):
        # Code Start
        start_time = time.time()

        # Read Image
        source_image = cv.imread(source_image_path)

        source_height, source_width, _ = source_image.shape
        print('original_height : ', source_height)
        print('original_width : ', source_width)

        encoded_height, encoded_width, _ = encoded_image.shape

        # Convert image to frequency area with Fast Fourier Transform (image -> frequency)
        source_frequency = np.fft.fft2(source_image)
        encoded_frequency = np.fft.fft2(encoded_image)

        # Convert frequency area to image (frequency -> image)
        watermark_layer = (source_frequency - encoded_frequency) / self.alpha
        watermark_layer = np.real(watermark_layer).astype(np.uint8)

        # Get random seed
        y_random_indices, x_random_indices = [list(range(encoded_height)), list(range(encoded_width))]
        random.seed(self.random_seed)
        random.shuffle(x_random_indices)
        random.shuffle(y_random_indices)

        print('y random seed : ', y_random_indices)
        print('x random seed : ', x_random_indices)

        # Restore watermark
        result_image = np.zeros(watermark_layer.shape, dtype=np.uint8)

        for y in range(encoded_height):
            for x in range(encoded_width):
                result_image[y, x] = watermark_layer[y_random_indices[y], x_random_indices[x]]

        # Show elapsed time
        end_time = time.time()
        print('Encoding elapsed time : ', end_time - start_time, '\n')

        # Visualization
        cv.imshow('original image', source_image)
        cv.imshow('target image', encoded_image)
        cv.imshow('watermark layer', watermark_layer)
        cv.imshow('result image', result_image)
        cv.waitKey(0)
        cv.destroyAllWindows()

if __name__ == '__main__':
    source_path = '../Watermark/jennie.jpg'

    # good work
    protected_image = Watermark().encoding(source_path)
    Watermark().decoding(source_path, protected_image)

    # doesn't work
    result_path = '../Watermark/result.jpg'
    result_image = cv.imread(result_path)
    Watermark().decoding(source_path, result_image)

Please give me some advice.

A: Carlos Melus have a good point.
Your code is not suitable for processing jpg images.
if you use png format, it will work out well.


text:
Q: Storing message into image I tried to read this paragraph from a website, but i don not understand why "32nd pixel store the bits needed for reconstructing the byte value needed to create the original string."
This is trying to put the message into alpha (transparency)(ARGB)
In this code below, why need to embed both integer and byte
 int imageWidth = img.getWidth(), imageHeight = img.getHeight(),
 imageSize = imageWidth * imageHeight;
 if(messageLength * 8 + 32 > imageSize) {
    JOptionPane.showMessageDialog(this, "Message is too long for the chosen image",
       "Message too long!", JOptionPane.ERROR_MESSAGE);
    return;
   }
   embedInteger(img, messageLength, 0, 0);

   byte b[] = mess.getBytes();
   for(int i=0; i<b.length; i++)
      embedByte(img, b[i], i*8+32, 0);
   }

 private void embedInteger(BufferedImage img, int n, int start, int storageBit) {
   int maxX = img.getWidth(), maxY = img.getHeight(),
      startX = start/maxY, startY = start - startX*maxY, count=0;
   for(int i=startX; i<maxX && count<32; i++) {
      for(int j=startY; j<maxY && count<32; j++) {
         int rgb = img.getRGB(i, j), bit = getBitValue(n, count);
         rgb = setBitValue(rgb, storageBit, bit);
         img.setRGB(i, j, rgb);
         count++;
         }
      }
   }

private void embedByte(BufferedImage img, byte b, int start, int storageBit) {
   int maxX = img.getWidth(), maxY = img.getHeight(),
      startX = start/maxY, startY = start - startX*maxY, count=0;
   for(int i=startX; i<maxX && count<8; i++) {
      for(int j=startY; j<maxY && count<8; j++) {
         int rgb = img.getRGB(i, j), bit = getBitValue(b, count);
         rgb = setBitValue(rgb, storageBit, bit);
         img.setRGB(i, j, rgb);
         count++;
         }
      }
   }

A: You need to store the message length so you know how many pixels to read to extract the message. Because the length of the message can't be predicted, 32 bits (for the first 32 pixels) are allocated.
The functions embedInteger and embedByte are almost similar.

*

*embedInteger deals with embedding the length of the message in the first 32 pixels.

*embedByte embeds your message characters, one by one. Every time it is called upon, it takes as an input the next character in your message in byte form, b[i]. There, it embeds one bit per pixel, for a total of 8 bits per byte.


text:
Q: How to update/delete an embedded object Given following domain model:
case class Benefits(id: Int, benefitPlan: String, comment : String)

case class Employee(empNum : Int, benefits : List[Benefit])

I've been using Salat to help derialize/deserialize these objects. However, I'm a little confused as to how to delete/update a specific object from the benefits List in employee object given that I know the benefit.id of the object that is to be deleted/updated?
I do not want to iterate the full benefits list to be able to update a single object since this list may hold large number of objects at runtime. Is there a better way than getting the emp object, iterating the list until desired object is found, update it and then save the emp object back?

A: In this case, I would say your benefits should be an Map[Int, Benefits].
If you use Map, your update/delete will be O(1) instead of linear time.
List is not a good choice if you need randomly access and update an element in it.

A: I'd suggest looking into this article about Casbah and Salat (assuming you're using salat for MongoDB)
def removeBenefit(empNum : Int, benefitId: Int)= {
  val updateQuery = $pull("benefits " -> MongoDBObject("id" -> benefitId))
  val query = MongoDBObject("empNum " -> empNum )
  modify(query, updateQuery) // your findAndModify operation goes here
}


text:
Q: Is there an elliptic curve mod n with exactly one point? I have tried many elliptic curves $y^2 = x^3 + ax +b$ with no success. I know that for prime modules there exists a minimum number of points the elliptic curve has to have, and I couldn't satisfy this for the smallest primes. So I decided to try luck with modules with few quadratic residues such as 8. But again, no luck.

A: The answer is: $y^2 + y = x^3 + x +1 \pmod{2}$. The only element here is the point in infinity: the neutral element.

A: You can also construct an answer mod 3 (which is in short weierstrass form) as follows:
For all $x \in \mathbf Z/3\mathbf Z$ we know by Fermat's little theorem that $x^3 = x$, therefore the polynomial $x^3 - x + 2$ always takes the value $2$ on elements of $\mathbf Z/3 \mathbf Z$, as 2 is not  a square in this ring the curve
$$y^2= x^3 - x + 2$$
has no non-infinite points.


text:
Q: How can I instantiate optimised modules in requirejs outside of the optimised file? In my require.config I create shorthands for a couple of paths that I use regularly:
require.config({
    paths: {
        text: 'components/requirejs-text/text',
        url: 'config/url',
        List: 'modules/List/main'
        ...

Then on the individual pages (in separate script files), I instantiate  a module like this:
require(['List'], function(List){ new List; });

My plan was to optimise all files into one file, require that and instantiate a module as in my example, but since the paths of require.config aren't really relevant anymore (Because I now only have main.build.js) how can I instantiate my modules?
UPDATE: Let me rephrase:
I'm trying to instantiate a module outside of the optimised build script, how do I do that?

A: Move your config into a separate location (either inline in the head, or in a JS file) that is after the require.js library. Now you can load any modules in the future and they will all be able to read the config regardless of which ones are loaded first.

A: Wherever you want to include the List module just create a new paths configuration which points to the optimized file.
require.config({
    paths: {
        'List': 'js/myApp'
    }
});
require(['List'], function(List) {
    ...
});

A: i think, we have one file called appInit.js, which do instantiate our application, so after that all other modules should instantiate on requirement, and also its not good practice to instantiate modules from every module.js,
consider single instance of Application and all other instance should relate to this application as components, services etc.,
every developer has his own coding style, choose what you are comfortable with..
if you are worrying about paths of modules, after building then don't worry paths are just the name of module, and it should work, but dynamically loaded or created modules won't work any more.


text:
Q: I cannot execute NodeJS Script on macOS Catalina (10.15.2) A year ago I created a Nodejs script to download some files from an S3 bucket, when I was running it on my old Macbook with macOS High Sierra (10.13.6) I successfully downloaded the files but recently I updated my Macbook and now I have macOS Catalina (10.15 .2) and since then I cannot longer run my script.
Normally I just had to write: ./downloader.js download in the terminal and that worked, but now on my new Macbook the terminal returns the following message: zsh: operation not permitted: ./downloader.js
Does anyone have any idea why it doesn't work anymore?

A: When executing scripts with Node.js use:
node ./downloader.js download

A: http://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/
Hope this solves your problem.
tl;dr: give Terminal application full disk permission. Since Mojave(10.14), all applications cannot access files without adding permission in preferences.


text:
Q: plot principal components of iris data we have following command for analyse Iris data
load fisheriris
gscatter(meas(:,1), meas(:,2),  species,'rgb'); hold on
gscatter(meas(:,3), meas(:,4),  species,'rgb');hold on
xlabel('Sepal length');
ylabel('Sepal width');

[pc,score,latent,tsquare] = princomp(meas);
pc,latent
cumsum(latent)./sum(latent)

and we get result
pc =

    0.3614    0.6566   -0.5820    0.3155
   -0.0845    0.7302    0.5979   -0.3197
    0.8567   -0.1734    0.0762   -0.4798
    0.3583   -0.0755    0.5458    0.7537

latent =

    4.2282
    0.2427
    0.0782
    0.0238

ans =

    0.9246
    0.9777
    0.9948
    1.0000

and we have also figure

our task is
Please, display by plotting the projections of the data in the plan of the first two principal components with respect to the three colors of the three classes.
we can call  first two component by
x=pc(:,1);
y=pc(:,2);

but what about  plotting?please help me

A: The projected data onto the principle components is returned in the score variable, so the plot is simply:
gscatter(score(:,1), score(:,2), species, [], [], [], 'on', 'PC1', 'PC2')
title('Projected Iris data'), grid on

of course you could perform the PCA yourself using either EIG or SVD:
X = meas;
X = bsxfun(@minus, X, mean(X));    % zero-centered data
[~,S,V] = svd(X,0);                % singular value decomposition

[S,ord] = sort(diag(S), 'descend');
pc = V(:,ord);                    % principle components
latent = S.^2 ./ (size(X,1)-1)    % variance explained
score = X*pc;                     % projected data


text:
Q: Force Update from a filtered DataGridView to Database I have created an application to fix a date conversion problem when transferring data from the machines. The conversion works great. I create a DataGridView that contains all records. I then sort the DataGridView to display the data that needs updating using SqlDataAdapter and DataSet. I then make the changes to the data in the DataGridView and click a save button to apply changes to the database table.
     try
        {
            MessageBox.Show("Complete");
            this.log5DataGridView.EndEdit();
            //this.log5BindingSource.DataSource = this.log5DataGridView.DataSource; <-- Last Resort
            this.log5BindingSource.ResetBindings(false);
            this.log5BindingSource.EndEdit();
            this.log5TableAdapter.Update(roboticlineDataSet.Log5);
        }
        catch { }

When I run in debug mode the log5DataGridView.DataSource Table[] shows the data changes are available. But the log5BindingSource never seems to get the changes to push it through to the TableAdapter Update. I tried the  ResetBindings, EndEdit() the last thing is to take the Datasource and force it to the BindingSource.
If I use the following code to search for the precise record the save / update to database will not occur.
 using (SqlDataAdapter adpt = new SqlDataAdapter("SELECT * FROM [dbo].[RoboticLine] WHERE [FSItemNumber] = '" + Value + "' ORDER BY [FSItemNumber] ASC;", conn))
                        {
                            DataSet ds = new DataSet();
                            adpt.Fill(ds);
                            valueComboBox.Enabled = false;
                            log5DataGridView.DataSource = ds.Tables[0];
                            log5DataGridView.Refresh();
                            this.log5DataGridView.Rows[0].Selected = true;
                        }//end of adpt using

The Question is if there is a way to save the searched log5DataGridView record back to the database as the datagridview table retains the change but the log5BindingSource still contains the original
this.log5TableAdapter.Fill(this.roboticlineDataSet.Log5);

Thank you.

A: Found out what was occurring, when I programmed the datagridview to show the searched data it did not change the bindingsource but left it the same from the Form Load ().
this.log5TableAdapter.Fill(this.roboticlineDataSet.Log5);

To resolve this I found the RoboticLineTable in the Dataset.xsd location in the Soultion Explorer. Here I selected the roboticlinetableadapter and right-clicked where i selected Add->Query. Here I created a SQL query with a where ID = @Value  to do the required filtering / search. This replaces the using SqlDataAdapter code with this code
this.log5DataGridView.EndEdit();
this.log5BindingSource.EndEdit();
this.log5tableAdapter.FillByID(this.roboticline.Log5, Value);
this.invalidate();
this.log5DatagridView.Refresh();

Now when I wish to save, the BindingSource has the changes made in the datagridview  and update / save to the Database. Creating and refilling the tableadapter helps keep the link to the bindingsource for you.
Hope this helps someone else that may run into this in the future


text:
Q: Read and Write Text in ANSI format Please have a look at the following code
import java.io.*;

public class CSVConverter
{
    private File csvFile;
    private BufferedReader reader;
    private StringBuffer strBuffer;
    private BufferedWriter writer;
    int startNumber = 0;
    private String strString[];

    public CSVConverter(String location, int startNumber)
    {
        csvFile = new File(location);
        strBuffer = new StringBuffer("");
        this.startNumber = startNumber;

        //Read
        try
        {
         reader = new BufferedReader(new FileReader(csvFile));
         String line = "";

         while((line=reader.readLine())!=null)
         {
             String[] array = line.split(",");

             String inputQuery = "insertQuery["+startNumber+"] = \"insert into WordList_Table ('Engl','Port','EnglishH','PortugueseH','Numbe','NumberOf','NumberOfTime','NumberOfTimesPor')values('"+array[0]+"','"+array[2]+"','"+array[1]+"','"+array[3]+"',0,0,0,0)\"";

             strBuffer.append(inputQuery+";"+"\r\n");
             startNumber++;

         }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

       System.out.println(strBuffer.toString());

        //Write
        try
        {
            File file = new File("C:/Users/list.txt");
            FileWriter filewrite = new FileWriter(file);

            if(!file.exists())
            {
                file.createNewFile();
            }

            writer = new BufferedWriter(filewrite);

            writer.write(strBuffer.toString());
            writer.flush();
            writer.close();

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

    public static void main(String[]args)
    {
        new CSVConverter("C:/Users/list.csv",90);
    }
}

I am trying to read a CSV file, edit the text in code, and write it back to a .txt file. My issue is, I have Portuguese words, so the file should be read and write using ANSI format. Right now some Portuguese words are replaced with symbols in the output file.
How can I read and write text data into a file in ANSI format in Java?

A: To read a text file with a specific encoding you can use a FileInputStream in conjunction with a InputStreamReader. The right Java encoding for Windows ANSI is Cp1252.
reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), "Cp1252"));

To write a text file with a specific character encoding you can use a FileOutputStream together with a OutputStreamWriter.
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "Cp1252"));

The classes InputStreamReader and OutputStreamWriter translate between byte oriented streams and text with a specific character encoding.


text:
Q: Active class is not able to add on li tag I try to add class in li tag but it's not able to add via javascript function but it's just append on li tag while page is loading then it is disappeared. Can you ju help us how can i solve it?
active class is not set while we are selected to while we are click to one menu
html code

        Client

      Medical

        Social

        Transportation

        Activity

        Food

        Reports

        Schedule

 script code

A: Try to write your jQuery code inside a document.ready
$(document).ready(function(){
     $("#navMenus").on('click', 'li', function () {
        alert("in navMenus click");
        $("#navMenus li.active").removeClass("active");
        // adding classname 'active' to current click li
        $(this).addClass("active");
     });
});


text:
Q: Difference between NIB from Xcode and App Store we got a business app in app store and since last update the main shaped button on the main view isn't working. The User can't touch up the button.
Now, it doesn't work only in app store app. When I deploy the app (same code, same version) directly from Xcode to same device, it works. So, why?
With iExplorer I've export both folder an compared it. What I could see is, that the .nib files are different. In that special case, the main view with the shaped button, also the file size is diffrent. Xcode Version has a file size of 10814 Bytes, the App Store Version only 10804. Can someone explain it to me?
thanks


text:
Q: SAP Cloud OData filter logical (substringof and substringof) on same property fails I'm working with the SAP Cloud platform and their OData APIs.
I'm having an OData filter that looks like this:
$filter=substringof('120',PROPERTY) and substringof('130',PROPERTY)

As soon as I have 2 substringof operations on the same property name, the query fails.
"Expression can not converted into ABAP select options"

Replacing the 'and' with an 'or' passes, but changes completely the context of my query.
My property is defined as a string, that can be either empty, have 1 value, or multiple comma-separated values, and the query should return the items that has all values specified.
PROPERTY=""
PROPERTY="120"
PROPERTY="120,130,150"

According to this question on the sap forums from 2012, multiple actions on the same properties are not supported yet.
https://answers.sap.com/questions/9264652/multiple-filters-with-dates.html
Can someone confirm this is still the case?
Does someone have another performant solution for my case?
Thanks


text:
Q: Debouncing IC input resistor? I've recently been working on a breadboard compatible compact debouncing PCB. I found the MAX6816, a debouncing IC - check the spreadsheet here.
I made the below simple circuit as per the "Typical Operating Circuit" on the data sheet.

The datasheet does not show a resistor between ground and the button here:

Should I add one to my circuit or would the IC include one?
Thanks for your help in advance.

A: The IC has an internal pullup resistor. Like most resistors in ICs it is loosely specified (a 3:1 range) and (because the manufacturer wants to maximize the market) rather on the high side.

So the minimum switch current with a 5V supply is 50uA. Some switches would be more reliable with a higher current (often specified on the switch datasheet as minimum current) and if that is so you can add an external pullup resistor, so the effective pullup will be the parallel combination of the internal and external resistors.


text:
Q: How to fix netlogo 6.1.1 nothing named ? has been defined I just started to learn Netlogo. I followed the code written by Lynne Hamill and Nigel Gilbert
when I finished, it reminded me that "nothing named ? has been defined".
foreach xs [
    create-traders 1 [
      set shape "house"
      setxy ? 0
      set color red
      ; give each trader some knids of produce to sell
      set stock n-of n-items-stocked fruit-and-veg
    ]
  ]

Any ideas?

A: As Jasper notes in the comments, the ? is outdated syntax. Something like this should work - instead of an implicit ?, you iterate with an explicit variable (named this-x in the example below) and use that variable name wherever relevant.
foreach xs [ this-x ->    ; name the variable here and add the arrow
    create-traders 1 [
      set shape "house"
      setxy this-x 0    ; use that variable name
      set color red
      ; give each trader some knids of produce to sell
      set stock n-of n-items-stocked fruit-and-veg
    ]
  ]

You can think about it as equivalent to the conceptual loop "for each item in the list, call it 'this-x' and do something (everything after ->), replacing the 'this-x' in the code with whatever item is in the list at the moment".


text:
Q: iOS 7 alert view automatic trigger I am pretty new to iOS programming and still learning a lot. I was hoping to make an alert view pop up automatically on a certain screen. Basically I am using the new qualquamm Gimbal beacons for an app. This code triggers a log when a beacon is first found:
// FYXVisitDelegate protocol
- (void)didArrive:(FYXVisit *)visit;
{
    // this will be invoked when an authorized transmitter is sighted for the first time
    NSLog(@"I arrived at a Gimbal Beacon!!! %@", visit.transmitter.name);

}

What I would like to do is have this trigger a pop up or alert when first found saying what the log says just for testing. I would like to brand the alert but heard that is not possible in iOS 7 anymore so if there are any suggestions for a pop up as well I would love to hear.
This is what I had with no luck (the log still is trigged though):
- (void)didArrive:(FYXVisit *)visit;
{
    // this will be invoked when an authorized transmitter is sighted for the first time
    NSLog(@"I arrived at a Gimbal Beacon!!! %@", visit.transmitter.name);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome" message:@"%@" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:@"View", visit.transmitter.name, nil];

    [alert show];
}

A: The problem is probably your message string assignment, you're using a format string @"%@" but you're missing the call to stringWithFormat:
Old code: (check out the message parameter)
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome" message:@"%@" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:@"View", visit.transmitter.name, nil];

New code: (notice the [NSString stringWithFormat] call)
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome" message:[NSString stringWithFormat:@"%@",  visit.transmitter.name] delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:@"View",  visit.transmitter.name, nil];

The old code also assigned an alertView button to be named after the transmitter's name.  I kept this in the new code, but remove the "visit.transmitter.name" from the otherButtonTitles: parameter if you don't want it.
Also, if you're looking for updates while a visit is in progress, use this FYXVisitManager delegate method:

*

*(void)receivedSighting:(FYXVisit *)visit updateTime:(NSDate *)updateTime RSSI:(NSNumber *)RSSI;


text:
Q: Como usar a API do Google Maps em um Windows Form em c#? Estou tendo problemas em como fazer isso. Meu TCC possui uma aba onde aparece uns endereços (Label), onde, ao clicar, quero que o endereço apareça no Maps. Já pensei em usar o WebBrowser, mas não quero que o usuário fique navegando além daquele endereço.

Quero que essa janela apareça. Mas não não sei o que fazer.

A: Você não disse se esses endereços serão estáticos ou não.
Caso seja estático, você pode fazer assim:

*

*Busque cada local no site do google maps e ajuste o nível de zoom, tipo de terreno e etc.

*Ainda no site do google maps, clique no botão de menu(aqueles três risquinhos no cando superior direito) e depois clique em Compartilhar ou incorporar mapa.

*Clique em incorporar mapa, faça os ajustes necessários e copie o código gerado.Faça isso para cada endereço.

*Adicione a seu form uma WebView e cada vez que clicar em um endereço você chama a função abaixo passando como parâmetro o código gerado por cada endereço no google.

Desse modo o WebView irá exibir somente a porção do mapa escolhida por você
Código:
public void updateWebView(string codigoIncorporado)
{
    webBrowser1.Refresh();
    var str = "" + codigoIncorporado + "";
    webBrowser1.DocumentText = str;
}


text:
Q: graphql node api: how can I define a field as optional? GraphQL allows you to specify whether a field is to be optional or not (add !)
Using the Node API, I cannot find that option.
see https://graphql.org/graphql-js/constructing-types/
I also went through the types without luck
see https://github.com/graphql/graphql-js/blob/main/src/index.ts
What am I missing?
I basically want
type MyEntity {
  uuid: ID!
  name: String!
}

instead of
type MyEntity {
  uuid: ID
  name: String
}

A: I found the answer
const preType:GraphQLOutputType = GraphQLInt;
// wrap the type with `GraphQLNonNull`
const type = new GraphQLNonNull(preType);

see https://github.com/graphql/graphql-js/blob/main/src/type/definition.ts#L391


text:
Q: Probability, covariance, joint density Let $f(x, y) =3\min(x,y)$ if x and y are values between $0$ and $1$.
Find $\operatorname{cov}(x, y)$.
Is the right way to solve it, finding the marginal density of $x$ and $y$? And then the expected values? Or is there any other simpler way?

A: One way is to find directly $E[XY]$ and $E[X]=E[Y]$ (due to symmetry), the joint density is a simple function if you consider $y<x$ and $y>x$ cases separately: $$E[XY]=\int_{0}^1\int_0^x (xy)(3y)dydx+\int_0^1\int_x^1(xy)(3x)dydx$$
Execute the same integral by replacing $xy$ to $x$ or $y$ to find $E[X]=E[Y]$, and then you've the covariance.


text:
Q: haproxy-varnish can't reach 6k requests Issue
I can't reach 6k requests/seconds.
I get a lot of timeouts.
My response time goes as high as 26 seconds.

Intro
I am setting up a server that will host a 100MB static-website.
The thing is that I will have to handle about 8000 constant requests for 5 days in a row.
I made the following setup :
HAProxy -> Varnish -> Nginx -> Staticfiles

HAProxy handle the connections on port 80 (soon on port 443 as well), transferts the requests to Varnish that will serve the files from the cache. I have set Nginx to expires 7d;. So Narnish will request the static file to Nginx every 7 days.

*

*I use the highest compression level on Nginx so Varnish store highly compressed  static files gzip_comp_level 9;.

*I have set the ttl of the static files to 7 days in Nginx expires 7d;.

*I have set a high number of thread (At least, I think) in Varnish thread_pools=8 thread_pool_max=4000.

*I have set a not to big but not to small memory for Varnish (static files are not bigger 100MB altogether) malloc,512m.

*I have set a max nuimber of maxconn in HAProxy maxconn 65000.

*I tried to play with the sysctl configs, but I'm not sure it changed anything, that's why I think my problem come from my configurations.

*I believe HAProxy with maxconn 65000 doesn't throttle. I think Varnish throttle my requests, but I'm not sure how to confirm it.

my server is set like so:
Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz
Number : 8
Cache : 8192 KB
Speed : 1764 MHz
RAM 2 x 8192 MB
Configuration files
Nginx
user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
  worker_connections 768;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
  ssl_prefer_server_ciphers on;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_comp_level 9;
  gzip_buffers 16 16k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

server {
  listen 127.0.0.1:82 default_server;
  root /var/www/html;

  index index.html index.htm index.nginx-debian.html;
  location / {
    expires 7d;
    add_header Cache-Control "public";
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }
}

}

Varnish
//DEAMON
DAEMON_OPTS="-a localhost:6081 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -p thread_pools=8 \
             -p thread_pool_min=100 \
             -p thread_pool_max=4000 \
             -s malloc,512m"
//default.vcl
# new 4.0 format.
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
  .host = "127.0.0.1";
  .port = "82";
}

HAProxy
global
  log /dev/log  local0
  log /dev/log  local1 notice
  chroot /var/lib/haproxy
  stats socket /run/haproxy/admin.sock mode 660 level admin
  stats timeout 30s
  user haproxy
  group haproxy
  daemon
  ca-base /etc/ssl/certs
  crt-base /etc/ssl/private
  ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
  ssl-default-bind-options no-sslv3
  maxconn 65000

defaults
  log global
  mode  http
  option  httplog
  option  dontlognull
  timeout connect 5000
  timeout client  50000
  timeout server  50000
  errorfile 400 /etc/haproxy/errors/400.http
  errorfile 403 /etc/haproxy/errors/403.http
  errorfile 408 /etc/haproxy/errors/408.http
  errorfile 500 /etc/haproxy/errors/500.http
  errorfile 502 /etc/haproxy/errors/502.http
  errorfile 503 /etc/haproxy/errors/503.http
  errorfile 504 /etc/haproxy/errors/504.http

userlist users
  group admin
  user username insecure-password password groups admin

frontend static_https
  bind *:80
  mode http
  acl aclok http_auth_group(users) admin
  #http-request auth realm admin if !aclok
  default_backend static_varnish

backend static_varnish
  mode http
  option forwardfor
  http-request set-header X-Forwarded-Port %[dst_port]
  http-request add-header X-Forwarded-Proto https if { ssl_fc }
  option httpchk HEAD / HTTP/1.1\r\nHost:localhost
  server varnish 127.0.0.1:6081 check

sysctl.conf
net.ipv4.tcp_max_syn_backlog = 10240
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 2048 61000
net.core.netdev_max_backlog = 40000
net.ipv4.tcp_max_tw_buckets = 400000
net.ipv4.tcp_max_orphans = 60000
net.core.somaxconn = 40000

EDIT
loader.io config load test and result

Answers
@fox

Why HAProxy in front of Varnish?

My client absolutely want https to appear in the browser. So I tought I would delegate the job of handling the ssl certificate to HAProxy.

What are the loads during test?

I haven't set a monitoring tool yet, but from the last test I ran, by looking at htop I can tell:
 - proc: 25% avg.
 - ram: 1070MB avg.

How are you testing?

I am using loader.io, it creates 10000 clients, and make them request for 1 minute. you can see the full test here: http://ldr.io/1eLKrrT

Using keep-alives?

I'm not sure how loader.io does.

What hardware?

I can't tell you more than what I wrote above, unless there is a way using some shell commands ?

Does the test pass Accept-Encoding: gzip?

I added it in loader.io after your comment, it didn't change anything.

What is the cache hit rate?

This is a very good question, but I don't know where to see that?

A: I will start this answer as a kind of open-answer. As I can not answer it all at once and there will be follow-up questions.
First thing is - you are kind of overcomplicating things. Serving static content through nginx, varnish and haproxy will probably cause a lot of unnecessary overhead (more TCP connections, more content switches, more memory used, etc.).
You may actually get better performance using directly nginx. As all of your content will fit into memory, nginx will be serving those files from memory anyway (thanks to OS cache). And using open_file_cache you even get around the filesystem overhead. Varnish could probably give you a slightly better performance for plain HTTP.
In your case, I would start with the KISS method - plain nginx, tune it to best performance. Then add SSL and tune that to best performance (keep-alives, ssl session caching). If you feel, that your performance with nginx alone is not good enough, then try figuring, what your real bottleneck is and how that can be mitigated (using what software).
And the benchmarking. I'd start with something local, like JMeter, or httperf, or at least Apache Bench. That helps you rule out all the things internet. Once you have figured out how your setup reacts to different kinds of tuning, then use something like loader.io to finetune the real world performance.
Some reasons that come to mind for the performance you are seeing now:

*

*you add latency to every connection, by putting afront of varnish (try hitting varnish directly)

*your varnish cache hit rate is not as good as you expect, with static content it should be 100% (use varnishstat to find out)

*you are starving some resource, open file descriptors, etc.

*if you are serving 7000 rps, but getting hit by 10000 rps, there are 3000 unserved requests. That's what causes the timeouts.

*logging can actually cause hiccups too. It should not be problem for Varnish (it's using shm and separate process), but I have no information about how logging is done in HAProxy and nginx

*we'll come up with more I think ...