text:
Q: Clojure editing code while running split into different files I've recently been trying to test OpenGL in Clojure with the lwjgl library. I started off with this code:
(ns test.core
  (:import [org.lwjgl.opengl Display DisplayMode GL11]))

(defn init-window
  [width height title]
  (Display/setDisplayMode (DisplayMode. width height))
  (Display/setTitle title)
  (Display/create))

(defn update
  []
  (GL11/glClearColor 0 0 0 0)
  (GL11/glClear GL11/GL_COLOR_BUFFER_BIT))

(defn run
  []
  (init-window 800 600 "test")
  (while (not (Display/isCloseRequested))
    (update)
    (Display/update))
  (Display/destroy))

(defn -main
  [& args]
  (.start (Thread. run)))

This worked well as in emacs, with the nREPL plugin, I could start it and while it was running change something (eg the call to glClearColor).
I decided to split this into two seperate files, so I could reuse the init-window function :
(ns copengl.core
  (:import [org.lwjgl.opengl Display DisplayMode GL11]))
(defn init-window
  [width height title]
  (Display/setDisplayMode (DisplayMode. width height))
  (Display/setTitle title)
  (Display/create))

(defn mainloop
  [{:keys [update-fn]}]
  (while (not (Display/isCloseRequested))
    (update-fn)
    (Display/update))
  (Display/destroy))

(defn run
  [data]
  (init-window (:width data) (:height data) (:title data))
  (mainloop data))

(defn start
  [data]
  (.start (Thread. (partial run data))))

and then in a seperate file
(ns test.core
  (:import [org.lwjgl.opengl Display DisplayMode GL11])
  (:require [copengl.core :as starter]))

(def -main
  [& args]
  (starter/start {:width 800 :height 600 :title "Test" :update-fn update})

This, however, does not let me change while running. I have to close the window then execute -main again to see the change.
So far I have tried putting these last two excerpts of code into just one file which also did not work. However, if I change the call from update-fn to the name of my update function (update) when they were in the same file I could change things while it was running.
I'm guessing this is because when I create the map with the update function in it passes the actual function and so if I redefine update by using the nREPL plugin to evaluate it there is no effect because the mainloop function is using the function - not looking up the symbol update and using that.
Is there a way to have the code split between two files whilst still being able to change the code while running?

A: Pass it the var update instead of the function that is currently contained in the var update by putting #' in front of the var name. This will cause the contents of the update function to be looked up in the var every time it is called.
(def -main
  [& args]
  (starter/start {:width 800 :height 600 :title "Test" :update-fn #'update})

This has a very slight cost to performance which is why it is not the default though it's very useful in cases like this and the cost is slight.


text:
Q: How do I count the number of buckets that match a condition in Elastic Search? I have a collection of documents describing the scores of users. The same user will have multiple scores.
My data is structured like so:
[
  { "user_id" : 3, "score" : 10 },
  { "user_id" : 1, "score" : 20 },
  { "user_id" : 2, "score" : 60 },
  { "user_id" : 1, "score" : 10 },
  ...
]

I am trying to determine each user's max score. The elastic search query that I am using looks like this:
{
  "size": 0,
  "aggs": {
    "users": {
      "terms": {
        "field": "user_id",
        "size": 9999
      },
      "aggs": {
        "max_score": {
          "max": {
            "field": "score"
          }
        }
      }
    }
  }
}

The response looks like this:
  "aggregations": {
    "users": {
      "buckets": [
        {
          "key": "1",
          "doc_count": 10,
          "max_score": {
            "value": 10
          }
        },
        {
          "key": "2",
          "doc_count": 10,
          "max_score": {
            "value": 20
          }
        },
        ...
      ]
    }
  }
}

How can I find the number of buckets where max_score > 20, max_score > 50, and max_score > 100?
Is there any way to make the response look like below?
  "aggregations": {
    "users": {
      "buckets": [
        {
          "key": "1",
          "doc_count": 10,
          "max_score": {
            "value": 10
          }
        },
        ...
      ],
      "scoresGreaterThan20": {
         "value": 10
      },
      "scoresGreaterThan50": {
         "value": 5
      },
      "scoresGreaterThan100": {
         "value": 2
      },
    }
  }
}

A: You can achieve your use case by repeating the same terms and max aggregation along with bucket selector aggregation, for different conditions you need. Adding a working example -
Index Data:
  { "user_id" : 3, "score" : 10 }
  { "user_id" : 1, "score" : 20 }
  { "user_id" : 2, "score" : 60 }
  { "user_id" : 1, "score" : 10 }

Search Query:
You can use stats bucket aggregation to get the count of buckets after performing the bucket selector aggregation.
{
  "size": 0,
  "aggs": {
    "user_gt20": {
      "terms": {
        "field": "user_id",
        "size": 9999
      },
      "aggs": {
        "max_score": {
          "max": {
            "field": "score"
          }
        },
        "scoresGreaterThan20": {
          "bucket_selector": {
            "buckets_path": {
              "values": "max_score"
            },
            "script": "params.values > 20"
          }
        }
      }
    },
    "user_gt20_count": {
      "stats_bucket": {
        "buckets_path": "user_gt20._count"
      }
    },
    "user_gt50": {
      "terms": {
        "field": "user_id",
        "size": 9999
      },
      "aggs": {
        "max_score": {
          "max": {
            "field": "score"
          }
        },
        "scoresGreaterThan50": {
          "bucket_selector": {
            "buckets_path": {
              "values": "max_score"
            },
            "script": "params.values > 50"
          }
        }
      }
    },
    "user_gt50_count": {
      "stats_bucket": {
        "buckets_path": "user_gt50._count"
      }
    },
    "user_gt100": {
      "terms": {
        "field": "user_id",
        "size": 9999
      },
      "aggs": {
        "max_score": {
          "max": {
            "field": "score"
          }
        },
        "scoresGreaterThan100": {
          "bucket_selector": {
            "buckets_path": {
              "values": "max_score"
            },
            "script": "params.values > 100"
          }
        }
      }
    },
    "user_gt100_count": {
      "stats_bucket": {
        "buckets_path": "user_gt100._count"
      }
    }
  }
}

Search Result:
 "aggregations": {
    "user_gt100": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": []
    },
    "user_gt20": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 2,
          "doc_count": 1,
          "max_score": {
            "value": 60.0
          }
        }
      ]
    },
    "user_gt50": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 2,
          "doc_count": 1,
          "max_score": {
            "value": 60.0
          }
        }
      ]
    },
    "user_gt20_count": {
      "count": 1,            // note this
      "min": 1.0,
      "max": 1.0,
      "avg": 1.0,
      "sum": 1.0
    },
    "user_gt50_count": {
      "count": 1,             // note this
      "min": 1.0,
      "max": 1.0,
      "avg": 1.0,
      "sum": 1.0
    },
    "user_gt100_count": {
      "count": 0,             // note this
      "min": null,
      "max": null,
      "avg": null,
      "sum": 0.0
    }
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get any objects (Rect, Surfaces...) at position / coordinates X, Y So the question is simple:
Given a Surface, let's call it screen and x,y coordinates, can I get anything that lays at that coordinates on that Surface?
For example, let's say we have typical, Player attack, and if the attack reach the Enemy position x,y then enemy dies.
So given this simple app (is an example only not a real app)
import pygame as pg
from pygame.math import Vector2

# pygame constants
CLOCK = pg.time.Clock()
WIN_SIZE = (1280, 640)
# pygame setup
pg.init()
# screen
window = pg.display.set_mode(WIN_SIZE, 0, 32)
background = pg.Surface(WIN_SIZE)

player = pg.Surface(Vector2(12, 64))
player_rect = player.get_rect(topleft=Vector2(150, 150))
player_attack = False
player.fill((102, 255, 178))
player_attack_range = 20 # player can hit at min 20 pixel from target

enemy = pg.Surface(Vector2(12, 64))
enemy_rect = player.get_rect(topleft=Vector2(175, 150))
enemy.fill(pg.Color("green"))

while True:
    background.fill((0, 0, 0))  # screen clear

    # Render enemy
    attacked = False
    if player_attack:
        # !!!!! HERE !!!!!
        # Now we check if the playuer is close enough to the enemy, so we MUST know the enemy pos
        distance_x = abs(player_rect.x - enemy_rect.x)
        if distance_x > player_attack_range:
            attacked = True
            enemy.fill(pg.Color("red"))
    if not attacked:
        enemy.fill(pg.Color("green"))

    background.blit(enemy, enemy_rect.topleft)
    # Render player
    background.blit(player, player_rect.topleft)

    # Events
    for event in pg.event.get():
        if event.type == pg.QUIT or (
                event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):  # x button and esc terminates the game!
            exit(1)
        # ............. Mouse ............. #
        if event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                player_attack = True
        if event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                player_attack = False

    pg.display.update()  # 2) Update the game
    window.blit(background, (0, 0))  # 3) Repaint the screen
    CLOCK.tick(60)  # 4) Wait 60 Frames

When is attacked

Now I always seen it done this way more or less:
distance_x = abs(player_rect.x - enemy_rect.x)
if distance_x > player_attack_range:
    attacked = True
    enemy.fill(pg.Color("red"))

With this example, I'm not pointing out the code implementation but the fact that, the player must know the target position and then check whether or not the target is hit
But what I want to know, let's say I don't know the enemy position, and the player just attacks, is there a way that we can get what's currently on the surface at the attack range?
So do something like
attacked_area_x = abs(player_rect.x +  player_attack_range) # only care of x coords
rects_or_surfaces_in_area = background.what_have_we_got_here(Vector(attacked_area, 0))
for r in rects_or_surfaces_in_area:
    print("Hit!")

A: Update
So By checking MDN documentation of Game Development MDN I actually find a game algorithm / Technique that is similar (but concept is the same) of my solution.
Is called the Broad Phase
From the documentation:

road phase should give you a list of entities that could be colliding. This can be implemented with a spacial data structure that will give you a rough idea of where the entity exists and what exist around it. Some examples of spacial data structures are Quad Trees, R-Trees or a Spacial Hashmap.

So yes, it seems one of many good approach to solve this problem.

So, after some research and thanks to Rabbid76 and his answer here How do I detect collision in pygame? which covers in details the most common collisions in Pygame, it seems that what I was looking for natively is just not possible.
Maybe is normal, I'm also new to game development and maybe what I want to do just doesn't make any sense, but I bet it does.
The scenario I'm facing is, just one player with a sword hitting, so I asked my self, why should I need to know prior what objects lie on the sword path and check if is hit, instead, do the hit and request to the parent screen "what object are in the sword path"? , which, is for sure faster because we don't need to know what object that have collision are (and avoid a for loop and check for each react/surface).
So, let's say there are many many object that have collision and a player may hit it, it would be way faster do don't know what' there but request it instead to the surface, so basically the surface should be aware of its children / objects.
I tried a bit the Surface.subsurface() and the Surface.get_parent() but couldn't make it work, anyway still, in a surface area we may have many thinks like:

*

*draws, Rect, Surfaces, Sprites, Imgs etc...

I have only 2 solutions in my mind:
Map the objects coordinates
This only really works if, the entities are static, if so, then we could create a dict with key x:y coordinates and then check if the sword is in within a certain x:y and exist in the dict, then the entity is hit.
But with entity then moves by themself, is a nigtmare and will have a worst problem than before, you would need to update the keys at each frame and so on..
Make it 'distance' sensible
So, this could apply to each entity that is moving and may or may not hit something that has a collision. But staying on the example context, let's say we are iterating thourgh entities / object that at each frame are updating their position.
We could check how distant are from the player, let's say 2 chunks away (or the sword lenght) and collect them in a list
Then we that list, we check if, once the sword is updated, is hitting anything close by.
Still, pretty sure there are better ways (without changing or extending pygame its self).
And maybe, by extending pygame, there may be a way to implement a 'surface aware' class that when we request a specific Rect area, it tells us what's there.


text:
Q: Where does the route /json/syncreply come from in ServiceStack? I'm trying to send a request to a third party api using this DTO:
[Route("log_entries", "GET")]
public class MyRequest: IReturn<MyResponse>
{
}

The client request:
string uri = "https://..../api/v1"
var jsonClient = new JsonServiceClient(uri);

// This works
var response = client.Get<MyResponse>("/log_entries");

// Does not work
var response = client.Send(new MyRequest());

I'm getting a Not Found response currently. When I send to http:// using Fiddler, I can see the
path /json/syncreply is added i.e. ../api/v1/json/syncreply> I am looking to understand where this comes from and how to ensure my request is sent on the right path.
Cheers

A: The /json/syncreply is route that is defined in ServiceStack API, as a method for sending DTOs without having to provide a specific route for the given DTO, in other words a ServiceStack host would make a route based on the the type name of MyRequest, which can be resolved by ServiceStack clients using the Send method.
3rd party API don't use Send
As you are consuming a 3rd party API using the ServiceStack.JsonServiceClient and their API is not ServiceStack based, then the Send method will not work, because their server API does not have appropriate routes.
The Send method only works for consuming ServiceStack API, because this is a ServiceStack specific feature.
Use the Request DTO
You should be making your request like this, note the Get<T> where T is the request object, MyRequest not MyResponse.
MyResponse response = client.Get<MyRequest>();

And also add a slash at the front of your route declaration on your DTO:
[Route("/log_entries", "GET")]
public class MyRequest: IReturn<MyResponse>
{
}

tldr;
For 3rd party API that is not a ServiceStack Service, you need to use the appropriate VERB methods such as Get, Post, Put etc, so the route defined on the DTO is used, not the json/syncreply route, therefore simply avoid the Send method.


text:
Q: How to translate this SQL query with propel? i don't know how to  translate this query :
SELECT distinct(id_ville) FROM `point_location`

I try to do it, but it doesn't work :
$c = new Criteria();
$c->add(PointLocationPeer::ID_VILLE, Criteria::DISTINCT);
$c->setDistinct();
$this->villes = PointLocationPeer::doSelect($c);

A: Try something like this:
$c = new Criteria();
$c->addSelectColumn(PointLocationPeer::ID_VILLE);
$c->setDistinct();
$this->villes = PointLocationPeer::doSelect($c);


text:
Q: find rows in table where all column values are within a specific range I have a table with an id column (row names: x1-x5)followed by 20 columns with numerical values. I need to find rows where all column values are within a given range e.g. 1000-2000.
x1  614.514 587.3   719.25  604.801 669.595 1703.74 1744.23 1876.09 846.224 2314.82 1348.99 2013.43 1867.24 1762.6  1566.74 1590.8  1587.01 1544.88 1617.78 1309.69

x2  3254.02 5258.79 2648.52 2644.17 3222.8  4127.27 5254.42 5434.76 6102.35 5890.25 5619.38 3346.84 3696.11 4581.44 1468.48 4628.4  4969.09 4623.34 4842.4  5542.33

x3  596.369 561.562 860.907 612.952 636.416 1246.69 1122.82 1125.08 508.835 1173.63 1046.1  1078.4  1238.64 1042.9  950.404 1120.76 998.17  1075.62 1115.9  914.933

x4  1343.95 1712.76 952.298 1018.87 1084.32 578.646 707.197 599.226 1337.18 1686.72 840.897 539.199 533.319 563.101 736.027 661.588 711.23  657.246 687.865 793.797

x5  1118.95 1325.52 1287.7  1666.06 1740.34 1799.18 1956.39 1483.32 2998    4045.77 2176.8  1693.72 1896.93 2041.38 1014.72 2128.76 2043.94 1831.81 1936.41 2275.93

A: Try using rowSums
df[rowSums(df >= 1000 & df <= 2000) == ncol(df), ]

Using apply
df[apply(df >= 1000 & df <= 2000, 1, all), ]

Using filter_all from dplyr
library(dplyr)
df %>% filter_all(all_vars(. >= 1000 & . <= 2000))


text:
Q: Undefined index but the index exists I hope someone could help me with the following error. I can't find a solution.
var_dump($curl->response);
echo '

';
$result = json_decode(json_encode($curl->response), true);

var_dump($result);
echo '

';

$key = 'email';
foreach ($result as $k => $v) {
    echo  $k . '->' . $result[$k] . '
';
    if ($k == $key) {
        echo $result[$key] . '
';
    }
}
//$result[$key];

If I run I get the following data (I changed some value for security reason)
object(stdClass)#2085 (6) {
    ["account_type"]=> string(0) ""
    ["email"]=> string(17) "sales@example.com"
    ["firstName"]=> string(4) "Mary"
    ["lastName"]=> string(6) "McLonn"
    ["organizer_key"]=> string(19) "1234567890123456789"
    ["version"]=> string(1) "3" }

array(6) {
    ["account_type"]=> string(0) ""
    ["email"]=> string(17) "sales@example.com"
    ["firstName"]=> string(4) "Mary"
    ["lastName"]=> string(6) "McLonn"
    ["organizer_key"]=> string(19) "1234567890123456789"
    ["version"]=> string(1) "3" }

account_type->
    email->sales@example.com
    sales@example.com
    firstName->Mary
    lastName->McCann
    organizer_key->1234567890123456789
    version->3

Everything ok here. But if uncomment the last line $result[$key], it gives me the followinf error:
Slim Application Error
The application could not run because of the following error:

Details
Type: ErrorException
Code: 8
Message: Undefined index: email
File: \App\Controllers\Api\V1\binar\Model.php
Line: 313
Trace
#0 \App\Controllers\Api\V1\binar\Model.php(313): Slim\Slim::handleErrors(8, 'Undefined index...', 'App\Controllers\Api...', 313, Array)
#1 \App\Controllers\Api\V1\binar\Model.php(352): App\Controllers\Api\V1\binar\Model::send('https://api.get...', 'POST', Array, Array, false)
#2 \App\Controllers\Api\V1\binar\binar.php(47): App\Controllers\Api\V1\binar\Model->applyCredentials()
#3 [internal function]: App\Controllers\Api\V1\binar\binar::demo()
#4 \vendor\slim\slim\Slim\Route.php(173): call_user_func_array(Array, Array)
#5 [internal function]: Slim\Route->Slim\{closure}()
#6 \vendor\slim\slim\Slim\Route.php(468): call_user_func_array(Object(Closure), Array)
#7 \vendor\slim\slim\Slim\Slim.php(1355): Slim\Route->dispatch()
#8 \vendor\slim\slim\Slim\Middleware\Flash.php(85): Slim\Slim->call()
#9 \vendor\slim\slim\Slim\Middleware\MethodOverride.php(92): Slim\Middleware\Flash->call()
#10 \App\Resources\Middleware\APMiddleware.php(28): Slim\Middleware\MethodOverride->call()
#11 \App\Resources\Middleware\LPMiddleware.php(31): App\Resources\Middleware\APMiddleware->call()
#12 \vendor\slim\slim\Slim\Middleware\PrettyExceptions.php(67): App\Resources\Middleware\LPMiddleware->call()
#13 \vendor\slim\slim\Slim\Slim.php(1300): Slim\Middleware\PrettyExceptions->call()
#14 \index.php(8): Slim\Slim->run()
#15 {main}

The same line is working good inside the foreach, that why it shows me the email two times.
I'm using php-curl-class/php-curl-class 4.8
I really do not understand what I'm doing wrong, or where look for the solution.
Thanks for your help.
EDIT
If I do
$this->email = $curl->response->email

I get the error: Undefined property: stdClass::$email
But if I do
$this->email = (property_exists($curl->response, 'email')) ? $curl->response->email : null;

I have no error and $this->email has the correct value loaded


text:
Q: Clean app cache in windows phone 7 I am developing an app based on winPho7 (no updated to 7.5 yet)
In my app, I call to a navigator to show a webpage but my problem is that (still testing)when I deploy the app in the phone, it shows the webpage perfectly.
But if I make changes in the webpage, the next time I open the app, it still shows the older one. My app doesn't get new images, new css, new buttons...
In Android I can delete cache and get the new webpage. How can I do it on winpho?
Now, I have to delete the app, install again and then, it will show the new webpage.

A: To prevent caching, add a random query parameter to the url, e.g. http://example.com/?ignore=425897425.
That will force retrieving the page again.
I hope that that is what you are looking for.


text:
Q: Getting rid of black screen in android intent flag Intent.FLAG_ACTIVITY_CLEAR_TOP I am new to android and i am stuck with this.
I have a login activity, when i click on login it goes to main menu where i have a grid view, so when i select an item from grid view it goes to next activity say "B",and when i click on confirm button in activity "B" it shows me activity "c" which has home button.
I am using android:theme="@android:style/Theme.Dialog" theme which is showing my activity as a dialog.
When Clicked on home button, it should bring me to the main menu i.e. the Gridview.
So now when i press back button in main menu it shows me activity "c", but my problem is i have to go to Login Activity.
I have tried putting finish() in activity "B" but in activity "C" when i click back button i want to c activity "B" which currently showing me main menu i.e. the gridview.
I have also tried setting intent flag Intent.FLAG_ACTIVITY_CLEAR_TOP in activity "c" but it shows a black screen for a second before showing main menu.

A: When you click on your "home" button, you need to go back to the grid view activity like this:
Intent intent = new Intent(this, MainMenuActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

This will clear all activities in the task, back to (but excluding) the main menu activity. It will then call onNewIntent() on the existing instance of your main menu activity, followed by onResume().
This should solve your "black screen" problem.

A: Guys The Simple Solution is
Step 1) Create a drawable shape with the color you want like this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
</shape>

Step 2) add this to your theme in style.xml
 <itemname="android:windowBackground">@drawable/any_default_background</item>

Actually the window color is by default black in dark mode in android so you can change the color to the activity screen background color and the black color by default would be gone.
you can try other solutions as well but this is the one i always use.


text:
Q: How to make the linebreak in conteditable div be posted as a new line? In  contenteditable div, The line-break made by pressing the  enter key is indeed shown as a new line in this div. But when the value of the div being posted and fetched, the line break doesn't show up. I think by default it is captured as an empty string when posting to database and fetch out. I wondered what is the most common way to make it posted and fetched as a line break?

A: Pass your text through nl2br before displaying it. It will transform new line breaks into
 tags.
$value = nl2br("Your \ndata");
?>

<?php echo $value;?>


text:
Q: Decompose compound sentence to simple sentences I am looking for a way to decompose the compound sentence to simple sentences in stanford nlp.
For ex: Input: The manager went home and committed suicide.
Output: The manager went home. He committed suicide.

A: If you are lucky and Stanford parser works correctly on your sentence, you can just decompose the parse tree:
(ROOT
  (S
    (S
      (NP (PRP I))
      (VP (VBP am)
        (NP (NNP John))))
    (CC and)
    (S
      (NP (PRP I))
      (VP (VBP am)
        (NP (DT an) (NN engineer))))
    (. .)))

As you can see, there are 2 S nodes deriving from ROOT-S node. Another way of saying it: Take only the S nodes that don't have S children.

A: If you would be ok with, "The manager went home, and he committed suicide" (2 independent clauses can be found), maybe check out:
Clause Extraction using Stanford parser, or
Independent clause boundary disambiguation, and independent clause segmentation – any tools to do this?


text:
Q: HTML / CSS - (Float: left) does not work in application.scss
.message-sent {
  position: relative;
  background-color: #FFFF00;
  border-color: #BCE8F1;
  margin: 5px 20px;
  padding: 10px;
  float: right;
}

.message-received {
  background-color: #F1F0F0;
  border-color: #EEEEEE;
  margin: 5px 20px;
  padding: 10px;
  float: left;
}

in view/messages/_message.html.erb

    <div class="<%= user.id == message.user_id ? 'message-sent' : 'message-received' %>">
      <%= message.body %>

in view/conversations/_conversation.html.erb

  <div class="panel panel-default" data-conversation-id="<%= conversation.id %>">

      <%= link_to conversation.opposed_user(user).nickname, '', class: 'toggle-window' %>

      <%= link_to "x", close_conversation_path(conversation), class: "btn btn-default btn-xs pull-right", remote: true, method: :post %>

            <%= render 'conversations/conversation_content', messages: conversation.messages, user: user %>

        <form class="new_message">
          <input name="conversation_id" type="hidden" value="<%= conversation.id %>">
          <input name="user_id" type="hidden" value="<%= user.id %>">
          <textarea name="body" class="form-control"></textarea>
          <input style="font-size: 13px; height: 30%;" type="submit" class="btn btn-warning" value="전송">
        </form>

*
I made real-time chat from rails to actioncable.
I send-message on the right side of the chat window.
I want the receive-message to appear on the left.
In the tutorial it was possible.
But it will not be in my project
All chats appear on the left.
It does not seem to be a problem with scss.
It is correct if you modify the color in scss
If you want additional code, please let me know by comment.*
chrome browser(F12) in the error page

<!DOCTYPE html>

    <title>Univ. Community Prototype</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <meta name="csrf-param" content="authenticity_token" />
    <meta name="csrf-token" content="UNQR3pfc6IF9oi+Wp3fgdvvJSJNQ1AXgrX6R1uroKEtyVyJqyOLxCQ+WEp9wPfca0xfz9DDsOIO9rOMAQ0kfTw==" />

    <link rel="stylesheet" media="all" href="/assets/application.self-607424cb77179d6e129430471baf980e5ad301867ac29c26b26d7212ad5f08ff.css?body=1" />

    <meta property="og:image" content="/img/op_thum.png">

    <link rel="stylesheet" href="/css/image-box.css">
    <link rel="stylesheet" href="/css/customize.css">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="//v4-alpha.getbootstrap.com/assets/css/docs.min.css">

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

    <button class="navbar-toggler navbar-toggler-right" data-toggle="collapse" data-target="#navbar-collapse">

    </button>

카테고리 설정

          게시판

            자유게시판
            피드백 게시판

Admin

 Git!

장식메뉴2

쪽지함가기

 나야나

로그아웃

          : 아이디를 누르면 채팅창이 열립니다.

      선풍기

      x

      sadsd

      <form class="new_message">
        <input name="conversation_id" type="hidden" value="2">
        <input name="user_id" type="hidden" value="3">
        <textarea name="body" class="form-control"></textarea>
        <input style="font-size: 13px; height: 30%;" type="submit" class="btn btn-warning" value="전송">
      </form>

          : 아이디를 누르면 채팅창이 열립니다.

      냉장고

      x

      asdsad

      하하하

      <form class="new_message">
        <input name="conversation_id" type="hidden" value="3">
        <input name="user_id" type="hidden" value="3">
        <textarea name="body" class="form-control"></textarea>
        <input style="font-size: 13px; height: 30%;" type="submit" class="btn btn-warning" value="전송">
      </form>

쪽지 보내기

선풍기

냉장고

Sjeisjd

    : 닉네임을 누르면 메세지를 전송할 수 있습니다.

A: This problem can be fixed with some HTML. Just put this below both floats like so:
<your right float div>
<your left float div>


text:
Q: Windows Forms sizes not matching I've got some very strict requirements on windows form sizes for elements and I've been having some trouble actually matching that up, I figured out the problem but I don't understand why I'm getting it. I have a picture box that needs to be a specific size, when I set it to that size in the properties panel of visual studio, it doesn't actually take that size, but a value smaller than that. It was throwing off my development. I can rectify it by manually setting the size value in the form code, however I'd like to know why the properties tab doesn't automatically do it correctly. I've just got it outputting the precise size value to a message box.

A: I have noticed the exact same behaviour in my project today. The form and all objects on it hat a certain size, but when run, the size was all different.
After checking the InitializeComponents() I found this line
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

so I checked the according property, and I changed it to "None".
Have never actually witnessed this behaviour before, but this did the trick for me. Now the Forms and everything else has the specified size.

A: The Size is actually size of whole window including the borders of windows form. You can see that the inner portion has exactly 18 pixels less for both width and height. You might calculate the desired width and height to assign to the form. Like if you want 100 x 100 pixel inner window size, you can assign 118 x 118 pixel for the size.

A: Any of the following properties of PictureBox could have caused it:

*

*Anchor

*Dock

*Margin

*MinimumSize

*MaximumSize

*SizeMode

Also need to check the direct parent (container) of your PictureBox. Is it directly put in the Form, or inside another container like GroupBox or Panel? If latter is the case, you should check properties of the parent object too.

A: Size of you pictureBox is determined according to size of Form. That is why you picturebox does not fit size you defined.


text:
Q: correct jquery syntax on the each of the selector for checking class I am trying to check for a class if it not exists then do some work, else skip it over
    $.each($(":not textarea.hasClass('encypted')", "#"+formID),function(k){
   do the code part
});

what i am doing here is to check if the textarea does not have a class encypted and only then go inside and do its work, if it has that class, just skip the entire code part

A: You can use :not() to directly select the textareas which do not have the given class:
$(`#${formID} textarea:not(.encrypted)`).each(function() {
  // your code here...
});


text:
Q: Ubuntu 11.10 64 bit won't start after I upgrade it, possible procesor problems? I have a HP 630 with an i3 processor on which I run Windows 7 64 bit without any problems, I also dual booted Ubuntu 10.04 32 bit I believe, now I upgraded to 11.10 and the clean install doesn't have any apparent problems.
But first thing I update, my Ubuntu won't start it just goes into the purple screen, or more rarely a black screen with a blinking cursor, where it stays indefenetly. The only clue I could find was that when I entered recovery mode the last instruction which appeared on screen before it friezed was:
Booting Node 0,Processors #1

After I tried to install the 32 bit version of Ubuntu 11.10 from a USB stick It froze at exactly the same instruction and wouldn't let me install.
So it's a dual core problem, and maybe a BIOS problem, because it seems that it doesn't want to pass from one processor to another, I added to the grub command line maxcpus=1 and it worked but I don't think it's healthy and it looks like hell.
What is the problem and how do I fix it?

A: So I will close this, a stop gap solution seems to be adding adding maxcpus=1 but I think I will have to wait for the dev team to trully fix it.

A: Got the same problem with Ubuntu 11.10 64 bit and now on 12.04 64 bit. My laptop is Lenovo G460 with Intel i3 350 processor. Try to update your BIOS. After updating mine, Ubuntu boot normally.


text:
Q: Correlation between categorical and numerical variables: TypeError I have some problems in calculating correlation between categorical and numerical variables.
I have a dataset(head(5) shown below):
    A     C   Label
0   a1  gt2016  0
1   a2  gt2016  0
2   b13 gt2016  0
3   a5  gt2016  1
4   b12 gt2016  1

and I would like to find the correlation between C and Label. Since C contains categorical variables, I used a dummy variable as follows:
df_dummies = pd.get_dummies(df['C'])
del df_dummies[df_dummies.columns[-1]]
df_new = pd.concat([df, df_dummies], axis=1)
del df_new['C]

However, when I calculate the correlation as follows
x = df_new.values
correlation_matrix = np.corrcoef(x.T)
print(correlation_matrix)

I get this error:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Can you please give me if I missed a step in calculating the correlation in order to fix the issue?

A: Recall that correlation is defined as
r = cov(X,Y) / sqrt(var(X) var(Y))
So you cannot have correlation with a constant since it's variance is 0, and C is always gt2016. But supposing there was variation, the following code would work for getting correlation between Label and each value of C:
df = pd.DataFrame({'A': ['a1', 'a2', 'b13', 'a5', 'b12'], 'C': ['gt2016']*4 + ['hi'], 'Label': [0,0,0,1,1]})

df_dummies = pd.get_dummies(df['C'])
df_new = pd.concat([df.drop('C', axis=1), df_dummies], axis=1)
df_new.corr()


text:
Q: MariaDB failed to start I have to fix an issue on a VM for a website that use Mariadb technology. When I type "systemctl start mariadb", it shows :
Job for mariadb.service failed because the control process exited with error code.
See "systemctl status mariadb.service" and "journalctl -xe" for details.

Here is what I have in error.log:
 2020-12-23 20:17:52 0 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2020-12-23 20:17:52 0 [ERROR] mysqld: Can't lock aria control file '/var/lib/mysql/aria_log_control' for exclusive use, error: 11. Will retry for 30 seconds
2020-12-23 20:18:23 0 [ERROR] mysqld: Got error 'Could not get an exclusive lock; file is probably in use by another process' when trying to use aria control file '/var/lib/mysql/aria_log_control'
2020-12-23 20:18:23 0 [ERROR] Plugin 'Aria' init function returned error.
2020-12-23 20:18:23 0 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed.
2020-12-23 20:18:23 0 [Note] InnoDB: Using Linux native AIO
2020-12-23 20:18:23 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2020-12-23 20:18:23 0 [Note] InnoDB: Uses event mutexes
2020-12-23 20:18:23 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2020-12-23 20:18:23 0 [Note] InnoDB: Number of pools: 1
2020-12-23 20:18:23 0 [Note] InnoDB: Using SSE2 crc32 instructions
2020-12-23 20:18:23 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2020-12-23 20:18:23 0 [Note] InnoDB: Completed initialization of buffer pool
2020-12-23 20:18:23 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2020-12-23 20:18:23 0 [ERROR] InnoDB: Unable to lock ./ibdata1 error: 11
2020-12-23 20:18:23 0 [Note] InnoDB: Check that you do not already have another mysqld process using the same InnoDB data or log files.
2020-12-23 20:18:23 0 [Note] InnoDB: Retrying to lock the first data file
2020-12-23 20:18:24 0 [ERROR] InnoDB: Unable to lock ./ibdata1 error: 11

I have searched similar issues but solutions didn't work.
Thank you very much for your help.
Update : When I killall mysqld and I restart it, I have same issues


text:
Q: How does a benchtop power supply measure and control current? This may be a simple question, but it is something that I can't seem to wrap my head around.
I have a +12v 5A power supply at work which has two knobs, one for voltage and one for current.
There are various devices that upon plugging them in I have to increase the current otherwise they will not work, but when I do this, the voltage level stays the same.
My question is, what exactly is happening when I turn the amperage knob on a benchtop power supply? My guess would be that we are changing the resistance being supplied to the device but I am unsure and would love a real explanation!
Thanks!

A: You most likely have a switching power supply that measures the current through a shunt resistor before the output voltage is measured - because the two are in series the power supply knows the output current is the same as the shunt current
The logic then follows something like if the voltage is less than the knob set, and the current is less than the knob set, then turn on the switch, and if it's higher on either, turn off the switch - then after the switch there is a smoothing capacitor or similar to reduce the ripple to where you won't notice it

A: Here is one current-limiting circuit

simulate this circuit – Schematic created using CircuitLab

A: For most uses of a bench power supply you're interested in providing a steady voltage. That's what the voltage setting is for. The current setting is a current limiter -- if your load draws more current than you've set the limiter for, it lowers the voltage until the load draws only the amount that you set the limiter for.
The idea is to keep your electronics from frying if you've made a mistake.


text:
Q: Sqoop and Multiline free form query I'm trying to sqoop some data using a free form query, it's only that my queries are pretty long (several JOINs and PIVOT for several columns) and it's really messy to include within the Sqoop command itself. I know that I can create a .props file and put my query there. My file.props is of the form:
import
--connect
jdbc:oracle:thin:@hostname:port:sid
--username
user
--password
password1
--query
'SELECT col1, col2, ..., col18,"'pivotedcol1'", ..., "'pivotedcol21'"\
FROM (SELECT col1, ..., col18, DEFINITIONS,\
      to_char(to_date(TIME),'DD.MM.YY', 'YYYY-MM-DD')   \
       FROM    table1\
       LEFT OUTER JOIN table2\
       ON      table2.colX = table1.colX\
         LEFT OUTER JOIN table3\
       ON      table2.colY = table3.colX\
       LEFT OUTER JOIN table4\
       ON      table4.colX = table1.colX\
         LEFT OUTER JOIN table5\
       ON      table5.colX = table4.colY\
         LEFT OUTER JOIN table6\
       ON      table5.colY = table6.colX\
         LEFT OUTER JOIN table7\
       ON      table7.colX = table1.colX\
         LEFT OUTER JOIN table8\
       ON      table7.colY = table8.colX\
     WHERE ROWNUM <= 45000 AND $CONDITIONS)\
PIVOT (MAX(TIME) FOR DEFINITIONS IN ('pivotedcol1', ..., 'pivotedcol21'))'
--as-avrodatafile
--verbose
--target-dir
directory/freeform

After running
sqoop --options-file file.props

I get an error
ERROR sqoop.Sqoop: Error while expanding arguments java.lang.Exception: Multiline quoted strings not supported in file(file.props)

Where's mistake? Can I be doing something better?

A: You need to do two things here.

*

*Put double quotes for SQL Query and remove backslashes (/)

*Put backslash infront of $CONDITIONS.
SELECT col1, col2 FROM table where rownum<=45000 AND \$CONDITIONS


text:
Q: How to create multi row as header of Material UI Datatable We are using Material UI and using <MUIDataTable> To display table.
We have multiple row as table header which is were we have to do colspan 2-3 columns also.
Looking for, How to customise table header column in a way that we can have multiple row as header.
I am new to React and Material UI, any hint or suggestions will also helpful.

A: Might help others...
Using customHeadRender we can customize table header column.
Here is example.
I used two div in on column and added line between these div.
Limitations: In my case sorting and searching on these(customized header) column are not required so no need to write logic for this but after customisation need to think about these functionality provide my MUi-datatable.


text:
Q: Can I use the fact that {0} is a subring of every ring in this statements? Prove:
a) A subring $S$ of a ring with unity $R$ does not have to be a ring with unity.
b) A subring $S$ of a ring $R$ without unity can contain a unity.
c) A subring $S$ of a ring $R$ can have a unity which is different than $1_R$
In b) and c), is it enough to say that {0} is a subring of every ring, and 0 is a unity in it?
Also, how to show a)?

A: For part $a$, look at $2\mathbb{Z} \subseteq \mathbb{Z}$.
Your solution to parts $b$ and $c$ seem correct.

A: a) You already know several subsets of $\Bbb{Z}$ which are closed under addition and multiplication and do not contain $1$.  They're kernels of $\Bbb{Z} \rightarrow \Bbb{Z}: z \mapsto [z \pmod{p}]$ for primes $p$.
b) and c)  If your definition of subring allows the trivial ring (which is usually the case), then the trivial ring, which you recite, is an example.


text:
Q: What is the formula for the surface area and volume of a concave cylinder? What is the formula for the surface area and volume of a concave cylinder, with radial radius 'r' and longitudinal radius 'R'?
To explain a bit more, the shape is bicurved, based on a cylinder with radius r but with a narrower mid-point, with a radius R of curvature to either end, .
The shape is encountered in a liquid 'capillary bridge' in which a drop of liquid between two cylindrical surfaces is slightly stretched.
Any help greatly appreciated. Thanks Julian

A: If the cross section of the shape is always circular, then the area of each infinitesimally thin cross section is
$$A(r) = \pi r^2$$
where $r = r(t)$ is measured perpendicular to the line between the axis endpoints at $t=0$ and $t=h$, so that the deflection of the centerpoint from that axis does not matter.
In other words, if we assume the shape to have its axis between $(0,0,0)$ and $(0,0,z)$, each infinitesimally thin slice is taken on the $xy$ plane, and the radius $r(z)$ measured in the $xy$ plane. It does not then matter how much the axis then deflects (in the $xy$ plane) in $0 \lt z \lt h$.
(For an analog, consider a 2D parallelogram. If $w$ is the length of two opposite sides, and $h$ is the distance between the two (height), the area is always $wh$ no matter how skewed the parallelogram is. Here, we measure the radius similar to measuring the height of the parallelogram, and axis deflection corresponds to skewing the parallelogram.)
The volume is then a simple integral:
$$V = \int_{0}^{h} A(z) dz = \pi \int_{0}^{h} r(z)^2 dz$$
If the radius is symmetric with respect to the center of the bridge, and is described using function $r(t)$, with $r(0)$ being the radius at endpoints, and $r(1)$ the radius at center, the integral simplifies to
$$V = \pi h \int_0^1 r(t)^2 dt$$
For example, if the radius follows a simple interpolating polynomial ($3 t^2 - 2 t^3$),
$$r(t) = r_0 + 3 (r_1 - r_0) t^2 - 2 (r_1 - r_0) t^3 = 2 (r_0 - r_1) t^3 - 3 (r_0 - r_1) t^2 + r_0$$
then
$$V = \frac{\pi h}{35}\left( 13 r_0^2 + 9 r_0 r_1 + 13 r_1^2 \right)$$
Another example: If the radius follows a cosine curve, then
$$r(t) = r_0 + \frac{r_1 - r_0}{2} \left( 1 - \cos(\pi t) \right )$$
and
$$V = \frac{\pi h}{8}\left( 3 r_0^2 + 2 r_0 r_1 + 3 r_1^2 \right)$$


text:
Q: Create a Django's model which can have one of two types I have a model Client which can be one of two types: PJ or PF. That means that a Client can have the fields of a PJ model or the fields of a PFmodel.
But I'm not sure how I can do it using the Django's models and admin app. I would like to give the user the option to select which type the Client is and then the appropriate fields will be shown to him/her.
Can someone help me with this problem? Should I use some kind of Design Pattern or how should I create my models?
Thanks in advance.

Model PF:
class PF(models.Model):
    name = models.CharField(max_length=512)
    card = models.IntegerField(unique=True)

Model PJ:
class PJ(models.Model):
    ie = models.IntegerField(unique=True, null=True, blank=True)

Model Client:
class Client(models.Model):
    type = models.SmallIntegerField(default=0) # 0=PF, 1=PJ

A: First I'd recommend to look at the commonality between these two models and use inheritance if you can. If a type field is inevitable, I'd recommend using CharField with choices instead.
If the two models are drastically different, I'd recommend separating these two models completely, and call them InternalClient, ExternalClient, however the name would make sense to the data model.


text:
Q: Getting Compilation error while using "Microsoft.office.Server.Search.Query.dll" DLL
We are using sharepoint 2007.We have reference to "Microsoft.office.Server.Search.Query" assembly in one custom page.
on that page we are using KeywordQuery to search on scope.
We are getting below Compilation error on any point of time on that search page.
" Compiler Error Message: CS0234: The type or namespace name 'Office does not exist in the namespace 'Microsoft'(are you missing an assembly reference?) "
PFA image is the screenshot of that error page
The solution to resolve this error is
We go to server and from port 80 bin folder of inetpub we just cut and paste "Microsoft.office.Server.Search.Query.dll"
after doing cut+paste all works normal but error occurs again n again.
We want to fix this issue permanently.If any one have any solution on this please share.


text:
Q: gdiplus members is ambiguous I'm trying to run code from this page http://msdn.microsoft.com/en-us/library/windows/desktop/ms534077(v=vs.85).aspx  in win32 console application (VS 2012)
and have this errors:
Error   3   error LNK2019: unresolved external symbol _GdiplusStartup@12 referenced in function _main   c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   4   error LNK2019: unresolved external symbol _GdiplusShutdown@4 referenced in function _main   c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   6   error LNK2019: unresolved external symbol _GdipLoadImageFromFileICM@8 referenced in function "public: __thiscall Gdiplus::Image::Image(wchar_t const *,int)" (??0Image@Gdiplus@@QAE@PB_WH@Z)    c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   5   error LNK2019: unresolved external symbol _GdipLoadImageFromFile@8 referenced in function "public: __thiscall Gdiplus::Image::Image(wchar_t const *,int)" (??0Image@Gdiplus@@QAE@PB_WH@Z)   c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   9   error LNK2019: unresolved external symbol _GdipGetImageWidth@8 referenced in function "public: unsigned int __thiscall Gdiplus::Image::GetWidth(void)" (?GetWidth@Image@Gdiplus@@QAEIXZ)    c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   10  error LNK2019: unresolved external symbol _GdipGetImageHeight@8 referenced in function "public: unsigned int __thiscall Gdiplus::Image::GetHeight(void)" (?GetHeight@Image@Gdiplus@@QAEIXZ) c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   2   error LNK2019: unresolved external symbol _GdipFree@4 referenced in function "public: static void __cdecl Gdiplus::GdiplusBase::operator delete(void *)" (??3GdiplusBase@Gdiplus@@SAXPAX@Z) c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   8   error LNK2019: unresolved external symbol _GdipDisposeImage@4 referenced in function "public: virtual __thiscall Gdiplus::Image::~Image(void)" (??1Image@Gdiplus@@UAE@XZ)   c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   7   error LNK2019: unresolved external symbol _GdipCloneImage@8 referenced in function "public: virtual class Gdiplus::Image * __thiscall Gdiplus::Image::Clone(void)" (?Clone@Image@Gdiplus@@UAEPAV12@XZ)  c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   1   error LNK2019: unresolved external symbol _GdipAlloc@4 referenced in function "public: static void * __cdecl Gdiplus::GdiplusBase::operator new(unsigned int)" (??2GdiplusBase@Gdiplus@@SAPAXI@Z)   c:\Users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.obj    ConsoleApplication4
Error   11  error LNK1120: 10 unresolved externals  c:\users\администратор\documents\visual studio 2012\Projects\ConsoleApplication4\Debug\ConsoleApplication4.exe  ConsoleApplication4

in gdiplusinit.h i see that GdiplusStartupInput,GdiplusStartupOutput,DebugEventLevel is ambiquous. Any knows how fix this?

A: There's no ambiguity here, you simply forgot to link gdiplus.lib.  Add it to the linker's Input + Additional Dependencies setting.
An easy way is to put the link directive in your source code:
#include <windows.h>
#include <gdiplus.h>
#pragma comment(lib,"gdiplus.lib")

A: All the errors you posted are symbols not resolved by the Linker.
It seems you forgot to add a lib (something like gdi.lib or gdiplus.lib ) to your VS project.


text:
Q: Find an algorithm that minimize the maximum distance of two sets, better than Greedy algorithm Here is the interesting but complicated problem:
Suppose we have two sets of points. One set A includes points in some space grid, like regular 1D or 3D grid. The other set B includes points that are randomly spaced and are of the same size as the space grid. Mathematically, we could order the two sets and construct a corresponding matrix with respect to the distance between A and B. For example, A(i, j) may refer to the distance between i of A and j of B.
Given some ordering, we have a matrix. Then, the diagonal element (i,i) in the matrix is the distance between point i of A and point i of B. The problem is how to find a good reordering/indexing such that the maximum distance is as small as possible? In matrix form, how to find a good reordering/indexing such that the largest diagonal element as small as possible?
Notes from myself:

*

*Suppose set A is corresponding to rows of the matrix, and set B is to columns of the matrix. Then reordering the matrix means we are doing row/column permutation. Therefore, our problem is equivalent to find a good permutation to minimize the largest diagonal element.

*Greedy algorithm may be a choice. But I am trying to find an ideally perfect reordering that minimize the largest diagonal element.

A: The reordering you are referring to is essentially a correspondence problem i.e. you are trying to find the closest match for each point in the other set. The greedy algorithm will work fine. The distance you are looking for is commonly referred to as the Hausdorff distance.


text:
Q: Assigned texture to glb model in Three.js is reversed and only working with THREE.RepeatWrapping I load a glb model in Three.js generated in SketchUp. The file can be found here https://www.graviditetsberegner.dk/bpnew.skp
The model contains a group called text with a mesh. I want to display a texture containing text here. I use the below code:
var modelLoader = new THREE.GLTFLoader();

modelLoader.load("https://www.graviditetsberegner.dk/bpnew.glb", function (gltf) {

model = gltf.scene.clone();
model.scale.set(50,50,50)
scene.add(model);

//Use canvas to draw texture and add it to the model group Text
var textModelMesh = FindMeshWithNameInModel(model, "Text");
var textTexture = CreateCanvasTexture("This is a test");

textTexture.wrapS = THREE.RepeatWrapping;
textTexture.wrapT = THREE.RepeatWrapping;

textModelMesh.material.map = textTexture;

I have two issues with the code:

*

*The text is mirrored. In other formats such as dae, the text is not mirrored

*The text is only displayed when I set wrapS and wrapT to RepeatWrapping. However, the texture used in SketchUp should be similar to the dimensions of the generated texture in the canvas.

How can I fix these issues?
A fiddle showing the problem: https://jsfiddle.net/Lgmds9ce/2/

A:
The text is mirrored. In other formats such as dae, the text is not mirrored

As mentioned in the official documentation for THREE.GLTFLoader you have to set Texture.flipY to false if you manually replace a texture.

The text is only displayed when I set wrapS and wrapT to RepeatWrapping. However, the texture used in SketchUp should be similar to the dimensions of the generated texture in the canvas.

The texture from the asset has also set Texture.wrapS and Texture.wrapT to THREE.RepeatWrapping.
Updated fiddle: https://jsfiddle.net/d12t6p5q/1/
three.js R105


text:
Q: What does elastic search Store, and how? Elastic search is a search engine, according to Wikipedia. This implies it is not a database, and does not store the data it is indexing (but presumably does store its indexes)
There are presumably 2 ways to get data into Es. Log shipping or directly via api.
Let's say my app wants to write an old fashioned log file entry:
Logger.error(now() + " something bad happened in module " + module + ";" + message"
This could either write to a file or put the data directly in es using a rest api.
If it was done via rest api, does es store the entire log message, in which case you dont need to waste disk writing the logs to files for compliance etc. Or does it only index the data, so you need to keep a separate copy?  If you delete or move the original log file, how does es know, and is what it Deos store still usefull?
If you write to a log file, then use log stash or similar to "put the log data in es" does es store the entire log file as well as any indexes?
How does es parse or index arbitrary log files? Does it treat a log line as a single string, or does it require logs to have a specific format such as cvs or Jason?
Does anyone know of a resource with this key info?

A: Elasticsearch does store the data you are indexing.
When you ingest data into elasticsearch, this data is stored in one or more index and then it can be searched. To be able to search something with elasticsearch you need to store the data in elasticsearch, it can not for example search on external files.
In your example, if you have an app sending logs do elasticsearch, it will store the entire message you send and after it is in elasticsearch you don't need the original log anymore.
If you need to parse your documents in different fields you can do it before sending the log to elasticsearch as a json document, use logstash to do this or use an ingest pipeline in elasticsearch.
A good starting point to know more about how it works is the official documentation


text:
Q: A way to show all uploaded video folders on the homepage? On my website, there is a video upload section. It generates a link ending string based on random numbers and time, and then gives to the user to share. This link shows a page with their video. On the homepage I would like to show every one of the videos uploaded, but the videos are all in their seperate folders, etc: 234209346/video.mp4
I want to show this video file in a video tag, but i need it to check every subdirectory for videos and show them there, based on date. I'm very new to php, so please explain things.

A: Option 1: Best - Change your approach
When you save the videos, use a Database to save each video information. This way you will be able to quickly retrieve all the videos very quickly in your homepage.
If you don't have Mysql installed, you can also use a .sqlite local file or even a CSV/JSON. But storing the info is much better than just looking for files at runtime
Option 2: Bad, but exactly what you requested - recursive file listing
Read here for another answer on how to do recursive file listing. The only difference is that you will need to check the files to have the correct .mp4 extension, checking the filename.


text:
Q: Why is the desktop descriptor in GDI+ is limited to one monitor? I am trying to draw to the screen directly in C# via the Graphics object retrieved from Graphics.FromHwnd(IntPtr.Zero) but I am limited to the primary monitor for some reason.
Upon inspecting the Graphics object, I found that the VisibleClipBounds are limited to my first monitors resolution.
I have two 1920x1080 monitors, so, I guess, that property has to be 3840x1080.
Is there a way to solve my issue?
The code is really simple, I have a wrapper class that looks like this:
public class ScreenCropperDrawer
{
    private static Graphics screenGraphics;

    public static void FillRectangle(Brush brush, Rectangle rect)
    {
        if (screenGraphics == null)
        {
            screenGraphics = Graphics.FromHwnd(IntPtr.Zero);
        }
        screenGraphics.FillRectangle(brush, rect);
    }
}


text:
Q: How to filter advisories from GitHub GraphQL by ecosystem Links first

*

*https://docs.github.com/en/graphql/overview/explorer

*https://github.com/advisories

*https://docs.github.com/en/graphql/reference/
I am trying
{
    securityAdvisories(first: 100, ecosystem: nuget) {
    totalCount
    pageInfo {
        endCursor
        startCursor
    }
    nodes {
        description
        summary
        cvss {
        vectorString
        }
        databaseId
        identifiers {
        type
        value
        }
        ghsaId
    }
    }
}

I am getting Field 'securityAdvisories' doesn't accept argument 'ecosystem'"
I see the field ecosystem in the https://docs.github.com/en/graphql/reference/objects#securityadvisorypackage
How do I filter by "ecosystem"?
This is possible, because I can do https://github.com/advisories?query=ecosystem%3Anuget
How do I get all 113 advisories?
Update
I can filter vulnerabilities belonging to an advisory by ecosystem.
  vulnerabilities(first: 10, ecosystem: NUGET) {
    edges {
      node {
        advisory {
          id
        }
      }
    }

Update 2
I crawl the UI first
page=1;while [ 1 ];do  curl "https://github.com/advisories?page=$count&query=ecosystem%3Anuget" -o $count.txt;count=$((count+1));done
find -maxdepth 1 -name "*.txt" | xargs grep -oE "GHSA-\w{4}-\w{4}-\w{4}"

After I have the list of GHSA I run this a bit cryptic Python
import requests
import easyargs

template="""
{"query": "query securityAdvisory(ghsaId: \\"GHSA_VALUE\\") {     id     description     ghsaId     permalink     summary     identifiers {       type       value     }     references {       url     }     origin     cwes(first: 10) {       nodes {         name         id         description         cweId       }     }     cvss {       score       vectorString     }     databaseId     publishedAt     notificationsPermalink     updatedAt     severity     withdrawnAt     vulnerabilities(first: 50) {       edges {         node {           severity           updatedAt           vulnerableVersionRange         }       }     }   } } "}
"""

# get token from https://github.com/settings/tokens
# ghsas is a list of GHSAs
@easyargs
def main(token=str, ghsas=str):
    with open(ghsas) as f:
        lines = f.readlines()

    for s in lines:
        s = s.strip()
        data=template.replace("GHSA_VALUE", s, 1)
        r = requests.post(url="https://api.github.com/graphql", data=data, headers={"Authorization":f"bearer {token}"})
        print(r.text)

if __name__ == '__main__':
    main()

I am sure there is a better solution. In the perfect world I would have a single line curl returning a JSON containing 113 Nuget related security avisories. I can't figure out how to query the GraphQL.

A: For the arguments you can filter by you need to look at documentation for the Query type, not the Object type, i.e. https://docs.github.com/en/graphql/reference/queries#securityadvisoryconnection
Since it doesn't have an entry for ecosystem you can't filter your query results by ecosystem. You can return the ecosystem though (by adding it to your node block), then filter the results by ecosystem once they've been returned to you.
The things you can filter by are stored as redundant data in the graph, which means the backend can avoid visiting the node altogether. Obviously there's a cost to that though, so it's only done for things that people will commonly want to filter by


text:
Q: Trouble understanding instructions to install gremlim plugin on neo4j I am trying to install the gremlin plugin for neo4j 2.1.4 on OS X 1.9.4
The instructions say to run these commands
mvn clean package
unzip target/neo4j-gremlin-plugin-2.1-SNAPSHOT-server-plugin.zip -d $NEO4J_HOME/plugins/gremlin-plugin
cd $NEO4J_HOME
bin/neo4j restart

I am confused by two things.
1) when I run maven clean package I get this error.  I would think you would run maven to build a project -- but it seems like the gremlin plugin instructions say to run it before downloading the source.
$ mvn clean package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

2) What is the meaning of target in this line of code? I would think that you are unzipping code that you have downloaded into the plugins directory of neo4j. But why does that line come after the mvn line? Wouldn't you unzip, cd to /gremlin-plugin and then run maven clean package?
unzip target/neo4j-gremlin-plugin-2.1-SNAPSHOT-server-plugin.zip -d $NEO4J_HOME/plugins/gremlin-plugin

I am doing the following:

*

*download zip file from https://github.com/neo4j-contrib/gremlin-plugin

*unzip to $NEO4J_HOME/plugins/gremlin-plugin

*reboot neo4j

I get:
LookupError: ({'status': '404', 'access-control-allow-origin': '*', 'content-type': 'application/json; charset=UTF-8', 'content-length': '752', 'server': 'Jetty(9.0.5.v20130815)'}, '{\n  "message" : "No such ServerPlugin: \\"GremlinPlugin\\"",\n  "exception" : "PluginLookupException",\n  "fullname" : "org.neo4j.server.plugins.PluginLookupException",\n  "stacktrace" : [ "org.neo4j.server.plugins.PluginManager.extension(PluginManager.java:115)", "org.neo4j.server.plugins.PluginManager.invoke(PluginManager.java:156)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:312)", "org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension(ExtensionService.java:134)", "java.lang.reflect.Method.invoke(Method.java:601)", "org.neo4j.server.rest.transactional.TransactionalRequestDispatcher.dispatch(TransactionalRequestDispatcher.java:139)", "java.lang.Thread.run(Thread.java:722)" ]\n}')

How can I follow the gremlin plugin instructions?

A: if you want to build the plugin from source, then do the following:
git clone https://github.com/thinkaurelius/neo4j-gremlin-plugin.git
cd neo4j-gremlin-plugin
# now follow the instructions (build, unzip, restart Neo4j server)

Your steps to install the prebuilt plugin look good to me. When do you get the LookupError?  When you restart Neo4j or when you try to use the plugin via curl or whatever? Did you add the plugin in $NEO4J_HOME/conf/neo4j-server.properties?
I also created a video that should answer all remaining questions:
Install and use Neo4j Gremlin plugin


text:
Q: element & fetch in cakephp2 What's the difference between 'fetch' and 'element' in cakephp2? I have this code
 echo $this->fetch('meta');

in the default.ctp and have no clue why it's there. Can't I just use $this->element('meta') and will have to create meta.ctp in the elements folder.
Also this code
echo $this->fetch('content');

is in the content portion. Can someone explain this please? Thanks.

A: fetch will get the data and render it over there.
 echo $this->fetch('meta');

Will fetch meta data that you have defined in the pages.
    echo $this->Html->meta(
        'keywords',
        'enter any meta keyword here'
    );
    // Output
    <meta name="keywords" content="enter any meta keyword here" />

    echo $this->Html->meta(
        'description',
        'enter any meta description here'
    );
    // Output
    <meta name="description" content="enter any meta description here" />`

echo $this->fetch('content');
Will render the content that is defined in the view files.


text:
Q: Cast object in lambda expression I'm trying to cast a List to my custom list which is ProjectList
IList<Project> projects = cm.GetOrAdd("projectList", () => (ProjectList)ProjectService.GetAllProjects().ToList(), new CacheItemPolicy(5));

ProjectList contains only:
public class ProjectList : List<Project>
{
    public override string ToString()
    {
        return string.Format("Projects: {0}", this.Count());
    }
}

However it's giving a runtime error that it cant cast the object.
Error:

System.Collections.Generic.List`1[sidc.Framework.Data.Entities.Project]
  can't be converted to type sidc.Framework.Web.Helpers.ProjectList.

Am I overseeing something? I'm using the lambda because my cm (CacheManager) will evaluate the Func<> when the object is not in cache.

A: You can't downcast a List<T> to any type that inherits from List<T>, because the runtime can't fill in the blanks for you. It wouldn't know how to create a "Dog" from an "Animal". That's what the compiler tries to tell you.
Add a constructor that accepts an enumerable of Project, and populates itself with that list:
public class ProjectList : List<Project>
{
    public ProjectList() { }
    public ProjectList(IEnumerable<Project> projects)
        : this()
    {
        this.AddRange(projects);
    }

    public override string ToString()
    {
        return string.Format("Projects: {0}", this.Count());
    }
}

Then change your lambda from:
() => (ProjectList)ProjectService.GetAllProjects().ToList()

To:
() => new ProjectList(ProjectService.GetAllProjects())

But by introducing a concrete type (ProjectList for List<Project>) you're pretty much annihilating the use of generics: not having to specify a type per record type. You probably don't need ProjectList at all.

A: This is just how inheritance works - you can cast ProjectList to List<Project>, but not the other way - List<Project> is not of type ProjectList


text:
Q: Panel Data with three identifiers My panel dataset consists of three identifiers:

*

*Country

*Industry

*Year

I would like to calculate the effects of a variable X across different industries.
I am confused how I should treat in Stata the panel dimension (identifier) since standard panel data techniques treats are two dimensional (i, t).
For example, if I want to run a fixed effects and random effects model to check the effects of a variable X across industries, what is the correct approach in this case?
Should i go with:
xtset country

or:
xtset country industry

A: You can do the following:
egen id = group(country industry)
xtset id year


text:
Q: Different no. of clusters for different data sets I am trying to plot results of multiple clustering algorithms on multiple data sets
The code is the following
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

from time import time

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale

from sklearn import cluster, datasets, mixture
from sklearn.neighbors import kneighbors_graph
from sklearn.preprocessing import StandardScaler

np.random.seed(0)

cs_arry=[[0,1,0,1],[1,0,0,1],[0,0,1,1],[1,1,0,1],[1,0,1,1],[0,1,1,1]]
cs_arry=np.array(cs_arry * 20)
colors = np.array([x for x in cs_arry])

#################
n_pts = 1500#####
#################

noisy_circles = datasets.make_circles(n_samples=n_pts, factor=.5, noise=.05)
no_structure = np.random.rand(n_pts, 2), None
my_circles=make_circ(n_samples=n_pts, factor=.35, noise=.025, in_fact=2)
##############################################
blob_centers = [(-10, -10), (-3, 10), (10, 10)] # adjust blob centers for blob data making
##############################################
blobs=datasets.make_blobs(n_samples=n_pts, n_features=3, centers=blob_centers, cluster_std=3,
                          center_box=(-20,20), shuffle=True, random_state=0)

clustering_names=['Input','K-means','K-medoids','AP','Spectral','Gaussian','Hierarchical']

nofclusters=3
plt.figure(figsize=(len(clustering_names) * 2 + 3, 9.5))
plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=0,
                    hspace=0)
data_sets = [noisy_circles, my_circles, blobs, no_structure]
plot_num = 1

for i_dataset, dataset in enumerate(data_sets):
    x, y = dataset
    x = StandardScaler().fit_transform(x)

    bandwidth = cluster.estimate_bandwidth(x, quantile=0.3)
    connectivity = kneighbors_graph(x, n_neighbors=10, include_self=False)
    connectivity = 0.5 * (connectivity + connectivity.T)

#clustering algorithms
    orig_data=cluster.KMeans(n_clusters=1)
    kmeans=cluster.KMeans(n_clusters=nofclusters,init='k-means++')
    Kmedoids=cluster.KMeans(n_clusters=nofclusters,init='random')
    heir = cluster.AgglomerativeClustering(n_clusters=nofclusters, linkage='ward',
                                           connectivity=connectivity)
    spectral = cluster.SpectralClustering(n_clusters=2,
                                          eigen_solver='arpack',
                                          affinity="nearest_neighbors")
    affinity_propagation = cluster.AffinityPropagation(damping=.9,
                                                       preference=-200)
    gmm=mixture.gmm(n_components=nofclusters, covariance_type='diag', random_state=None,
                    thresh=None, tol=0.001, min_covar=0.001, n_iter=100, n_init=1, params='wmc',
                    init_params='wmc', verbose=0)

    #####################################
    #####################################

    clustering_algo=[orig_data, kmeans, kmedoids, ap, spectral, gmm, heir]

    #####################################
    #####################################

    for name, algorithm in zip(clustering_names, clustering_algo):

        t0 = time.time()
        algorithm.fit(x)
        t1 = time.time()
        if hasattr(algorithm, 'labels_'):
            y_pred = algorithm.labels_.astype(np.int)
        else:
            y_pred = algorithm.predict(x)

        # plot
        plt.subplot(len(datasets), len(clustering_algo), plot_num)

        if i_dataset == 0:
            plt.title(name, size=18)
        if name=='Input':
            plt.scatter(x[:, 0], x[:, 1], color='k', s=10, marker='o', facecolors='none')
        else: plt.scatter(x[:, 0], x[:, 1], color=colors[y_pred], s=10, marker='o', facecolors='none')

        plt.xlim(-2, 2)
        plt.ylim(-2, 2)
        plt.xticks(())
        plt.yticks(())
        if name!='Input':
            plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),
                     transform=plt.gca().transAxes, size=15,
                     horizontalalignment='right')
        plot_num += 1

plt.show()

I was wondering if there is a way to set different numbers of clusters for different datasets. Specifically, I want the circle datas to have 2 clusters while the remaining sets have 3.
I tried inserting
if data_sets==noisy_circles or my_circles:
     nofclusters=2

or
while data_sets==noisy_circles or my_circles:
     nofclusters=2

before and after the for loop statement with no results.
Any help is appreciated.
Thank you.

A: Use a dictionary, so you can easily configure the number of clusters for each data set. You will also need to choose many other parameters, such as epsilon and minpts in DBSCAN.
You need to do it inside the for loop obviously, and make sure to set the value at every iteration. Otherwise, the next iteration may get the previous value, and you get incorrect results.


text:
Q: Core Data Swift - Not Creating SQLite file I am new to Core Data and have followed a few tutorials. However I don't seem to be able to access the .sqlite file either on the simulator or on my iPhone 6. The debugger prints the following. Can anyone provide any assistance please?

2015-07-17 11:31:28.006 Rockford[390:32594] CoreData: error: (1) I/O error for database at /var/mobile/Containers/Data/Application/D2A80335-E681-4194-944D-CAE66F80EFA6/Documents/Rockford.sqlite.  SQLite error code:1, 'unknown database ZROCKFORD'
  2015-07-17 11:31:28.011 Rockford[390:32594] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///var/mobile/Containers/Data/Application/D2A80335-E681-4194-944D-CAE66F80EFA6/Documents/Rockford.sqlite options:{
      NSInferMappingModelAutomaticallyOption = 1;
      NSMigratePersistentStoresAutomaticallyOption = 1;
  } ... returned error Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn't be completed. (Cocoa error 256.)" UserInfo=0x170460a40 {NSSQLiteErrorDomain=1, NSUnderlyingException=I/O error for database at /var/mobile/Containers/Data/Application/D2A80335-E681-4194-944D-CAE66F80EFA6/Documents/Rockford.sqlite.  SQLite error code:1, 'unknown database ZROCKFORD'} with userInfo dictionary {
      NSSQLiteErrorDomain = 1;
      NSUnderlyingException = "I/O error for database at /var/mobile/Containers/Data/Application/D2A80335-E681-4194-944D-CAE66F80EFA6/Documents/Rockford.sqlite.  SQLite error code:1, 'unknown database ZROCKFORD'";

A: Just delete the App from the simulator/device and run it again. It may happen when you make some changes in core data part of your project and the device have the previously created database.


text:
Q: Disk ID update after partition cloning from HDD to SSD I am looking forward to adding SSD in a laptop and in a desktop both currently having single HDD each. Laptop has single partition (well apart from the Recovery and OEM) and desktop has two partitions  (again apart from System Reserved). Both HDDs are significantly greater in size (used space is more as well) than the SSDs. While I understand the easiest way is to just copy the data off of the HDDs so that they have less data than the SSD size, reduce the partition size and then do partition cloning using GParted, Clonezilla or EaseUS Partition Manager. However I would like to use the partition cloning to clone only boot/system partition in case of desktop that has a rather large HDD. I would like to keep the respective HDDs in both systems without formatting them. In Desktop I would like to leave it internal and make the SSD as boot drive and in laptop I would make the HDD as an external drive via USB/eSata enclosure. I am getting inclined to use GParted/EaseUS to do this. I have gone thru this, this for GParted and this for EaseUS and many more. I have few doubts though.

*

*After the disk is cloned, the cloned disk would have same Disk ID and a machine cannot have two disks with same Disk ID. Is this true for the external USB/eSata drives as well?

*Is there a simpler way to change the Disk IDs of the cloned HDD? The method given in this is fine but I would like to know if there is a simpler way.

*How to make the SSD in the desktop as boot drive, as the machine would have two disks both having MBR and valid bootable data (in fact identical). I believe this is just a boot device priority in BIOS. Is that correct?

*Anything else I might have missed.

The laptop has Windows 7 and the desktop has Windows 8 RC, if that matters.

A: My usual procedure was as follows...

*

*Partition the new drive

*Run Ghost and copy over the required partitions

*Run RPM (Ranish Partition Manager) again to make sure the boot part is selected

*BOOT INTO WINDOWS WITH ONLY THE NEW DRIVE CONNECTED

*Shutdown, add the old drive, deselect the boot partition on it and make sure the BIOS has the NEW drive as a higher priority drive

*Turn off and on...

Windows used to sort itself doing it that way. Do beware, this is all from memory. Ghost is commercial and RPM is very old.
But so am I.


text:
Q: Javascript single use variable declaration This may be a obvious question, but I was wondering if there was an efficiency difference between declaring something in a one time use variable or simply executing the code once (rather then storing it then using it). For example
var rowId = 3,
updateStuff(rowId);

VS
updateStuff(3);

A: I think that worrying about performance in this instance is largely irrelevant. These sorts of micro-optimizations don't really buy you all that much. In my opinion, the readability of the code here is more important, since it's better to identify the 3 as rowId than leaving it as a magic number.
If you are really concerned about optimization, minimizing your code with something like Google Closure would help; it has many tools that will help you make your code more efficient.

A: If you were using google closure to compile and if you annotated the var as a constant (as it appears in your example), I suspect the compiler would remove the constant and replace it with the literal.
My advice is to pick the readable option and if you really need the micro-optimizations and reduction in source size, use the google closure compiler or a minifier-- a tool is more likeley to accumulate enough micro-optimizations to make something noticeably faster, although I'd guess most of the saved milliseconds would come from reduced network time from minification.
And var declarations do take time and if you added that var to the global namespace, then there is one more thing that will be searched during resolving names.

A: With a modern browser that compiles your code, the generated code will be exactly the same unless the variable is referenced somewhere else also.
Even with an old browser if there is a difference it won't be something to worry about.

A: EDIT:
delete does not apply to non-objects, therefore my initial response was wrong. Furtermore  since the variable rowId is declared with the flag var it will be cleaned up by the garbage collection. Was it on the other hand defined without, it would live for the duration of the page / application.
source: http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/

The variable rowId will be kept in memory and will not be released by the garbage collector since it's referenced to. Unless you release it afterwards like below it will be there till the end of the programs life. Also remember it take time to create the variable (minimal, but you asked)
   var rowId = 3
   updateStuff(rowId);
   delete rowId

With efficiency in mind, then yes there is a difference. Your second example is the quickest and doesn't spend any extra resources.
OBS. Some languages do optimize code as such and simply remove the sequence, but I strongly doubt that JavaScript does so.


text:
Q: Having Trouble With POST Bodies in Javascript (window.fetch) I'm using HTML5 and javascript but I could not make a POST request to a URL with a body. The code I used is:
var username = document.getElementById('uname').value;
var password = document.getElementById('pword').value;
var rbody = JSON.stringify({username, password});
window.fetch('https://somewhere.com/some/path', {
    method: 'POST',
    body: rbody
})
.then(res=> {
    console.log(res.body);
    return res.text()
}).then(res=> {
    if(res === 'true') {
        window.localStorage.setItem('loginDetails', {
            username,
            password
        });
        window.location = "https://somewhere.com/home";
    }
    else alert('Girdiğiniz kullanıcı ismi ya da şifre yanlış.');
});

The requests' bodies were empty. I couldn't make a request with a body :(
Thanks for your helps in advance.

A: I've just run your code like this and it worked:
var username = 'username';
var password = 'password';
var rbody = JSON.stringify({username, password});
window.fetch('https://somewhere.com/some/path', {method: 'POST', body: rbody}).then(res=> {console.log(res.body);  return res.text()}).then(res=> {
  if(res === 'true') {
    window.localStorage.setItem('loginDetails', {username, password});
    window.location = "https://somewhere.com/home";
  }
  else alert('Girdiğiniz kullanıcı ismi ya da şifre yanlış.');
});

Open Developer Tools, check 'Preserve Log' option on 'Network' tab and run it on Console. Then go back to 'Network' tab and check the request (Headers tab, Request Payload). The body is sent.

A: There is no issue with the way you are making the request, but I think the back end is not sending proper data or there is some error. You can open the console and in the network tab, you can see the request is going properly. you can also see the response returned there.
One thing that you are not doing though is checking for errors
var username = document.getElementById('uname').value;
var password = document.getElementById('pword').value;
var rbody = JSON.stringify({ username, password });
window
    .fetch('https://somewhere.com/some/path', { method: 'POST', body: rbody })
    .then(res => {
        if(!res.ok)
            return Promise.reject(new Error(response.statusText));
        return res.text()
    })
    .then(res => {
        if (res === 'true') {
            window.localStorage.setItem('loginDetails', { username, password });
            window.location = "https://somewhere.com/home";
        }
        else alert('Girdiğiniz kullanıcı ismi ya da şifre yanlış.');
    })
    .catch((err) => {
        //handle errors here
        console.log(err);
    });

A: Thanks for help guys, but none of them worked for me. I searched more and found $.ajax (jquery) Now I'm using $.ajax and it's working fine.
Here is the code I used (I added form):
$.ajax({
    url:'/api/checkpassword',
    type:'post',
    data:$('#logInForm').serialize(),
    success:function(res){
        if(res === 'true' || res === true) {
          window.localStorage.setItem('loginDetails', {username: document.getElementById('uname').value, password:document.getElementById('pword').value});
          window.location = "https://dchat.glitch.me/home";
        }
        else alert('Girdiğiniz kullanıcı ismi ya da şifre yanlış.');
    }
});


text:
Q: Application crash only on device but not on emulator The error:
04-24 08:48:10.779: INFO/Database(31359): sqlite returned: error code = 14, msg = cannot open file at source line 25467
What could be the error that could disturb just the device and not the emulator?
Where I should start to check?
public class DBHelper extends SQLiteOpenHelper {

private static String DB_PATH = "";
private static final String DB_NAME = "med.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;

private static DBHelper mDBConnection;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
private DBHelper(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
    DB_PATH = "/data/data/"+ context.getApplicationContext().getPackageName()   + "/databases/";
    // The Android's default system path of your application database is
    // "/data/data/mypackagename/databases/"
}

/**
 * getting Instance
 * @param context
 * @return DBAdapter
 */
public static synchronized DBHelper getDBAdapterInstance(Context context) {
    if (mDBConnection == null) {
        mDBConnection = new DBHelper(context);
    }
    return mDBConnection;
}

/**
 * Creates an empty database on the system and rewrites it with your own database.
 **/
public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    if (dbExist) {
        // do nothing - database already exist
    } else {
        // By calling following method
        // 1) an empty database will be created into the default system path of your application
        // 2) than we overwrite that database with our database.
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        // database does't exist yet.
    }
    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {
        // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);
        // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;
        // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
        // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

/**
 * Open the database
 * @throws SQLException
 */
public void openDataBase() throws SQLException {
    String myPath = DB_PATH + DB_NAME;

    myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
}

/**
 * Close the database if exist
 */
@Override
public synchronized void close()
{
    if (myDataBase != null)
        myDataBase.close();
    super.close();
}

/**
 * Call on creating data base for example for creating tables at run time
 */
@Override
public void onCreate(SQLiteDatabase db)
{
}

/**
 * can used for drop tables then call onCreate(db) function to create tables again - upgrade
 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}

// ----------------------- CRUD Functions ------------------------------

/**
 * This function used to select the records from DB.
 * @param tableName
 * @param tableColumns
 * @param whereClase
 * @param whereArgs
 * @param groupBy
 * @param having
 * @param orderBy
 * @return A Cursor object, which is positioned before the first entry.
 */
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
        String whereClase, String whereArgs[], String groupBy,
        String having, String orderBy)
{
    return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
            groupBy, having, orderBy);
}

/**
 * select records from db and return in list
 * @param tableName
 * @param tableColumns
 * @param whereClase
 * @param whereArgs
 * @param groupBy
 * @param having
 * @param orderBy
 * @return ArrayList<ArrayList<String>>
 */
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
        String whereClase, String whereArgs[], String groupBy,
        String having, String orderBy)
{

    ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
      ArrayList<String> list = new ArrayList<String>();
      Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
                groupBy, having, orderBy);
      if (cursor.moveToFirst()) {
         do {
             list = new ArrayList<String>();
             for(int i=0; i<cursor.getColumnCount(); i++){
                 list.add( cursor.getString(i) );
             }
             retList.add(list);
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return retList;

}

/**
 * This function used to insert the Record in DB.
 * @param tableName
 * @param nullColumnHack
 * @param initialValues
 * @return the row ID of the newly inserted row, or -1 if an error occurred
 */
public long insertRecordsInDB(String tableName, String nullColumnHack,
        ContentValues initialValues) {
    return myDataBase.insert(tableName, nullColumnHack, initialValues);
}

/**
 * This function used to update the Record in DB.
 * @param tableName
 * @param initialValues
 * @param whereClause
 * @param whereArgs
 * @return true / false on updating one or more records
 */
public boolean updateRecordInDB(String tableName,
        ContentValues initialValues, String whereClause, String whereArgs[]) {
    return myDataBase.update(tableName, initialValues, whereClause,
            whereArgs) > 0;
}

/**
 * This function used to update the Record in DB.
 * @param tableName
 * @param initialValues
 * @param whereClause
 * @param whereArgs
 * @return 0 in case of failure otherwise return no of row(s) are updated
 */
public int updateRecordsInDB(String tableName,
        ContentValues initialValues, String whereClause, String whereArgs[]) {
    return myDataBase.update(tableName, initialValues, whereClause, whereArgs);
}

/**
 * This function used to delete the Record in DB.
 * @param tableName
 * @param whereClause
 * @param whereArgs
 * @return 0 in case of failure otherwise return no of row(s) are deleted.
 */
public int deleteRecordInDB(String tableName, String whereClause,
        String[] whereArgs) {
    return myDataBase.delete(tableName, whereClause, whereArgs);
}

/**
 * apply raw Query
 * @param query
 * @param selectionArgs
 * @return Cursor
 */
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
    return myDataBase.rawQuery(query, selectionArgs);
}

/**
 * apply raw query and return result in list
 * @param query
 * @param selectionArgs
 * @return ArrayList<ArrayList<String>>
 */
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
      ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
      ArrayList<String> list = new ArrayList<String>();
      Cursor cursor = myDataBase.rawQuery(query, selectionArgs);

      if (cursor.moveToFirst()) {
         do {
             list = new ArrayList<String>();
             for(int i=0; i<cursor.getColumnCount(); i++){
                 list.add( cursor.getString(i) );
             }
             retList.add(list);
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }

      return retList;
   }

}
  04-24 12:04:14.289: INFO/Database(3807): sqlite returned: error code = 14, msg =     cannot open file at source line 25467
  04-24 12:04:14.289: ERROR/Database(3807):     sqlite3_open_v2("/data/data/com.TravelPharm/databases/Medicaments.sqlite", &handle, 1, NULL) failed
  04-24 12:04:14.299: DEBUG/RegisterService(431): insert plugin size 1
  04-24 12:04:14.339: DEBUG/asset(3807): Data exceeds UNCOMPRESS_DATA_MAX (17304576 vs  4194304)
  04-24 12:04:14.339: WARN/System.err(3807): java.io.IOException
04-24 12:04:14.339: WARN/System.err(3807):     at android.content.res.AssetManager.readAsset(Native Method)
04-24 12:04:14.339: WARN/System.err(3807):     at android.content.res.AssetManager.access$700(AssetManager.java:36)
04-24 12:04:14.339: WARN/System.err(3807):     at android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:571)
04-24 12:04:14.339: WARN/System.err(3807):     at com.TravelPharm.DBHelper.copyDataBase(DBHelper.java:116)
04-24 12:04:14.339: WARN/System.err(3807):     at com.TravelPharm.DBHelper.createDataBase(DBHelper.java:73)
04-24 12:04:14.339: WARN/System.err(3807):     at com.TravelPharm.TravelPharm.SumofDetails(TravelPharm.java:286)
04-24 12:04:14.339: WARN/System.err(3807):     at com.TravelPharm.TravelPharm.onCreate(TravelPharm.java:61)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.ActivityThread.access$2300(ActivityThread.java:135)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
04-24 12:04:14.339: WARN/System.err(3807):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 12:04:14.339: WARN/System.err(3807):     at android.os.Looper.loop(Looper.java:144)
04-24 12:04:14.339: WARN/System.err(3807):     at android.app.ActivityThread.main(ActivityThread.java:4937)
04-24 12:04:14.339: WARN/System.err(3807):     at java.lang.reflect.Method.invokeNative(Native Method)
04-24 12:04:14.339: WARN/System.err(3807):     at java.lang.reflect.Method.invoke(Method.java:521)
04-24 12:04:14.339: WARN/System.err(3807):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 12:04:14.339: WARN/System.err(3807):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 12:04:14.339: WARN/System.err(3807):     at dalvik.system.NativeStart.main(Native Method)

A: Are you sure the path
DB_PATH = "/data/data/"+ context.getApplicationContext().getPackageName()
    + "/databases/";

exists, and is writeable for you? I would first check this.

A: Maybe the database is not the problem:

04-24 12:04:14.339: DEBUG/asset(3807):
  Data exceeds UNCOMPRESS_DATA_MAX
  (17304576 vs  4194304)

Maybe the assets folder is too big for the phone , but not for the emulator. Try removing each asset file (except the db) or try reducing the size of the db.


text:
Q: Finding Bitwise & operations inside a C Source Code Good Day RegEx Gurus,
I just would like to request for some help regarding REGEX.
How to find the Bitwise & operator inside a C source code?
Currently I already have this RegEx:
[^\&=](\&)[^\&]

Case #1 : should Return : 3 (Currently returns 3, which is OK)
                 :
u1_dfsmd_igbt_sdown = ( u1r_dfsmd_igbt[IGBT_WSDOWN] &
u1r_dfsmd_igbt[IGBT_SSDOWN] &
u1r_dfsmd_rcv_wsdown &
u1r_dfsmd_rcv_ssdown ) ;
                 :

Case #2 : should Return : 0 (Currently returns 1, which is NOT OK)
                 :
scanf ("%d", &i)
                 :

Case #3 : : should Return : 0 (Currently returns 0, which is OK)
                 :
if (xx && yy && zz) {
//Some statements here
}
                 :

I'm a beginner w/ RegEx (My current Regex might be in brute-force)
Thanks in advance for the help.

A: Wouldn't this be enough?
\s\&=?\s

It's a '&' prefixed by any whitespace character [ \t\n\x0B\f\r] with optional '=' and suffixed with any whitespace character (including new line). I didn't test that and don't know all the criteria but I hope it helps.


text:
Q: Generate HTML dynamically on button click in Angular js I have a select box. I want to generate the same on a 'Add New' button click.
View
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="Get_toolNames()">Add New

</button>

<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>
  <option value="">Select</option>
</select>

How can I generate the same on this button click?

A: If you have
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="buttonClick"> Add New

 </button>

In your controller you can inject and use $compile service.
$scope.buttonClick = function(){
   var el = angular.element(/* Here your element */);
   el.append( '<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name"  ng-options="t.tm_id as t.tm_name for t in tools" required>' +
                     '<option value="">Select</option>' + '</select>')
   $compile(el)($scope);
}

Change your logic to get the data and the element you want:
For more see $compile.
Update
var sample_2_tbody = angular.element('#sample_2 tbody');
$compile(sample_2_tbody)($scope);

How to inject a service in the controller:
app.controller('MyController', ['$scope', '$compile', function($scope, $compile){

}])

A: In AngularJS views are just a model reflection and their scope is only for data presentation. That's mean you never need to manually copy a DOM Element, you just need to operate on the bound model.

function TestCtrl($scope, select) {
  copy = () => angular.copy(select);

  $scope.selects = [copy()];
  $scope.values = {};

  $scope.add = () => {
    //$scope.selects.unshift(select); // add at the beginning
    $scope.selects.push(copy()); // add at the end
  };
}

angular
  .module('test', [])
  .value('select', [{
    id: 1,
    label: 'aLabel',
    subItem: { name: 'aSubItem' }
  }, {
    id: 2,
    label: 'bLabel',
    subItem: { name: 'bSubItem' }
  }])
  .controller('TestCtrl', ['$scope', 'select',  TestCtrl])
;

    <button ng-click="add($event)">Add</button>

      <select ng-model="values[$index]" ng-options="t as t.label for t in select">
      </select>