text:
Q: HoverTool shows '???' in bokeh plot after a template render I can't seem to get the HoverTool to show the info for the circle glyph after rendering the plot in this fashion(code below). The hovertool pops up but each of the tooltips show '???' instead of the info from the ColumnDataSource. Any help would be greatly appreciated!
from jinja2 import Template

from bokeh.models import HoverTool, ColumnDataSource, BoxSelectTool,             GeoJSONDataSource
from bokeh.core.templates import CSS_RESOURCES, JS_RESOURCES
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8

source = ColumnDataSource(
    data=dict(
        x=[1, 2, 3, 4, 5],
        y=[2, 5, 8, 2, 7],
        desc=['A', 'b', 'C', 'd', 'E'],
    )
)

hover = HoverTool(

    tooltips=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("desc", "@desc"),
    ]
)

p = figure(plot_width=400, plot_height=400,
       title="Mouse over the dots")

g1 = p.circle('x', 'y', size=20, source=source)

hover = HoverTool(
    renderers= [g1],
    tooltips=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("desc", "@desc"),
    ]
)
p.add_tools(hover)

js_resources = JS_RESOURCES.render(
    js_raw=INLINE.js_raw,
    js_files=INLINE.js_files
)

css_resources = CSS_RESOURCES.render(
    css_raw=INLINE.css_raw,
    css_files=INLINE.css_files
)

script, div = components(p, INLINE)
template = Template('''<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Bokeh Scatter Plots</title>
        {{ js_resources }}
        {{ css_resources }}
        {{ script }}
    </head>
    <body>
            {{ div }}
    </body>
</html>
''')
html = template.render(
    js_resources=js_resources,
    css_resources=css_resources,
    script=script,
    div=div
)

filename='toolTipPrac.html'
with open(filename, 'w') as f:
    f.write(html)


text:
Q: Converting an IP address to a number: Question:
When I convert the IP address 192.168.115.67 to a number, is it done like this:
192*2563 + 168*2562+115*2561+67*2560 = 3232265027

or like this:
192*2560 + 168*2561+115*2562+67*2563 = 1131653312

I find both variants online, and frankly it doesn't matter as long as I do all the internal IP-range comparison using the same conversion process variant.
But I want to calculate the IP V6 from the IPv4 address, and it seems both variants are on the web...
resulting in different IPv6 addresses, and only one can be correct...

I use the 1131653312 variant, as 1131653312 is the variant I saw .NET giving me, but 3232265027 is the variant I used when I did it in C++, and that is also the variant I find on the web for IPv4 to IPv6 conversion, and which I used before I saw that .NET uses variant 1131653312 ...

A: It is definitely first one. You can ping and see how ping utility convert it to a.b.c.d notation. If you going to do this conversion I recommend expression: (a << 24) | (b << 16) | (c << 8) | d

A: The method resulting in 3232265027 should be correct, as the first number is stored in the highest bits of the IPv4 compatibility part of IPv6:
0000:0000:0000:0000:0000:ffff:AABB:CCDD
where
AA = 192
BB = 168
CC = 0
DD = 1
etc.
https://wikipedia.org/wiki/IPv6
Also, you can't have a 256 in an IP address. The values are 0 - 255 each.

A: Numbers are sent in big-endian order over the wire, which is the same as the way they are written (192 is the most significant byte). Thus the first number is the "correct" one. The other variant is how the same bytes will be interpreted on a little-endian architecture, hence the .Net behaviour.
Having said all that, I'm really not sure what the question is, so I can only hope that this exposition constitutes an answer of sorts.

A: The difference has to do with endianness. You are storing it in an integer, but different processors have different byte orderings for their integers (big or little end first). However, that number has to go out over the line, so IP has a specific order it needs the bytes transferred in. That order looks different to bigendian and littleendian machines.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting JS to TS - React Hooks I'm making a basic chat app with React w/Typescript. I understand that TS requires type declaration.
I would like to convert this from JS to TS, what all would need to be changed and where do I declare the type in each case?
CODE
function App() {

 const [rooms, setRooms]   = useState(''); // type str
 const [roomId, setRoomId] = useState(''); // type str
 const [user, setUser]     = useState(''); // type str

function updateRoom(id) {

 return id === '' ? setRoomId('') : setRoomId(id) // ??

}

return (

   {rooms.map((room, index) => (
     <Room key={index} index={index} room={room} />
   ))}

)
}

TS
function App() {

   const [rooms, setRooms] type Str = useState('');

}

Would it be something like this?

A: Typescript only requires typing where it can't be inferred.
const [rooms, setRooms] = useState('');

Because of how useState is typed, typescript knows that when passed a string, it will return something like this type:
[string, (newRooms: string) => void]

Which gets destructured into your value and your setter.
So typescript will know that rooms will be a string because you pass a string to useState.
This code should work as is in typescript. Just convert it and fix what errors come up.

But in case it can't be inferred, you can give it a hint:
const [foo, setFoo] = useState(null as string | null)

Now foo could be null or string, but null is the default value on component mount.


text:
Q: Spring Boot validation takes float value in integer field I'm trying to implement a POST service with request validation.
My Controller method looks something like below
public void updateScore(@Valid ScoreRequest)

ScoreRequest looks like below
import javax.validation.constraints.*;
import lombok.Data;

@Data
public class ScoreRequest {
    @Min(0)
    @Max(100)
    @Digits(fraction = 0, integer = 3)
    private Integer score;

    ...
}

It all works fine till I pass integer values for score, however If I pass fraction part as well, request  goes through and Spring somehow truncates the fraction and uses the integer part in the request.
I was expecting it to throw a validation error since datatype of score doesn't match.
It works with followling request, and uses 10 as the score value in the request object. I'm expecting it to throw an error, what am I doing wrong?
{"score": 10.234234}

Spring Boot version: 2.0.3.RELEASE

A: I was trying to debug Spring Boot's validation classes to find what was happening, but after looking at the comment by @M.Denium I searched for Jackson issues and found a related SO entry.
Java Jackson - prevent float to int conversion when deserializing
I'm using answer by @Jichao Zhang, however Just to confirm answer by @Eduardo Sanchez-Ros works as well. This is what works for me.
ObjectMapper.configure(DESERIALIZATION_FEATURE.ACCEPT_FLOAT_AS_INT, false);

A: Don't use this annotation: @Digits(fraction = 0, integer = 3 with Integer since it is useless to set fractions for Integer.
Why don't you do:
@Min(0)
@Max(100)
@Digits(fraction = 0, integer = 3)
private BigDecimal score;

A: If you closely look at the definition of the @digits annotation,
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })

So this annotation can be applied to methods also.
If you read the docs, it says this annotation can be applied to the following types

*

*BigDecimal

*BigInteger

*CharSequence

*byte (or Byte)

*short (or Short)

*int (or Integer)

*long (or Long)

the integer field of the annotation checks for the number of integral digits while the fraction field of the annotation checks for the number of fractional digits.

Since, you declared your field to be an Integer value. It casts the value to an integer and truncates the fractional part.
This does not fail validations as both the fields satisfy the validation.

This annotation is ideally to be only used with BigDecimal type.


text:
Q: Auth is not working in middleware in Laravel I have successfully loggedin my adminpanel but while I redirect to dashboard after login using middleware it's not working.
login controller
if (Auth::attempt(['username' => $request->email, 'password' => $request->password]))
{
    return redirect('/dashboard');
}

route
Route::group(['middleware' => ['adminAuth']], function () {

    Route::get('/dashboard', 'dashboardController@index');

});

dashboard controller
public function index()
{
    return 'admin dashboard';
}

adminAuthenticate.php Middleware
 public function handle($request, Closure $next)
{
    if(Auth::check() && Auth::user()->role_code == '1'){
        return $next($request);
    }
    return abort(404);
}

kernel.php
protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'adminAuth' => \App\Http\Middleware\adminAuthenticate::class,
    ];

Always it returns '404' page though I have successfully loggedin.
Where is the problem ? anybody help please ? Thanks in advance


text:
Q: Casting result from Database Function not working I'm using the following to get the ISO Week Date:
class DateWeek(Func):
  """ Return the ISO8601 Week Number """

  def as_mysql(self, compiler, connection):
    self.function = 'WEEK'
    self.output_field = IntegerField()
    self.template = 'CONVERT(%(function)s(%(expressions)s, 3), UNSIGNED INTEGER)'
    return super().as_sql(compiler, connection)

Which works fine:
MyObj.annotate(wk=DateWeek('date')).values('wk')

<QuerySet [{'wk': 1}, {'wk': 21}]>

...until I want to do something like:
MyObj.annotate(wk=DateWeek('date')).filter(wk__gt=20)

When I try and do this I get a dateparse error as Django is trying to calculate the filter assuming that wk is a date of some kind. I've set the output_field to IntegerField, is there anything else I should be doing?
-----------------------------------------------------
TypeError           Traceback (most recent call last)
<ipython-input-8-16eccbbc84a8> in <module>()
----> 9       ).filter(dy__gt=2016).values('dw', 'dy')

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/query.py in filter(self, *args, **kwargs)
    834         set.
    835         """
--> 836         return self._filter_or_exclude(False, *args, **kwargs)
    837
    838     def exclude(self, *args, **kwargs):

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs)
    852             clone.query.add_q(~Q(*args, **kwargs))
    853         else:
--> 854             clone.query.add_q(Q(*args, **kwargs))
    855         return clone
    856

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/sql/query.py in add_q(self, q_object)
   1250         # So, demotion is OK.
   1251         existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}
-> 1252         clause, _ = self._add_q(q_object, self.used_aliases)
   1253         if clause:
   1254             self.where.add(clause, AND)

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/sql/query.py in _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)
   1274                     child, can_reuse=used_aliases, branch_negated=branch_negated,
   1275                     current_negated=current_negated, allow_joins=allow_joins,
-> 1276                     split_subq=split_subq,
   1277                 )
   1278                 joinpromoter.add_votes(needed_inner)

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/sql/query.py in build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, allow_joins, split_subq, reuse_with_filtered_relation)
   1167         clause = self.where_class()
   1168         if reffed_expression:
-> 1169             condition = self.build_lookup(lookups, reffed_expression, value)
   1170             clause.add(condition, AND)
   1171             return clause, []

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/sql/query.py in build_lookup(self, lookups, lhs, rhs)
   1082             return
   1083
-> 1084         lookup = lookup_class(lhs, rhs)
   1085         # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
   1086         # uses of None as a query value.

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/lookups.py in __init__(self, lhs, rhs)
     16     def __init__(self, lhs, rhs):
     17         self.lhs, self.rhs = lhs, rhs
---> 18         self.rhs = self.get_prep_lookup()
     19         if hasattr(self.lhs, 'get_bilateral_transforms'):
     20             bilateral_transforms = self.lhs.get_bilateral_transforms()

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/lookups.py in get_prep_lookup(self)
     66             return self.rhs._prepare(self.lhs.output_field)
     67         if self.prepare_rhs and hasattr(self.lhs.output_field, 'get_prep_value'):
---> 68             return self.lhs.output_field.get_prep_value(self.rhs)
     69         return self.rhs
     70

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value(self, value)
   1269     def get_prep_value(self, value):
   1270         value = super().get_prep_value(value)
-> 1271         return self.to_python(value)
   1272
   1273     def get_db_prep_value(self, value, connection, prepared=False):

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/db/models/fields/__init__.py in to_python(self, value)
   1231
   1232         try:
-> 1233             parsed = parse_date(value)
   1234             if parsed is not None:
   1235                 return parsed

~/.virtualenvs/f4c2/lib/python3.6/site-packages/django/utils/dateparse.py in parse_date(value)
     72     Return None if the input isn't well formatted.
     73     """
---> 74     match = date_re.match(value)
     75     if match:
     76         kw = {k: int(v) for k, v in match.groupdict().items()}

TypeError: expected string or bytes-like object


text:
Q: How Can I Intelligently Implement Auto-Resizing in a Visual C# Winforms App? My application (which I am using Visual C# 2008 WinForms for) involves a lot of generated controls. Specifically: grids of buttons, arrays of labels, lists, headings, etc... all populated so that they fit their containers appreciably.
I want users to be able to resize the main form, which obviously would require me to either destroy my generated content, and remake it at the proper size OR I could index through every control, figure out what it is by name and type, and re-size each item individually. I would have to do this while/after the form resizes.
Are there any more intelligent ways of doing this? Dock and Anchor don't quite apply here because I am dealing with items that don't make up 100% of a dimension (for example, grids of buttons).

A: Hard do give a reasonnable answer without seing just how complex the layout in question is.
But in principle, you should use a layout container such as FlowLayoutPanel or TableLayoutPanel to do the job they were designed to do. If one does not do the job, just nest them.

A: Docking/anchoring is probably the answer here. You need to anchor your grid to top/bottom/left/right or dock it (same effect, but the grid will fill the parent control).
If this is done right your control(s) will re-size with the rest of the form just as if you created everything in the designer.
I believe something like this would work:
Control.Anchor = AnchorStyles.TopLeft | AnchorStyles.BottomRight;


text:
Q: How to resolve all implementations of one interface in unity? Okay, I want to create arbitrary implementations of a specific Interface and resolve them. It's actually similiar to a plugin system. "Create your own Implementation of intereface X  and the app does the rest"
public interface IMenuEntry { ... }

// auto-mapping (registration-by-convention)
_container.RegisterTypes(AllClasses.FromAssemblies(assemblies),
                         WithMappings.FromMatchingInterface,
                         // ResolveAll need names for multiple registrations of the same type (?)
                         WithName.TypeName,
                         WithLifetime.ContainerControlled);

var g = _container.ResolveAll<IMenuEntry>(); // empty - why?

When I check my container registrations my implemantations are there and the name is the name of the class - not the interface. Wonderful. But why can't I resolve all implementations of IMenuEntry? It is always empty.

A: WithMappings.FromMatchingInterface will only match a type named MenuEntry to IMenuEntry.
You might try WithMappings.FromAllInterfaces instead.
See the WithMappings methods documentation.


text:
Q: How to scale 3D object vertically (along y-axis) in Swift? I created a door with ARKit and I want create a scale animation. My goal is to scale it only along the y-axis (stretch the door to be longer).
I want the door to grow within a duration of 1 second.
My approach was to simply scale it but I only have options that allow me to scale my entire object along all 3 axis.
Next I tried node.scale = SCNVector3(0, 2, 0) and that works ok, but it has no nice animation to it. When I create a SCNAction() and run the code as a block with duration time, it still just changes the size without any smooth animation.

A: You need to use SCNTransaction. The simplest way to animate your node scaling would be something like this:
SCNTransaction.begin()
SCNTransaction.animationDuration = 3
node.scale = SCNVector3(0, 2, 0)
SCNTransaction.commit()

You might also need to modify pivot property of the node to position the animation correctly.


text:
Q: Debugging not running on PyCharm for my Django project I am not able to run with debug option for my Django project after an recent update of PyCharm.
The last line of stacktrace gives error
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

the first few lines of stacktrace gives error
Fatal Python error: Cannot recover from stack overflow.

Here is the full stacktrace -
pydev debugger: process 21976 is connecting

Connected to pydev debugger (build 181.5087.37)
Fatal Python error: Cannot recover from stack overflow.

Thread 0x000070000ee34000 (most recent call first):
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 101 in _on_run
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 303 in run
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916 in _bootstrap_inner
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 884 in _bootstrap

Thread 0x000070000e931000 (most recent call first):
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 365 in _on_run
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 303 in run
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916 in _bootstrap_inner
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 884 in _bootstrap

Current thread 0x000070000e42e000 (most recent call first):
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread
  ...

Thread 0x00007fffb4ace380 (most recent call first):
  File "<frozen importlib._bootstrap_external>", line 832 in get_data
  File "<frozen importlib._bootstrap_external>", line 764 in get_code
  File "<frozen importlib._bootstrap_external>", line 674 in exec_module
  File "<frozen importlib._bootstrap>", line 665 in _load_unlocked
  File "<frozen importlib._bootstrap>", line 955 in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 971 in _find_and_load
  File "/Volumes/Samsung_T5/Work/python/repos/venv3/lib/python3.6/site-packages/gevent/monkey.py", line 579 in patch_thread
  File "/Volumes/Samsung_T5/Work/python/repos/venv3/lib/python3.6/site-packages/gevent/monkey.py", line 178 in ignores
  File "/Volumes/Samsung_T5/Work/python/repos/venv3/lib/python3.6/site-packages/gevent/monkey.py", line 976 in patch_all
  File "/Volumes/Samsung_T5/Work/python/repos/manage.py", line 4 in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18 in execfile
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1068 in run
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1658 in main
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1664 in <module>

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

A: I had this same problem. In my case, it's because I was using gevent. There's an option in the PyCharm settings under Build, Execution, Deployment -> Python Debugger. I enabled "Gevent compatible", and debugging started working again.

A: I had the same Problem with starting a django 2.2 project with python 3.6. Troy Hoffmans solution could start the server in debug Mode, but the breakpoints were then ignored. So I activatet "Collect run-time types information for code insight" in PyCharm settings under Build, Execution, Deployment -> Python Debugger.


text:
Q: Combining Two Count Queries to Get Most Common I have a table for a football player grading system -
Columns are
player id - number score - decimal score
values available are
1-20 - 1-5 - 0-9
for example a player would be graded 4.9 or 3.2 etc.
I have the queries :
SELECT NS, COUNT(NS)
FROM playerrating
GROUP BY NS
ORDER BY NS DESC;

AND
SELECT DS, COUNT(DS)
FROM playerrating
GROUP BY  DS
ORDER BY DS DESC;

How do I combine the two to get the average score for all players ? thanks

A: I am assuming that NS and DS are a single floating point number.
I am assuming that DS has a length of 1
I am also assuming columns are named player_id, NS and DS but this is not clear from your question
Then your query per player would look like:
SELECT player_id, AVG(NS + ( DS / 10.0 )) AS rating
FROM playerrating
GROUP BY player_id

For an average of all players you can use:
SELECT AVG(NS + ( DS / 10.0 )) AS rating
FROM playerrating

A: I have used my own table and column names. Please change them as you need.
Below is the SQL code:
SELECT Sum(avg1) FROM
(SELECT * FROM
(SELECT Sum(ns*nscnt)/Sum(nscnt) AS avg1 FROM
(SELECT number_score AS ns, COUNT(number_score) AS nscnt
FROM soccer_score
GROUP BY number_score
ORDER BY number_score DESC))
UNION ALL
(SELECT Sum(ds*dscnt)/Sum(dscnt) AS avg1 FROM
(SELECT decimal_score AS ds, COUNT(decimal_score) AS dscnt
FROM soccer_score
GROUP BY  decimal_score
ORDER BY decimal_score DESC)));


text:
Q: Which tense to use here?
I would rather you mended your ways or be ready to face the music.

Is the use of be above correct? Or should I replace it with got to maintain parallelism?
be ready, incidentally, shows which tense?


text:
Q: Encrypting query string text I have a concatenated string and I want to pass it as query string. For security, I want to encrypt the concatenated string using gpg private key that resides in the same folder where this .php file resides on the remote server.
I want to know whether it is safe to keep the public and private keys on the remote server and use it for encryption and decryption.

A: First question: Why? - If you're transferring data on the same server use PHP sessions or store it in a database. IF you want to transport data from one server to another server use another communication channel between these too, like a HTTP request POSTing the data.
IF you still want to do it: I won't use GPG for this as this produces quite some CPU load and increases the size of the message dramatically, assuminf your data is relatively short. It's better to use blowfisch or similar algorithms, see PHP's crypt function for instance.
About the security: It is more or less as secure as the whole server is but you should make sure your private key is hidden outside the document root of the web server. And read rights should be limited to the web server user ...

A: Try these PHP functions convert_uuencode and convert_uudecode
function encrypt_decrypt ($data, $encrypt) {
    if ($encrypt == true) {
        $output = base64_encode (convert_uuencode ($data));
    } else {
        $output = convert_uudecode (base64_decode ($data));
    }
    return $output;
}

$enc_txt = encrypt_decrypt ("QUERY TEXT", true);
echo $enc_txt."\n";
// KjQ1NSU0RURANSQ1ODVgYGAKYAo=
echo encrypt_decrypt ($enc_txt, false);
// QUERY TEXT


text:
Q: Django 2.1 : Render JSONresponse to template, byte string doesn't work with javascript In view:
response = JsonResponse(available_lessons, safe=False)

In template:
var available_lessons_json = {{available_lessons_json.content|safe}}

In my source js file I see:
var available_lessons_json = b'{"courses": {"courseName": "Everyday English", "lessons": ["Phrasal Verbs I", "Phrasal Verbs II", "Phrasal Verbs III"]}}'

which is giving me the error "Uncaught SyntaxError: Unexpected string"

A: Javascript doesn't like the b at the start of your response content, which denotes that it is a byte string. response.content always encodes to bytes- which you can decode with {{available_lessons_json.content.decode|safe}}
Just be aware that if response.content contains user input you're likely to be introducing XSS vulnerabilities into your site

A: If you want to render your template with your data, your should use render function not JsonResponse. This should be like this.
return render(request, template, {'available_lessons': available_lessons})

In your template
var available_lessons_json = {{available_lessons|safe}}


text:
Q: ASP.NET Cannot get value from second modal input I have two modal in a single .aspx file
and I call modal from code behind using
ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openImportModal();", true);

And due to I can't get input value from modal, so append the modal by using code below
<script type="text/javascript">
    function openImportModal() {
        $('[id*=ImportData]').modal('show');
    }
    window.addEventListener('DOMContentLoaded', init, false);
    function init() {
        var element = $('#ImportData').detach();
        $($("div")[0]).append(element);
    }

    function openAddPlayerModal() {
        $('[id*=AddPlayerForm]').modal('show');
    }
    window.addEventListener('DOMContentLoaded', init2, false);
    function init2() {
        var element2 = $('#AddPlayerForm').detach();
        $($("div")[0]).append(element2);
    }
</script>

When I use the first modal #ImportData , it can get input value from the modal,
and when run to the second modal #AddPlayerForm , I can't get any input value from the modal...
Did anyone can help me to see how I can do for this ?
Many thanks !


text:
Q: ssh login and untar file I have two server (LOCAL) 192.168.1.1 and (REMOTE) 192.168.15.2
I want to untar a file from LOCAL (192.168.1.1) on REMOTE (192.168.15.2) via an SSH connection. What command can I use for that?
source path: /home/user/example.tar.gz
target path: /mnt/untar/extracted_folder

A: On the source system (LOCAL):
ssh -e none 192.168.15.2 'tar -xzf - -C /mnt/untar/' </home/user/example.tar.gz

A: Try this
ssh root@host1 "cd /dir/tocopy/ && tar -cf - ." | \
ssh root@host2 "cd /dir/tocopyto/ && tar -xf -"

NJOY


text:
Q: Visual Studio 2012: 'opencv2/opencv.hpp' : No such file or directory (C1083) This question was asked several times, there are some answers, but this problem is more specific, the additional directories path is set correctly (files are found).
Nevertheless building my project i get the following error:
 fatal error C1083: Cannot open include file:
 'opencv2/opencv.hpp': No such file or directory

but i can right click on the file and open it in visual studio 2012?

I tried:
1) specifying the full path: WORKS!
#include <D:\frameworks\opencv_2_4\build\include\opencv2\opencv.hpp>

2) Putting the file to C:\ Doesn't Work! (add. directories added)
3) Empty project with the same include syntax. (add. directories added). WORKS!
4) I've configured a VS2010 Version of the same project with CMake, and i have there the same problems.
Any hints what could be causing this error?

A: project property  =>  C/C++   => General => Additional include Directories =>  "put the address of library from your openCV folder  eg: C:\opencv\build\include
As shown in the picture below

A: If you put the headers within your project. As @CalaveraLoco's answer. Could using the relative path to access the header.
But it's better to include the project folder path into your project settings.

*

*Open Properties of the project.

*Select C/C++

*Select General

*Add $(ProjectDir); into Addition Include Directories

A: Open Configuration Properties > C/C+
+ > General , and edit the field
Additional Include Directories to add
these 3 paths (for the headers):
C:\OpenCV2.3\build\include\opencv
C:\OpenCV2.3\build\include
\opencv2
C:\OpenCV2.3\build\include

A: In my case the problem had to do with exported classes.
I have 2 VS projects. Let's name them A and B.
Project A uses classes from project B; and project B uses classes of OpenCV.
Project A didn't use (neither link) OpenCV. (as you can imagine project A uses openCV throught project B).
But if any of the exported classes of B (used by A) had a private member of type OpenCV (cv::Mat, for example), in that case, the error C1083 appeared, although i had correctly linked openCV in project B.
My solution was to be carefull with the includes in the *.hpp files of the exported classes of project B.
Hope it's usefull.

A: In addition to the existing answers. Try to change
<opencv2/core.hpp>

to
"opencv2/core.hpp".

A: since I am running with 64 bit window 10, visual studio professional 2017, I follows below step to fix:

*

*Project > Properties -> change platform to x64

*project property > C/C++ -> General -> Additional include Directories ->{DIR}{PATH}\opencv\opencv\build\include

*project property > C/C++ -> All Options -> Additional include Directories ->{DIR}{PATH}\opencv\opencv\build\include

*project property > Linker -> Input -> Additional Dependencies -> Edit.. -> enter 'opencv_world330d.lib' -> OK -> OK

A: On Windows:

*

*In Search, search for and then select: "System" (Control Panel).
Click on the "Advanced System Settings" link.

*Click Environment Variables. In System Variables, click on "Path".

*Click on "Modify". Click on "New" and add the following (without
quotation marks): "C:\opencv\build\x64\vc14\lib\".

*Click on "New" again and add the following (without quotation
marks): "C:\opencv\build\x64\vc14\bin\".

*Restart Windows.

*Open Visual Studio and create a new project. On "Solution Explorer":

*Right click on the project title and then go to "Properties". Change
Platform to "x64".

*Go to "C/C++" -> "General" -> "Additional Include Directories" and
add (without quotation marks) "C:\opencv\build\include". Click on
"Apply".

*Go to "Linker" -> "General" -> "Additional Library Directories" and
add (without quotation marks) "C:\opencv\build\x64\vc14\lib". Click
on "Apply".

*Go to "Linker" -> "Input" -> "Additional Dependencies" and add
 (without quotation marks)
 "opencv_world310.lib;opencv_world310d.lib;". Click on "Apply".

when you are debug application use 'x64' mode
This works with VS2015, hope this will help.

A: that's funny but it seems that Visual Studio can't find the rigt headers files simply because there is not Opencv2 folder in the Opencv2 folder i mean that when reading the source code

#include <opencv2/core/core.hpp>

and following the include directories location,thus

$(OPENCV_DIR)\build\include\opencv2

he will try to find some

$(OPENCV_DIR)\build\include\opencv2\opencv2\core\core.hpp

which he will never find simply because the base directory is mismatch
to solve this problem just delete the base directory(opencv2) from the include
directive :

#include <core.hpp>

i hope this will help

A: You have to change Project > Properties -> change platform to x64 and the set the bin, lib and include folders again.
After this You have to also change "Solution platforms" tab from x86 to x64.
After this, you will be able to use OpenCV.


text:
Q: Creating child and grandchild paperclip records in a single controller action I've been asked to modify an upload system that uses paperclip. Currently Users have many uploads, but now they want to extend this functionality by giving uploads pictures to help users better visualize the uploads.
So:

*

*User has Many Uploads

*Uploads has one User

*Uploads has many pictures

*Pictures have one Upload

Right now my Upload is being created in an action sitting in the Users controller. But my client wants me to give the user the option of submitting multiple pictures along with the parent Upload. This is my current code:
  def upload_files
      @user = User.find_by_username(params[:username])
      @uploads = @user.uploads.paginate(:page => params[:page], :per_page => 10)
      1.times { @user.uploads.build }
      respond_to do |format|
        format.html # uploads.html.erb
        format.json { render json: @user }
      end
  end

I wasn't sure how I was supposed to go building my child photo records along with my Upload record in this one method.
Any ideas on how I can get this to work?

A: I found the answer. With a little more digging around it looks like what I wanted to do was asynchornously build a child and a grandchild record. I updated the question to demonstrate such and here's the code to do it.
  def upload_files
      @user = User.find_by_username(params[:username])
      @uploads = @user.uploads.paginate(:page => params[:page], :per_page => 10)
      1.times do
        child = @user.uploads.build
        1.times { child.upload_images.build }
      end
      respond_to do |format|
        format.html # uploads.html.erb
        format.json { render json: @user }
      end
  end

Cheers


text:
Q: Unexpected output instead of runtime error It might be obvious for who knows the background magic, but I could not understand how below code is giving correct output. I expected a runtime error. Please help.
class a
{
  public:
    void print()
    {
        cout<<"Hello\n"<<endl;
        int d = 100;
        cout<<d<<endl;
    }

    int val;
};

int main()
{
   a* ptr;

   ptr->print();

   return SUCCESS;
}

OUTPUT is as below :
Hello

100

A: There is no magic - your code has undefined behavior. In your code you do not access ptr which is implicitly passed to print() as this pointer, that is why no error happen.
It may happen in several other cases:

*

*Accessing fields of a instance. It will require to read memory *(this + field_offset) which will cause runtime error.

*Accessing virtual methods. Implementations known to me use vtable to do that, which is usually stored as first pointer in object space, so pointer to vtable  would be same as this, so: vtable = *this

*Other cases, depending on compiler and platform
NOTE: type conversion is omitted from examples with this

A: a::print is a not a virtual method, hence it is just a normal function that has an extra argument to receive the this pointer. Since the method never uses the this pointer, the fact that it is uninitialized doesn't turn into a memory access error or other failure. Declaring a::print static will still compile in this case since it doesn't use the this pointer. Declaring a::print virtual or accessing this inside the method will likely lead to the program crashing, at least under some circumstances.
The behavior is still undefined and it is an ill-formed program, but as it stands now it is very likely to work deterministically on most systems. In general C++ does not give runtime errors for such cases, but if you compile with e.g. "clang++ -Wall" a warning indicating the uninitialized variable will be given. (And there are tools such as clang's asan which will go further in diagnosing such errors.)


text:
Q: Stanford Tagger with GATE I am using GATE for Arabic under Linux and when using Stanford Tagger there aren't any POS tags. All parameters were not changed (as default) what can I do to perform that task?
Does this problem depend on the parameters ? What installation directory of the tagger must be set in the taggerBinary parameter?

A: First you have to create a new StanfordPOSTaggerPR in GATE and initialize the Tagger with the arabic.tagger model provided with the StanfordTagger.
The last version of GATE is the 8.0 and it uses the StanfordTagger 3.4. So you'll have to download the models provided with this version.

Next, you have to create a corpus pipeline with a SentenceSplitter and a Tokeniser (I've tried with the UnicodeTokeniser and the RegExp SentenceSplitter):

Finally, try the pipeline with a sample file:


text:
Q: How do I load and edit items (and also change the size of columns in code) into a datagrid in WPF (from a file) I've been dealing with issues loading and editing items from a datagrid in WPF.
Recently (about a month or so) I've made a question on this forum regarding saving and adding items into a datagrid (or listview when I first answered the question, then moved to a datagrid which is basically the same I suppose? but there's grids and you can edit items directly, just like excel. I think those are the main differences but correct me if I'm wrong).
Anyway, this is the code I have (saving and adding items into the datagrid): https://pastebin.com/HdC9dsJg
Basically, what I have at the moment to open (which doesn't work) is this:
Private DATABASE_QuantidadeAlimentos As Integer

'DATABASE_QuantidadeAlimentos (int) is how many Alimentos there are in the file
'PATH_DATABASE includes the folder name and the file location
Private Sub DATABASE_Abrir()
    Try
        Dim sb As New StringBuilder
        Dim path() As String = IO.File.ReadAllLines(PATH_DATABASE)
        Dim lines As String

        For Each line In lines
            Dim item As STRUCTURE_Alimento(lines)
            sb.AppendLine($"{item.Categoria}|{item.Alimento}|{item.Calorias}|{item.Proteinas}|{item.Hidratos}|{item.Lipidos}|{item.Gorduras}|{item.Quantidade}")
            DATABASE_Alimentos.Add(New STRUCTURE_Alimento)
            DATABASE_QuantidadeAlimentos += 1
            If DATABASE_QuantidadeAlimentos = 1 Then
                StatusBarAlimentos.Content = DATABASE_QuantidadeAlimentos & " Alimento"
            Else
                StatusBarAlimentos.Content = DATABASE_QuantidadeAlimentos & " Alimentos"
            End If
        Next
    Catch ex As Exception
        MsgBox("Erro: " & ex.Message, vbCritical, "Erro")
        End
    End Try
End Sub

Basically, what I was trying to do is:
For each line found in the text file, add a line in the datagrid. Then, inside that line, load the column details accordingly.
Right now, this is what I need to do:

*

*Load items from the (text) file we just created in code;

*Edit selected item directly from the datagrid and, after the changes are made, bind it to the 'ObservableCollection' we have (I believe that's what I have to do anyway, but you get the point);

*Resize columns in vb.net code.

Also, I don't really know what's the purpose of these lines of code:
        Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

I'm assuming it'll check if the properties changed and if yes, it'll raise an event but how do I actually implement it?
Thanks


text:
Q: Hibernate: best way to acquire rows sequentually I have a simple problem. I have a DB table with some data and sequential numbers. And several nodes pointing to database.
I need every node to guarantee that this and only this node picks one row with minimal sequential number at the moment of time.
What is the best way to do this in hibernate?
The first thing that I've done is to execute query with UPGRADE NOWAIT clause, and then try to update the row. Otherwise if catching LockAcquisitionException - retry it with some timeout.
while (retryCount < MAX_RETRY_ATTEMPTS) {
  try {
      Object obj = session().get(MyObject.class, stringId, LockMode.UPGRADE_NOWAIT);
      //Acquire this row somehow
  } catch (LockAcquisitionException | OptimisticLockException | StaleObjectStateException  e) {
      retryCount = handleException(retryCount, e);
  }
}

But this way is error prone - how much times should I retry and with which interval?
I would rather to find better way with guaranteed sequential lock. But have no idea how to do this.

A: Consider using LockMode.PESSIMISTIC_FORCE_INCREMENT, and release the lock with transaction commit.


text:
Q: Fatal error memory exhausted Zend Pdo I am having an error with memory while browsing my site - my server has increased memory allocation to a large enough level (I think).
Does anyone know why I'm getting these errors whilst browsing? After a local cache clear I can access the site again but doesn't seem right to me, here are two errors I get individually at different times;

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 8192 bytes) in lib/Zend/Db/Statement/Pdo.php on line 228
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 32 bytes) in lib/Zend/Db/Statement/Pdo.php on line 235

My code for Pdo.php below;
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Statement
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * @see Zend_Db_Statement
 */
#require_once 'Zend/Db/Statement.php';

/**
 * Proxy class to wrap a PDOStatement object.
 * Matches the interface of PDOStatement.  All methods simply proxy to the
 * matching method in PDOStatement.  PDOExceptions thrown by PDOStatement
 * are re-thrown as Zend_Db_Statement_Exception.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Statement
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (deleted link)
 * @license    deleted link     New BSD License
 */
class Zend_Db_Statement_Pdo extends Zend_Db_Statement implements IteratorAggregate
{

    /**
     * @var int
     */
    protected $_fetchMode = PDO::FETCH_ASSOC;

    /**
     * Prepare a string SQL statement and create a statement object.
     *
     * @param string $sql
     * @return void
     * @throws Zend_Db_Statement_Exception
     */
    protected function _prepare($sql)
    {
        try {
            $this->_stmt = $this->_adapter->getConnection()->prepare($sql);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Bind a column of the statement result set to a PHP variable.
     *
     * @param string $column Name the column in the result set, either by
     *                       position or by name.
     * @param mixed  $param  Reference to the PHP variable containing the value.
     * @param mixed  $type   OPTIONAL
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function bindColumn($column, &$param, $type = null)
    {
        try {
            if ($type === null) {
                return $this->_stmt->bindColumn($column, $param);
            } else {
                return $this->_stmt->bindColumn($column, $param, $type);
            }
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Binds a parameter to the specified variable name.
     *
     * @param mixed $parameter Name the parameter, either integer or string.
     * @param mixed $variable  Reference to PHP variable containing the value.
     * @param mixed $type      OPTIONAL Datatype of SQL parameter.
     * @param mixed $length    OPTIONAL Length of SQL parameter.
     * @param mixed $options   OPTIONAL Other options.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    protected function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
    {
        try {
            if ($type === null) {
                if (is_bool($variable)) {
                    $type = PDO::PARAM_BOOL;
                } elseif ($variable === null) {
                    $type = PDO::PARAM_NULL;
                } elseif (is_integer($variable)) {
                    $type = PDO::PARAM_INT;
                } else {
                    $type = PDO::PARAM_STR;
                }
            }
            return $this->_stmt->bindParam($parameter, $variable, $type, $length, $options);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Binds a value to a parameter.
     *
     * @param mixed $parameter Name the parameter, either integer or string.
     * @param mixed $value     Scalar value to bind to the parameter.
     * @param mixed $type      OPTIONAL Datatype of the parameter.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function bindValue($parameter, $value, $type = null)
    {
        if (is_string($parameter) && $parameter[0] != ':') {
            $parameter = ":$parameter";
        }

        $this->_bindParam[$parameter] = $value;

        try {
            if ($type === null) {
                return $this->_stmt->bindValue($parameter, $value);
            } else {
                return $this->_stmt->bindValue($parameter, $value, $type);
            }
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Closes the cursor, allowing the statement to be executed again.
     *
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function closeCursor()
    {
        try {
            return $this->_stmt->closeCursor();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Returns the number of columns in the result set.
     * Returns null if the statement has no result set metadata.
     *
     * @return int The number of columns.
     * @throws Zend_Db_Statement_Exception
     */
    public function columnCount()
    {
        try {
            return $this->_stmt->columnCount();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Retrieves the error code, if any, associated with the last operation on
     * the statement handle.
     *
     * @return string error code.
     * @throws Zend_Db_Statement_Exception
     */
    public function errorCode()
    {
        try {
            return $this->_stmt->errorCode();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Retrieves an array of error information, if any, associated with the
     * last operation on the statement handle.
     *
     * @return array
     * @throws Zend_Db_Statement_Exception
     */
    public function errorInfo()
    {
        try {
            return $this->_stmt->errorInfo();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Executes a prepared statement.
     *
     * @param array $params OPTIONAL Values to bind to parameter placeholders.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function _execute(array $params = null)
    {
        try {
            if ($params !== null) {
                return $this->_stmt->execute($params);
            } else {
                return $this->_stmt->execute();
            }
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            $message = sprintf('%s, query was: %s', $e->getMessage(), $this->_stmt->queryString);
            throw new Zend_Db_Statement_Exception($message, (int) $e->getCode(), $e);
        }
    }

    /**
     * Fetches a row from the result set.
     *
     * @param int $style  OPTIONAL Fetch mode for this fetch operation.
     * @param int $cursor OPTIONAL Absolute, relative, or other.
     * @param int $offset OPTIONAL Number for absolute or relative cursors.
     * @return mixed Array, object, or scalar depending on fetch mode.
     * @throws Zend_Db_Statement_Exception
     */
    public function fetch($style = null, $cursor = null, $offset = null)
    {
        if ($style === null) {
            $style = $this->_fetchMode;
        }
        try {
            return $this->_stmt->fetch($style, $cursor, $offset);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Required by IteratorAggregate interface
     *
     * @return IteratorIterator
     */
    public function getIterator()
    {
        return new IteratorIterator($this->_stmt);
    }

    /**
     * Returns an array containing all of the result set rows.
     *
     * @param int $style OPTIONAL Fetch mode.
     * @param int $col   OPTIONAL Column number, if fetch mode is by column.
     * @return array Collection of rows, each in a format by the fetch mode.
     * @throws Zend_Db_Statement_Exception
     */
    public function fetchAll($style = null, $col = null)
    {
        if ($style === null) {
            $style = $this->_fetchMode;
        }
        try {
            if ($style == PDO::FETCH_COLUMN) {
                if ($col === null) {
                    $col = 0;
                }
                return $this->_stmt->fetchAll($style, $col);
            } else {
                return $this->_stmt->fetchAll($style);
            }
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Returns a single column from the next row of a result set.
     *
     * @param int $col OPTIONAL Position of the column to fetch.
     * @return string
     * @throws Zend_Db_Statement_Exception
     */
    public function fetchColumn($col = 0)
    {
        try {
            return $this->_stmt->fetchColumn($col);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Fetches the next row and returns it as an object.
     *
     * @param string $class  OPTIONAL Name of the class to create.
     * @param array  $config OPTIONAL Constructor arguments for the class.
     * @return mixed One object instance of the specified class.
     * @throws Zend_Db_Statement_Exception
     */
    public function fetchObject($class = 'stdClass', array $config = array())
    {
        try {
            return $this->_stmt->fetchObject($class, $config);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Retrieve a statement attribute.
     *
     * @param integer $key Attribute name.
     * @return mixed      Attribute value.
     * @throws Zend_Db_Statement_Exception
     */
    public function getAttribute($key)
    {
        try {
            return $this->_stmt->getAttribute($key);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Returns metadata for a column in a result set.
     *
     * @param int $column
     * @return mixed
     * @throws Zend_Db_Statement_Exception
     */
    public function getColumnMeta($column)
    {
        try {
            return $this->_stmt->getColumnMeta($column);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Retrieves the next rowset (result set) for a SQL statement that has
     * multiple result sets.  An example is a stored procedure that returns
     * the results of multiple queries.
     *
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function nextRowset()
    {
        try {
            return $this->_stmt->nextRowset();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Returns the number of rows affected by the execution of the
     * last INSERT, DELETE, or UPDATE statement executed by this
     * statement object.
     *
     * @return int     The number of rows affected.
     * @throws Zend_Db_Statement_Exception
     */
    public function rowCount()
    {
        try {
            return $this->_stmt->rowCount();
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Set a statement attribute.
     *
     * @param string $key Attribute name.
     * @param mixed  $val Attribute value.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function setAttribute($key, $val)
    {
        try {
            return $this->_stmt->setAttribute($key, $val);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Set the default fetch mode for this statement.
     *
     * @param int   $mode The fetch mode.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function setFetchMode($mode)
    {
        $this->_fetchMode = $mode;
        try {
            return $this->_stmt->setFetchMode($mode);
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

}

A: You can add the following in index.php - make sure the log file path is correct
function shutdownCapture() {
    global $lastQueryString;
    $error = error_get_last();
    if ($error !== null && strpos($error['message'], 'Allowed memory size') !== false) {
      file_put_contents(MAGENTO_ROOT.'/var/log/oom.log', print_r(array($lastQueryString, $_REQUEST, $_SERVER, $error), true), FILE_APPEND);
      mail('info@examplecom', 'Server Memory Error', print_r(array($lastQueryString, $_REQUEST, $_SERVER, $error), true), 'Cc: mycolleague@example.com');
    }
}
register_shutdown_function('shutdownCapture');

and set these variables in the last reported function where the error occurs
+       global $lastQueryString;
+       $lastQueryString = $this->_stmt->queryString;

This excellent description comes from Sonassi
https://www.sonassi.com/blog/capturing-memory-exhaustion-in-magento

A: When I made sure the cronjob was able to run -> the error disappears.
Greets


text:
Q: Compiling Ruby on Mac OS X Snow Leopard I am trying to follow this tutorial, on the subject of compiling ruby and rubygems on Snow Leopard:
http://hivelogic.com/articles/compiling-ruby-rubygems-and-rails-on-snow-leopard
I have added this to my ~/.profile:
export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"

But if I write: echo $PATH I get:
/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin

But in tutorial it says:

You should see /usr/local/bin at the
  beginning of the line returned by the
  system.

I have installed macports sometime ago and plenty of other software, perhaps it has changed the path.
Anyway, I have tried to proceed with the installation, so I have built ruby, I did:
./configure --enable-shared --enable-pthread CFLAGS=-D_XOPEN_SOURCE=1
make
sudo make install
cd ..

But when I do which ruby I get:
/usr/bin/ruby

And according to the tutorial that's wrong. Also if I do ruby -v I get the older version of ruby that was preinstalled on Snow Leopard and not the one I've compiled.
Thanks.
UPD:
This is content of my ~/.profile:
export PYTHONPATH="/Users/m/djangocode:$PYTHONPATH"

alias hibernateon="sudo pmset -a hibernatemode 5"
alias hibernateoff="sudo pmset -a hibernatemode 3"

export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"

I have deleted ~/.bash_profile, so it has no impact.
Here is the content of /etc/bashrc:
# System-wide .bashrc file for interactive bash(1) shells.
if [ -z "$PS1" ]; then
   return
fi

PS1='\h:\W \u\$ '
# Make bash check its window size after a process completes
shopt -s checkwinsize

and /etc/profile:
# System-wide .profile for sh(1)

if [ -x /usr/libexec/path_helper ]; then
    eval `/usr/libexec/path_helper -s`
fi

if [ "${BASH-no}" != "no" ]; then
    [ -r /etc/bashrc ] && . /etc/bashrc
fi

I think their contents are Mac OS X defaults. I never touched these.
If I open terminal up and type echo $PATH I still get:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin

But if I do: source ~/.profile then I get what I need:
misha-macbookpro:~ m$ . ~/.profile
misha-macbookpro:~ m$ echo $PATH
/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin

And there is no ~/.bashrc file.
It seems that ~/.profile doesn't get "sourced" on terminal's start up. What can cause that?

A: You should seriously consider Homebrew

A: set something like this in your ~/.bash_profile:
PATH=/usr/local/bin:/opt/local/bin:/opt/local/sbin:$PATH

MacPorts is already changing your $PATH in that file, so make your modifications there (MacPorts is the /opt/local tree)

A: Apple's Terminal uses the ~/.bash_profile, not a .bashrc nor a .profile.  Yes, its a bit annoying.


text:
Q: How to go from DBF files to SQL Server 2008? I have an application that uses DBF files and I need to import them to SQL Server 2008. However, I also need to modify some of the data along the way and some columns will be added to tables while others will be deprecated.
So far I'm using DBF -> Access -> MS Migration Assistant -> SQL Server 2008. But I think that there has to be a better way to handle it. I'd like to get away from the Migration Assistant because it doesn't let you modify the data when you import it.

A: I was able to import DBF into SQL Server 2008 by using the information at this link.
In particular I:

*

*Used Import/Export wizard, selecting the "Microsoft Office 12.0 Access Database Engine OLE DB Pro..." as the Data source in the dropdown.

*Opened the Properties dialog for the Access OLE DB connection.

*Specified the folder containg the DBFs as the Data Source.

*Set Extended Properties to "dBASE 5.0"

I then set destination as my local sql server and upon hitting next was able to see each DBF file in the folder as a possible table/view to import from. Clicking on them created the similarly named table in the specified database.

A: It seems you're out of luck :-(
See this note:

Note: In SQL Server 2005, the SQL
  Server Import and Export Wizard does
  not support importing from or
  exporting to dBASE or other DBF files.
  To import DBF files, first use
  Microsoft Access or Microsoft Excel to
  import the data from DBF files into an
  Access database or Excel spreadsheets.
  Then, use the SQL Server Import and
  Export Wizard to import the Access
  database or Excel spreadsheets that
  contain the data from the DBF files.

Microsoft SQL Server 2005 Books Online, Choose a Data Source (Import and Export Wizard)
But maybe this other Stackoverflow question can be of help??
How to import a DBF file in SQL Server
Or check out some commercial and/or shareware tools for the job

*

*EMS Data Import for SQL Server

*DBF to SQL Converter seems to convert DBF file content into SQL scripts

*Full Convert Enterprise

A: Since you apparently just want to import the data into SQL Server, I'd just use SQL Server's Import and Export Data, which will work with any data source for which you have an ODBC driver.

A: From Books Online it appears that while the import/export wizard won't let you use a .dbf file, SSIS can be configured to use one:

To configure a connection manager to connect to a dBASE or other DBF
  file Add a new OLE DB connection manager to the package. For more
  information, see How to: Add or Delete a Connection Manager in a
  Package.
On the Connection page of the Connection Manager dialog box, select
  Native OLE DB\Microsoft Jet 4.0 OLE DB Provider as the Provider.
When working with DBF files, the folder represents the database, and
  the individual DBF files represent tables. Therefore the Database file
  name text box must contain the path of the folder where the DBF file
  resides, and must not include the file name itself. You can type or
  paste in a folder path, or you can use the Browse button to select
  your DBF file, and then remove the file name from the end of the
  folder path.
On the All page of the Connection Manager dialog box, enter dBASE III,
  dBASE IV, or dBASE 5.0, as appropriate, as the value of Extended
  Properties.
Click Test Connection to validate the values that you have entered.
  You should see the message, "Test connection succeeded." Click OK to
  close the message box.
Click OK to save the configuration for the connection manager.
To use your connection manager in the data flow of the package, select
  an OLE DB source or destination and configure it to use the connection
  manager that you created by using the preceding steps.


text:
Q: Fitting multiple data sets using scipy.optimize with the same parameters I am trying to write a code that would fit multiple (>100) data sets with the same parameters.
For a simple example:
Suppose I have 4 different data sets that are supposed to approximately follow the function y(x)=A*Sin(bx+c)+dx. They all have the same parameters a,b,and d. The only parameter that is different is c (phase), but for each data set, I know exactly what c should be.
Now I want to fit all 4 of those functions simultaneously and get one set of fit parameters a,b and d out.
Here I wrote a code that fits each of the functions separately and gives me 4 different sets of parameters, which is not what I am looking for.
Thank you in advance for any help.
from scipy import optimize
import matplotlib
from matplotlib import pyplot as plt
from scipy import *

Mat_ydata=[]
Mat_angle=[]
Mat_xdata=[]

defining a function for fitting
def sin_func(x,a,b,c,d):
   return a*sin(b*x+c)+d*x

Generating some data: 4 sine functions with the same amplitude,frequency and linear offset, but each has different phase, that we know already. Also each is defined over different range. The x and y corrdinates of the functions are stored in the lists of lists Mat_ydata and Mat_xdata. The phase is stored in the list Mat_phase
for phase in range(0,181,60):
    angle=float(phase)/180*pi
    num_points=phase+50
    xdata=linspace(num_points/10,num_points/5, num_points)
    ydata=2.11*sin(pi/2*xdata+angle)+3.16*xdata+2*((0.5-rand(num_points))*exp(2*rand(num_points)**2))
    Mat_angle.append(angle)
    Mat_ydata.append(ydata)
    Mat_xdata.append(xdata)

Here is fitting. I am fitting each function separately right now and therefore getting different values for phase, amplitude and linear offset for each of them. I would like to fit them all together. In the end I also plot data and fits.
for i in range(0,len(Mat_angle)):
    fitfunc = lambda p, x: sin_func(x,p[0],p[1],Mat_angle[i],p[2])
    errfunc = lambda p, x, y: fitfunc(p, x) - y
    p0 = [2,1.5,3]
    p1, success = optimize.leastsq(errfunc, p0[:], args=(Mat_xdata[i], Mat_ydata[i]))
    print p1
    plt.plot(Mat_xdata[i],Mat_ydata[i],'o',Mat_xdata[i],fitfunc(p1,Mat_xdata[i]),'-')
plt.show()

A: I have actually figured it out in the last couple of days. I'll provide the code in case it may be of interest to anyone. I also found that fitting sine functions is pretty hard, so I changed my fake data to Lorentzians.
Importing modules and generating fake data, that will be kept in the the lists of lists:
from scipy import optimize
import matplotlib
from matplotlib import pyplot as plt
from scipy import *
import numpy as np

Mat_ydata=[]
Mat_angle=[]
Mat_xdata=[]

for c in range(0,100,20):
    num_points=c+100
    xdata=linspace(0,num_points/2, num_points)
    ydata=5.1/((xdata-c)**2+2.1**2)+0.05*((0.5rand(num_points))*exp(2*rand(num_points)**2))
    Mat_angle.append(c)
    Mat_ydata.append(ydata)
    Mat_xdata.append(xdata)

Defining the fitting function and the error function:
def lor_func(x,c,par):
    a,b,d=par
    return a/((x-c)**2+b**2)

def err (p,c,x,y):
    return lor_func(x,c,p)-y

def err_global(p,Mat_a,Mat_x,Mat_y):
    err0=[]
    for i in range(0, len(Mat_a)):
        errc=err(p,Mat_a[i],Mat_x[i],Mat_y[i])
        err1=np.concatenate((err0,errc))
        err0=err1
    return err0

Actual fitting and displaying results:
p_global=[1,1,1]
p_best,success=optimize.leastsq(err_global, p_global,args=(Mat_angle,Mat_xdata,Mat_ydata),maxfev=40000)
toplot=[]
for i in range(0,len(Mat_angle)):
    toplot.append(lor_func(Mat_xdata[i],Mat_angle[i],p_best))
err_toplot=err_global(p_best,Mat_angle,Mat_xdata,Mat_ydata)
print p_best

for i in range(0,len(Mat_angle)):
    plt.plot(Mat_xdata[i],Mat_ydata[i],'o',Mat_xdata[i],toplot[i],'-')
plt.show()

And here is what it displays:


text:
Q: Multiple vhost connection inside same project (Subscribe / Publish) Our requirement is like below :-

*

*Exchange 1 is a topic exchange and queue 1 is bound to it. It is on VHOST 1.

*Application is subscribed to the queue 1. It processes the message of queue 1. After processing of queue 1 message, we want to publish next message to different exchange which is on VHOST 2 (different rabbit connection)
I have below questions :-
a) Is it possible to implement this without federation ?a
b) In a same application, Can I maintain 2 different rabbit connections ?
We are using using EasynetQ as a client to connect with rabbitmq.
Can you please share some sample on this.
Thanks in advance.

A: a) Yes, you can also create a shovel between vhosts, which is simpler than a federation
b) Yes I don't see a problem with creating multiple IBus instances, as long as you use different DI (sub) containers per bus instance, so there's an added complexity.

A: Here is how I handle multiple connections. I can't find a solution directly from EasyNetQ. I don't use the default DI adaptors for MS DI. And I only use the advance api and inject the service I need manually. So far it seems working but it needs more test for sure.
in startup.cs / ConfigureServices
            services.AddBusStation(busStationBuilder =>
            {
                // inject IBusStation and get the bus thru name
                appSettings.RabbitMQSettings.Connections.ForEach(c =>
                {
                    var taskQueueBus = RabbitHutch.CreateBus(c.ConnectionString, CustomServiceRegister.ServiceRegisterAction());
                    c.Exchanges.ForEach(async e =>
                    {
                        await taskQueueBus.Advanced.ExchangeDeclareAsync(e.Name, e.Type, e.Durable, e.AutoDelete);
                    });
                    busStationBuilder.Add(c.Name, taskQueueBus.Advanced);
                    busStationBuilder.AddDefaultBus(taskQueueBus);
                });
            });

    public interface IBusStation
    {
        IBus DefualtBus { get; }
        IAdvancedBus Get(string busName);
        void Add(string busName, IAdvancedBus advancedBus);
        void Add(IBus bus);
    }

    public class BusStation : IBusStation
    {
        private Dictionary<string, IAdvancedBus> BusList { get; set; } = new Dictionary<string, IAdvancedBus>();
        public IBus DefualtBus { get; private set; }
        public IAdvancedBus Get(string busName)
        {
            if (BusList.TryGetValue(busName, out IAdvancedBus advancedBus))
            {
                return advancedBus;
            }
            return null;
        }
        public void Add(string busName, IAdvancedBus advancedBus)
        {
            BusList.Add(busName, advancedBus);
        }
        public void Add(IBus bus)
        {
            this.DefualtBus = bus;
        }
    }

    public class BusStationBuilder
    {
        private readonly IBusStation _BusStation;

        public BusStationBuilder(IServiceCollection services, IBusStation busStation)
        {
            this._BusStation = busStation;
            services.AddSingleton(busStation);
        }
        public BusStationBuilder Add(string busName, IAdvancedBus advancedBus)
        {
            _BusStation.Add(busName, advancedBus);
            return this;
        }
        public BusStationBuilder AddDefaultBus(IBus bus)
        {
            _BusStation.Add(bus);
            return this;
        }
    }

    public static class DependencyExtensions
    {
        public static IServiceCollection AddBusStation(this IServiceCollection services, Action<BusStationBuilder> builder)
        {
            var busStationBuilder = new BusStationBuilder(services, new BusStation());
            builder(busStationBuilder);
            return services;
        }
    }

appsettings.json

    "RabbitMQSettings": {
        "DefaultQueue": "task.main",
        "Connections": [
            {
                "Name": "Task_Queue",
                "ConnectionString": "host=192.168.123.123;virtualHost=/;username=admin;password=password123;prefetchCount=1;persistentMessages=true;publisherConfirms=true",
                "Exchanges": [
                    {
                        "Name": "Direct_Task_Queue",
                        "Type": "direct",
                        "Passive": false,
                        "Durable": true,
                        "AutoDelete": false,
                        "Internal": false,
                        "AlternateExchange": null,
                        "Delayed": false
                    }
                ]
            }
        ]
    },


text:
Q: Send email with PHP from html on subscribe with the same script I want to send an email confirmation with PHP when a user subscribes in my HTML page. I have a redirect page but I need to sent an email and let him know that he did subscribe. Here is my php. Can I do it fro the same php?
<?php
/* Set e-mail recipient */
$myemail  = "example@domain";
$subject  = "You have a new subscriber!";

/* Check all form inputs using check_input function */
$email    = check_input($_POST['email']);

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}

/* Let's prepare the message for the e-mail */
$message = "Hello!

An email has been submitted by:

E-mail: $email

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the success page */
header('Location: success.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
?>

    Please correct the following error:

    <?php echo $myError; ?>

<?php
exit();
}
?>

This the php I'm using! Can anyone help!!!!
Thanks in advanced

A: code snippet for sending mail
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

$message can be a html markup
If you are looking for some thirdparty way
https://github.com/Synchro/PHPMailer


text:
Q: How to close popup window onClick of button and onTouch of outside in android I tried like below
popupMoreWindow.setBackgroundDrawable(new BitmapDrawable());
popupMoreWindow.setOutsideTouchable(true);

if(popupOpened) {
    popupMoreWindow.dismiss();
    popupOpened = false;
} else {
    popupMoreWindow.showAsDropDown(custLookUpRowowHolder.btnMore, 150, 5);
    popupOpened = true;
}

*

*It was closing popup window, but not working for button onClick.

A: *

*To close the popup window on click of button and on click of outside, follow as below

*

*The touch interceptor and dismiss the popup when action is MotionEvent. ACTION_OUTSIDE Set the popup to be focusable using setFocusable(true)

*Setting focusable ensures that popup can grab outside touch events and since it will also capture the click on the menuitem or a button, It ensures that popup is not launched again if it is already showing.

*And code snippet that fullfills ur requirement should be as below.

btn.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        if (window == null) {
            View contentView = getLayoutInflater(null).inflate(R.layout.popup_menu, null);
            window = new PopupWindow(contentView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawable(new BitmapDrawable(getResources(), ""));

            window.setOutsideTouchable(true);
            window.setFocusable(true);
            window.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
                        window.dismiss();
                        return true;
                    }
                    return false;
                }
            });
        }

        window.showAsDropDown(getActivity().findViewById(R.id.action_open_popup));
        return true;
    }
});

`


text:
Q: Htaccess rewrite condicion url with dash I'm having trouble to make this htaccess work
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /([temp|ox|cond|new-url]+)/
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ graph.php?grap=$1&time=$2 [NC,L]

Before adding new-url condition to the rewrite condition it was working OK
I also tried to put new\-url and new/-url but doesn't work either
What I'm doing wrong?

A: I think there are a few errors in your file.
First, ([temp|ox|cond|new-url]+) is the same as ([cdelmnoprtuwx|-]+). Here you're searching for characters, not words. If I understand, you're looking for urls starting by either /temp/, /ox/, /cond/ or new-url. So I would use this condition:
RewriteCond %{REQUEST_URI} ^/(temp|ox|cond|new-url)/

Second, when you match new-url, there's a dash. But your next rule doesn't accept any dash! Change for this one:
RewriteRule ^([a-z-]+)/([a-z-]+)$ graph.php?grap=$1&time=$2 [NC,L]

Notes:

*

*I used [a-z] instead of [A-Za-z] as your rule doesn't take case in account ([NC])

*I added the dash at the end of the character range: [a-z-]

A: I think you need to escape the - inside character class.
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /([temp|ox|cond|new\-url]+)/
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ graph.php?grap=$1&time=$2 [NC,L]

If that doesnt solve the issue, you can use a simple pattern :
RewriteCond %{REQUEST_URI} /(temp|ox|cond|new-url)/?


text:
Q: How do I interact with an external search API in Rails5 using the HTTParty gem? How can I create an app in Rails that will let me input search parameters, which are then passed to an external API to perform the search, and then display those results in my app. I'm trying to use HTTParty to achieve this but I'm a bit lost. I've tried creating a class method in app/services and accessing it in my controller, and then calling the instance variable in my view. At the moment it's throwing a Routing Error uninitialized constant ResultsController::Api. Would be super grateful for some help.
services/Api.rb
class Api
  include HTTParty
  base_uri "search.example.com"
  attr_accessor :name

  def initialize(name)
    self.name = name
  end

  def self.find(name)
    response = get("/results&q=#{name}")
    self.new(response["name"])
  end

results_controller.rb
class ResultsController < ApplicationController
  include Api

  def index
    @results = Api.find('test')
  end
end

Routes:
Rails.application.routes.draw do
  resources :results
  root 'results#index'
end

A: You're almost right, just need some changes here. At first, rename Api.rb to api.rb - by convention, all files should be named in lower snake_case
class Api
  include HTTParty
  base_uri "http://search.spoonflower.com/searchv2"

  def find(name)
    self.class.get("/designs", query: { q: name }).parsed_response
  end
end

class ResultsController < ApplicationController
  def index
    # here you get some json structure that you can display in the view
    @results = Api.new.find('test')['results']
  end
end


text:
Q: Ngrx store is updated but not displayed I am currently running through a ngrx/store + RxJS6 course and have made several adjustments to bring them up to date with the latest version. This however means that the code in the solution looks different then mine.
The problem
My store successfully gets all the paprticipants and updates the state, however when trying to update the variable name to display the name of a participant with an userId of 3, nothing is updated or an error is thrown.

Thread-section.component.ts
export class ThreadSectionComponent implements OnInit {
userName: string;

constructor(private threadsService: ThreadsService, private store: Store<ApplicationState> ) {
    store
        .pipe(
            tap(state => console.log(state.storeData)),
            filter(state => typeof state.storeData !== 'undefined')
        )
        .subscribe(
        state => {
            this.userName = state.storeData.participants[state.uiState.userId].name;
        }
    );

}

ngOnInit() {
    this.threadsService.loadUserThreads()
        .subscribe(allUserData => this.store.dispatch(
            new LoadUserThreadAction(allUserData)
        ));
}

Reducers.ts
   export const reducers = {
  storeReducers: storeReducer
};

function storeReducer(state: ApplicationState =  INITIAL_APPLICATION_STATE, action: Action): ApplicationState {
  switch (action.type) {
      case LOAD_USER_THREADS_ACTION:
        return handleLoadUserThreadsAction(state, action);
      default:
        return state;
  }
}
function handleLoadUserThreadsAction(state: ApplicationState, action: LoadUserThreadAction): ApplicationState {
  const userData = action.payload;
  const newState: ApplicationState = Object.assign({}, state);
  newState.storeData = {
      participants: _.keyBy(action.payload.participants, 'id'),
      messages: _.keyBy(action.payload.messages, 'id'),
      threads: _.keyBy(action.payload.threads, 'id')
  };
  return newState;
}

Participant.ts
   export interface Participant {
    id: number;
    name: string;
}

Application-state.ts
import {INITIAL_UI_STATE, UiState} from './ui-state';
import {INTIAL_STORE_DATA, StoreData} from './store-data';
export interface ApplicationState {
    uiState: UiState,
    storeData: StoreData
}

export const INITIAL_APPLICATION_STATE: ApplicationState = {
    uiState: INITIAL_UI_STATE,
    storeData: INTIAL_STORE_DATA
};

Ui-state
export interface UiState {
    userId: number;
    currentThreadId: number;
}

export const INITIAL_UI_STATE: UiState = {
    userId: 3,
    currentThreadId: undefined
};

Store-data.ts
    export interface StoreData {
    participants: {[key: number]: Participant};
    threads: {[key: number]: Thread};
    messages: {[key: number]: Message};
}

export const INTIAL_STORE_DATA: StoreData = {
    threads: {},
    messages: {},
    participants: {}
};

Question:
My question to you guys is, why is my variable not updated? I've been thinking on the lines of an uncaught typeError, but the fact it doesn't display an error makes me think it's a logical mistake.


text:
Q: How to add a spinner in a fragment I'm trying to add a spinner in my fragment by using "double" instead of "String". I know, my code is not correct at all! But I came here to seek for another solution.
// Declaration
Spinner spinner;
double[] Array_note = {1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6};
ArrayAdapter<double> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_cofo, container,
false);

spinner = (Spinner)view.findViewById(R.id.Sp_F_Note);
adapter = new ArrayAdapter<ouble>(getActivity(),android.R.layout.simple_spinner_item,Array_note);
}

I hope someone can help me out :)

A: In array Adapter only class type is use can not use data type .
try to this code:
 List<Double> list=new ArrayList<>();
        double i=1.0;
        while(i<=6.0)
        {
            list.add(i);
            i=i+0.5;
        }

        ArrayAdapter<Double> arrayAdapter = new ArrayAdapter<Double>(getactivity(), android.R.layout.simple_list_item_1, list);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
        spinner.setAdapter(arrayAdapter);

Use this code it's help me show double value in spinner.